Skip to content

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

[#15192] fix(server): Allow catalog probes for dynamic-only providers (#15195)

roryqi34eef2751ebf
diff --git a/bundles/aliyun/src/main/java/org/apache/gravitino/oss/credential/OSSTokenProvider.java b/bundles/aliyun/src/main/java/org/apache/gravitino/oss/credential/OSSTokenProvider.java
index 3111498c12..817f5e55d7 100644
--- a/bundles/aliyun/src/main/java/org/apache/gravitino/oss/credential/OSSTokenProvider.java
+++ b/bundles/aliyun/src/main/java/org/apache/gravitino/oss/credential/OSSTokenProvider.java
@@ -21,12 +21,14 @@ package org.apache.gravitino.oss.credential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
import org.apache.gravitino.credential.OSSTokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* A lightweight credential provider for OSS. It delegates the actual credential generation to
* {@link OSSTokenGenerator} which is loaded via reflection to avoid classpath issues.
*/
-public class OSSTokenProvider extends CredentialProviderDelegator<OSSTokenCredential> {
+public class OSSTokenProvider extends CredentialProviderDelegator<OSSTokenCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/aliyun/src/test/java/org/apache/gravitino/oss/credential/TestCredentialProvider.java b/bundles/aliyun/src/test/java/org/apache/gravitino/oss/credential/TestCredentialProvider.java
index 0e8cd2fb74..bb0dd03ca3 100644
--- a/bundles/aliyun/src/test/java/org/apache/gravitino/oss/credential/TestCredentialProvider.java
+++ b/bundles/aliyun/src/test/java/org/apache/gravitino/oss/credential/TestCredentialProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.oss.credential;
import org.apache.gravitino.credential.OSSSecretKeyCredential;
import org.apache.gravitino.credential.OSSTokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -29,10 +30,12 @@ public class TestCredentialProvider {
@Test
void testCredentialProviderType() {
OSSTokenProvider ossTokenProvider = new OSSTokenProvider();
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, ossTokenProvider);
Assertions.assertEquals(
OSSTokenCredential.OSS_TOKEN_CREDENTIAL_TYPE, ossTokenProvider.credentialType());
OSSSecretKeyProvider ossSecretKeyProvider = new OSSSecretKeyProvider();
+ Assertions.assertFalse(ossSecretKeyProvider instanceof SupportsDynamicCredential);
Assertions.assertEquals(
OSSSecretKeyCredential.OSS_SECRET_KEY_CREDENTIAL_TYPE,
ossSecretKeyProvider.credentialType());
diff --git a/bundles/aws/build.gradle.kts b/bundles/aws/build.gradle.kts
index 207a51aa6f..549205d469 100644
--- a/bundles/aws/build.gradle.kts
+++ b/bundles/aws/build.gradle.kts
@@ -66,6 +66,9 @@ dependencies {
testImplementation(libs.hadoop3.client.runtime)
testImplementation(libs.junit.jupiter.api)
testImplementation(libs.junit.jupiter.params)
+ testImplementation(project(":core"))
+ testImplementation(libs.mockito.core)
+ testImplementation(libs.mockito.inline)
testRuntimeOnly(libs.junit.jupiter.engine)
}
diff --git a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/AwsIrsaCredentialProvider.java b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/AwsIrsaCredentialProvider.java
index 22f6f5d794..4db8562ad0 100644
--- a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/AwsIrsaCredentialProvider.java
+++ b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/AwsIrsaCredentialProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.s3.credential;
import org.apache.gravitino.credential.AwsIrsaCredential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* AWS IRSA credential provider that supports both basic IRSA credentials and fine-grained
@@ -56,7 +57,8 @@ import org.apache.gravitino.credential.CredentialProviderDelegator;
* directly)
* </ul>
*/
-public class AwsIrsaCredentialProvider extends CredentialProviderDelegator<AwsIrsaCredential> {
+public class AwsIrsaCredentialProvider extends CredentialProviderDelegator<AwsIrsaCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenProvider.java b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenProvider.java
index a90665b69c..05e9efd5ae 100644
--- a/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenProvider.java
+++ b/bundles/aws/src/main/java/org/apache/gravitino/s3/credential/S3TokenProvider.java
@@ -21,12 +21,14 @@ package org.apache.gravitino.s3.credential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
import org.apache.gravitino.credential.S3TokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* A lightweight credential provider for S3. It delegates the actual credential generation to {@link
* S3TokenGenerator} which is loaded via reflection to avoid classpath issues.
*/
-public class S3TokenProvider extends CredentialProviderDelegator<S3TokenCredential> {
+public class S3TokenProvider extends CredentialProviderDelegator<S3TokenCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/aws/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialContexts.java b/bundles/aws/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialContexts.java
new file mode 100644
index 0000000000..6e60038527
--- /dev/null
+++ b/bundles/aws/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialContexts.java
@@ -0,0 +1,185 @@
+/*
+ * 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.credential;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.connector.CatalogOperations;
+import org.apache.gravitino.connector.credential.PathContext;
+import org.apache.gravitino.connector.credential.SupportsPathBasedCredentials;
+import org.apache.gravitino.s3.credential.S3TokenProvider;
+import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.storage.IdGenerator;
+import org.apache.gravitino.storage.S3Properties;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.mockito.Answers;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.StsClientBuilder;
+import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
+import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
+import software.amazon.awssdk.services.sts.model.Credentials;
+
+/**
+ * Exercises the real dispatcher, providers and S3 generator, mocking only catalog paths and STS.
+ */
+public class TestCatalogCredentialContexts {
+ private static final NameIdentifier CATALOG = NameIdentifier.of("metalake", "catalog");
+ private static final NameIdentifier FILESET =
+ NameIdentifier.of("metalake", "catalog", "schema", "fileset");
+ private static final String PATH = "s3://bucket/warehouse/table";
+
+ /** Catalog probes have no authorized storage paths and must not request an STS token. */
+ @Test
+ public void testTokenOnlyCatalogProbeReturnsNoCredentials() {
+ try (Fixture fixture = new Fixture(false)) {
+ Assertions.assertInstanceOf(
+ S3TokenProvider.class,
+ fixture.manager.getCredentialProvider(S3TokenCredential.S3_TOKEN_CREDENTIAL_TYPE).get());
+ Assertions.assertTrue(fixture.manager.hasOnlyDynamicCredentialProviders());
+ Assertions.assertTrue(
+ fixture
+ .dispatcher
+ .getCredentials(fixture.catalog, CATALOG, CredentialPrivilege.READ)
+ .isEmpty());
+ verifyNoInteractions(fixture.sts);
+ }
+ }
+
+ /** Authorized mixed catalog requests return static credentials, without inventing token paths. */
+ @Test
+ public void testMixedCatalogProbeReturnsOnlyStaticCredentials() {
+ try (Fixture fixture = new Fixture(true)) {
+ Assertions.assertFalse(fixture.manager.hasOnlyDynamicCredentialProviders());
+ List<Credential> credentials =
+ fixture.dispatcher.getCredentials(fixture.catalog, CATALOG, CredentialPrivilege.READ);
+ Assertions.assertEquals(1, credentials.size());
+ S3SecretKeyCredential credential =
+ Assertions.assertInstanceOf(S3SecretKeyCredential.class, credentials.get(0));
+ Assertions.assertEquals("source-id", credential.accessKeyId());
+ Assertions.assertEquals("source-key", credential.secretAccessKey());
+ verifyNoInteractions(fixture.sts);
+ }
+ }
+
+ /**
+ * Token generation works when the dispatcher supplies the existing authorized path context.
+ *
+ * @param privilege the authorized fileset storage privilege
+ */
+ @ParameterizedTest
+ @EnumSource(CredentialPrivilege.class)
+ public void testPathCredentialsReachRealS3Generator(CredentialPrivilege privilege) {
+ try (Fixture fixture = new Fixture(false)) {
+ Assertions.assertTrue(
+ fixture.dispatcher.getCredentials(fixture.catalog, CATALOG, privilege).isEmpty());
+ verifyNoInteractions(fixture.sts);
+
+ List<Credential> credentials =
+ fixture.dispatcher.getCredentials(fixture.catalog, FILESET, privilege);
+ Assertions.assertEquals(1, credentials.size());
+ S3TokenCredential credential =
+ Assertions.assertInstanceOf(S3TokenCredential.class, credentials.get(0));
+ Assertions.assertEquals("session-id", credential.accessKeyId());
+ Assertions.assertEquals("session-token", credential.sessionToken());
+ ArgumentCaptor<AssumeRoleRequest> request = ArgumentCaptor.forClass(AssumeRoleRequest.class);
+ verify(fixture.sts).assumeRole(request.capture());
+ String policy = request.getValue().policy();
+ Assertions.assertTrue(policy.contains("arn:aws:s3:::bucket/warehouse/table/*"), policy);
+ Assertions.assertFalse(policy.contains("arn:aws:s3:::bucket/*"), policy);
+ Assertions.assertTrue(policy.contains("s3:GetObject"), policy);
+ Assertions.assertEquals(
+ privilege == CredentialPrivilege.WRITE, policy.contains("s3:PutObject"), policy);
+ }
+ }
+
+ private static class Fixture implements AutoCloseable {
+ private final StsClient sts = mock(StsClient.class);
+ private final CatalogCredentialManager manager;
+ private final BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ private final CredentialOperationDispatcher dispatcher =
+ new CredentialOperationDispatcher(
+ mock(CatalogManager.class), mock(EntityStore.class),
+ mock(IdGenerator.class), mock(SecretManager.class));
+
+ private Fixture(boolean mixed) {
+ Map<String, String> properties =
+ Map.of(
+ CredentialConstants.CREDENTIAL_PROVIDERS,
+ mixed ? "s3-token,s3-secret-key" : "s3-token",
+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,
+ "source-id",
+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,
+ "source-key",
+ S3Properties.GRAVITINO_S3_REGION,
+ "us-east-1",
+ S3Properties.GRAVITINO_S3_ROLE_ARN,
+ "arn:aws:iam::123456789012:role/vending");
+ StsClientBuilder builder = mock(StsClientBuilder.class, Answers.RETURNS_SELF);
+ when(builder.build()).thenReturn(sts);
+ when(sts.assumeRole(any(AssumeRoleRequest.class)))
+ .thenReturn(
+ AssumeRoleResponse.builder()
+ .credentials(
+ Credentials.builder()
+ .accessKeyId("session-id")
+ .secretAccessKey("session-key")
+ .sessionToken("session-token")
+ .expiration(Instant.now().plusSeconds(3600))
+ .build())
+ .build());
+ try (MockedStatic<StsClient> clients = mockStatic(StsClient.class)) {
+ clients.when(StsClient::builder).thenReturn(builder);
+ manager = new CatalogCredentialManager("catalog", properties);
+ }
+ when(catalog.catalogCredentialManager()).thenReturn(manager);
+ when(catalog.propertiesWithCredentialProviders()).thenReturn(properties);
+ CatalogOperations ops =
+ mock(
+ CatalogOperations.class,
+ Mockito.withSettings().extraInterfaces(SupportsPathBasedCredentials.class));
+ when(((SupportsPathBasedCredentials) ops).getPathContext(any()))
+ .thenReturn(List.of(new PathContext(PATH, S3TokenCredential.S3_TOKEN_CREDENTIAL_TYPE)));
+ when(catalog.ops()).thenReturn(ops);
+ }
+
+ /** Closes the real credential providers and their SDK client. */
+ @Override
+ public void close() {
+ manager.close();
+ }
+ }
+}
diff --git a/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestCredentialProvider.java b/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestCredentialProvider.java
index c0aaeaefcf..76e58d0f3b 100644
--- a/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestCredentialProvider.java
+++ b/bundles/aws/src/test/java/org/apache/gravitino/s3/credential/TestCredentialProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.s3.credential;
import org.apache.gravitino.credential.S3SecretKeyCredential;
import org.apache.gravitino.credential.S3TokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -29,10 +30,14 @@ public class TestCredentialProvider {
@Test
void testCredentialProviderType() {
S3TokenProvider s3TokenProvider = new S3TokenProvider();
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, s3TokenProvider);
Assertions.assertEquals(
S3TokenCredential.S3_TOKEN_CREDENTIAL_TYPE, s3TokenProvider.credentialType());
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, new AwsIrsaCredentialProvider());
+
S3SecretKeyProvider s3SecretKeyProvider = new S3SecretKeyProvider();
+ Assertions.assertFalse(s3SecretKeyProvider instanceof SupportsDynamicCredential);
Assertions.assertEquals(
S3SecretKeyCredential.S3_SECRET_KEY_CREDENTIAL_TYPE, s3SecretKeyProvider.credentialType());
}
diff --git a/bundles/azure/src/main/java/org/apache/gravitino/abs/credential/ADLSTokenProvider.java b/bundles/azure/src/main/java/org/apache/gravitino/abs/credential/ADLSTokenProvider.java
index 447ef31c5f..919cc05df4 100644
--- a/bundles/azure/src/main/java/org/apache/gravitino/abs/credential/ADLSTokenProvider.java
+++ b/bundles/azure/src/main/java/org/apache/gravitino/abs/credential/ADLSTokenProvider.java
@@ -21,12 +21,14 @@ package org.apache.gravitino.abs.credential;
import org.apache.gravitino.credential.ADLSTokenCredential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* A lightweight credential provider for ADLS. It delegates the actual credential generation to
* {@link ADLSTokenGenerator} which is loaded via reflection to avoid classpath issues.
*/
-public class ADLSTokenProvider extends CredentialProviderDelegator<ADLSTokenCredential> {
+public class ADLSTokenProvider extends CredentialProviderDelegator<ADLSTokenCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/azure/src/test/java/org/apache/gravitino/abs/credential/TestCredentialProvider.java b/bundles/azure/src/test/java/org/apache/gravitino/abs/credential/TestCredentialProvider.java
index 2a48d521a2..fc15fe24a6 100644
--- a/bundles/azure/src/test/java/org/apache/gravitino/abs/credential/TestCredentialProvider.java
+++ b/bundles/azure/src/test/java/org/apache/gravitino/abs/credential/TestCredentialProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.abs.credential;
import org.apache.gravitino.credential.ADLSTokenCredential;
import org.apache.gravitino.credential.AzureAccountKeyCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -29,10 +30,12 @@ public class TestCredentialProvider {
@Test
void testCredentialProviderType() {
ADLSTokenProvider adlsTokenProvider = new ADLSTokenProvider();
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, adlsTokenProvider);
Assertions.assertEquals(
ADLSTokenCredential.ADLS_TOKEN_CREDENTIAL_TYPE, adlsTokenProvider.credentialType());
AzureAccountKeyProvider azureAccountKeyProvider = new AzureAccountKeyProvider();
+ Assertions.assertFalse(azureAccountKeyProvider instanceof SupportsDynamicCredential);
Assertions.assertEquals(
AzureAccountKeyCredential.AZURE_ACCOUNT_KEY_CREDENTIAL_TYPE,
azureAccountKeyProvider.credentialType());
diff --git a/bundles/gcp/src/main/java/org/apache/gravitino/gcs/credential/GCSTokenProvider.java b/bundles/gcp/src/main/java/org/apache/gravitino/gcs/credential/GCSTokenProvider.java
index 580ebc0eb5..1da684adb3 100644
--- a/bundles/gcp/src/main/java/org/apache/gravitino/gcs/credential/GCSTokenProvider.java
+++ b/bundles/gcp/src/main/java/org/apache/gravitino/gcs/credential/GCSTokenProvider.java
@@ -21,12 +21,14 @@ package org.apache.gravitino.gcs.credential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
import org.apache.gravitino.credential.GCSTokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* A lightweight credential provider for GCS. It delegates the actual credential generation to
* {@link GCSTokenGenerator} which is loaded via reflection to avoid classpath issues.
*/
-public class GCSTokenProvider extends CredentialProviderDelegator<GCSTokenCredential> {
+public class GCSTokenProvider extends CredentialProviderDelegator<GCSTokenCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/gcp/src/test/java/org/apache/gravitino/gcs/credential/TestCredentialProvider.java b/bundles/gcp/src/test/java/org/apache/gravitino/gcs/credential/TestCredentialProvider.java
index 162e02c987..e43f966cac 100644
--- a/bundles/gcp/src/test/java/org/apache/gravitino/gcs/credential/TestCredentialProvider.java
+++ b/bundles/gcp/src/test/java/org/apache/gravitino/gcs/credential/TestCredentialProvider.java
@@ -20,6 +20,7 @@
package org.apache.gravitino.gcs.credential;
import org.apache.gravitino.credential.GCSTokenCredential;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -28,6 +29,7 @@ public class TestCredentialProvider {
@Test
void testCredentialProviderType() {
GCSTokenProvider gcsTokenProvider = new GCSTokenProvider();
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, gcsTokenProvider);
Assertions.assertEquals(
GCSTokenCredential.GCS_TOKEN_CREDENTIAL_TYPE, gcsTokenProvider.credentialType());
}
diff --git a/bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenProvider.java b/bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenProvider.java
index 531f96a38f..f1bb96ffa8 100644
--- a/bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenProvider.java
+++ b/bundles/tencent/src/main/java/org/apache/gravitino/cos/credential/COSTokenProvider.java
@@ -21,13 +21,15 @@ package org.apache.gravitino.cos.credential;
import org.apache.gravitino.credential.COSTokenCredential;
import org.apache.gravitino.credential.CredentialProviderDelegator;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
/**
* A lightweight credential provider for Tencent Cloud COS. It delegates the actual credential
* generation to {@link COSTokenGenerator}, which is loaded via reflection so that bundles without
* the Tencent Cloud STS SDK on the classpath do not fail at class loading time.
*/
-public class COSTokenProvider extends CredentialProviderDelegator<COSTokenCredential> {
+public class COSTokenProvider extends CredentialProviderDelegator<COSTokenCredential>
+ implements SupportsDynamicCredential {
@Override
public boolean supportsScheme(String scheme) {
diff --git a/bundles/tencent/src/test/java/org/apache/gravitino/cos/credential/TestCOSCredentialProviderSpi.java b/bundles/tencent/src/test/java/org/apache/gravitino/cos/credential/TestCOSCredentialProviderSpi.java
index 43f0707bcc..e7c298bf9e 100644
--- a/bundles/tencent/src/test/java/org/apache/gravitino/cos/credential/TestCOSCredentialProviderSpi.java
+++ b/bundles/tencent/src/test/java/org/apache/gravitino/cos/credential/TestCOSCredentialProviderSpi.java
@@ -23,6 +23,7 @@ import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import org.apache.gravitino.credential.CredentialProvider;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -35,6 +36,13 @@ import org.junit.jupiter.api.Test;
*/
public class TestCOSCredentialProviderSpi {
+ /** Checks that only token providers declare dynamic credential support. */
+ @Test
+ public void testDynamicCredentialCapability() {
+ Assertions.assertInstanceOf(SupportsDynamicCredential.class, new COSTokenProvider());
+ Assertions.assertFalse(new COSSecretKeyProvider() instanceof SupportsDynamicCredential);
+ }
+
@Test
void testCredentialProviderSpiRegistersBothCosProviders() {
Set<Class<?>> loaded = new HashSet<>();
diff --git a/common/src/main/java/org/apache/gravitino/credential/SupportsDynamicCredential.java b/common/src/main/java/org/apache/gravitino/credential/SupportsDynamicCredential.java
new file mode 100644
index 0000000000..733842f457
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/credential/SupportsDynamicCredential.java
@@ -0,0 +1,33 @@
+/*
+ * 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.credential;
+
+/**
+ * Marks a provider that issues dynamic credentials without exposing stored source credentials.
+ *
+ * <p>Catalog credential requests containing only providers with this capability require metadata
+ * access without static-secret privileges. Implementations must not return stored passwords, access
+ * keys, or other source credentials. Dynamic credentials must respect the authorization context;
+ * providers requiring storage paths must return no credentials for a pathless catalog request.
+ *
+ * <p>Providers without this capability retain the existing catalog secret-privilege checks,
+ * including implementations compiled against an earlier version of the credential provider SPI.
+ */
+public interface SupportsDynamicCredential extends CredentialProvider {}
diff --git a/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java b/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java
index fcfb9a4e43..e2fc2d99f2 100644
--- a/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java
+++ b/core/src/main/java/org/apache/gravitino/credential/CatalogCredentialManager.java
@@ -67,6 +67,17 @@ public class CatalogCredentialManager implements Closeable {
return Optional.ofNullable(credentialProviders.get(credentialType));
}
+ /**
+ * Returns whether every configured provider explicitly supports dynamic credentials.
+ *
+ * @return true if all configured providers support dynamic credentials, or no provider is
+ * configured
+ */
+ public boolean hasOnlyDynamicCredentialProviders() {
+ return credentialProviders.values().stream()
+ .allMatch(SupportsDynamicCredential.class::isInstance);
+ }
+
/**
* Returns whether a credential provider of this catalog supports the scheme of the path.
*
diff --git a/core/src/test/java/org/apache/gravitino/credential/DummyCredentialProvider.java b/core/src/test/java/org/apache/gravitino/credential/DummyCredentialProvider.java
index 99bc68feb9..67940eef7c 100644
--- a/core/src/test/java/org/apache/gravitino/credential/DummyCredentialProvider.java
+++ b/core/src/test/java/org/apache/gravitino/credential/DummyCredentialProvider.java
@@ -27,7 +27,7 @@ import javax.annotation.Nullable;
import javax.ws.rs.NotSupportedException;
import lombok.Getter;
-public class DummyCredentialProvider implements CredentialProvider {
+public class DummyCredentialProvider implements SupportsDynamicCredential {
Map<String, String> properties;
static final String CREDENTIAL_TYPE = "dummy";
diff --git a/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java b/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java
index e00324a60f..39cd0cc13b 100644
--- a/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java
+++ b/core/src/test/java/org/apache/gravitino/credential/TestCatalogCredentialManager.java
@@ -21,11 +21,40 @@ package org.apache.gravitino.credential;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
public class TestCatalogCredentialManager {
+ /**
+ * Checks capability queries against real configured providers, including an empty catalog.
+ *
+ * @param dynamic whether an explicitly dynamic provider is configured
+ * @param stored whether a static provider is configured
+ */
+ @ParameterizedTest
+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+ public void testHasOnlyDynamicCredentialProviders(boolean dynamic, boolean stored) {
+ List<String> providers = new ArrayList<>();
+ if (dynamic) {
+ providers.add(DummyCredentialProvider.CREDENTIAL_TYPE);
+ }
+ if (stored) {
+ providers.add(JdbcCredential.JDBC_CREDENTIAL_TYPE);
+ }
+ Map<String, String> properties =
+ ImmutableMap.of(
+ CredentialConstants.CREDENTIAL_PROVIDERS, String.join(",", providers),
+ JdbcCredential.GRAVITINO_JDBC_USER, "user",
+ JdbcCredential.GRAVITINO_JDBC_PASSWORD, "password");
+ try (CatalogCredentialManager manager = new CatalogCredentialManager("catalog", properties)) {
+ Assertions.assertEquals(!stored, manager.hasOnlyDynamicCredentialProviders());
+ }
+ }
@Test
void testSelectsStorageCredentialWhenJdbcProviderIsAlsoConfigured() {
diff --git a/core/src/test/java/org/apache/gravitino/credential/TestCredentialProvider.java b/core/src/test/java/org/apache/gravitino/credential/TestCredentialProvider.java
index 711cd30bdb..75011339c6 100644
--- a/core/src/test/java/org/apache/gravitino/credential/TestCredentialProvider.java
+++ b/core/src/test/java/org/apache/gravitino/credential/TestCredentialProvider.java
@@ -27,6 +27,16 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestCredentialProvider {
+ /** Checks that unmarked stored credential providers do not opt into metadata-only access. */
+ @Test
+ public void testStoredCredentialProvidersAreNotDynamic() {
+ Assertions.assertFalse(new JdbcCredentialProvider() instanceof SupportsDynamicCredential);
+ Assertions.assertFalse(
+ new AwsSecretKeyCredentialProvider() instanceof SupportsDynamicCredential);
+ Assertions.assertFalse(
+ new DlfSecretKeyCredentialProvider() instanceof SupportsDynamicCredential);
+ }
+
@Test
void testCredentialProvider() {
Map<String, String> catalogProperties = ImmutableMap.of("a", "b");
diff --git a/docs/open-api/credentials.yaml b/docs/open-api/credentials.yaml
index cf18e4e491..3b11ebda64 100644
--- a/docs/open-api/credentials.yaml
+++ b/docs/open-api/credentials.yaml
@@ -31,10 +31,16 @@ paths:
operationId: getCredentials
description: >
Retrieves credentials for a catalog or fileset. When authorization is enabled,
- catalog credentials require metadata access plus both USE_SECRETS and
- INCLUDE_CREDENTIAL_SECRETS, or metalake ownership. Catalog credentials carry
- the source account's permissions and are not scoped to individual Gravitino
- tables. Fileset credentials use path-based authorization.
+ catalog credentials require metadata access. Unless every configured provider
+ explicitly implements SupportsDynamicCredential, the request additionally requires
+ both USE_SECRETS and INCLUDE_CREDENTIAL_SECRETS, or metalake ownership. Unmarked
+ providers retain these secret checks, including existing custom providers and
+ mixed dynamic and unmarked provider configurations. Catalog requests do not provide a
+ storage path: built-in path-only token providers return no catalog credentials,
+ so a token-only catalog probe succeeds with an empty credential list.
+ Static catalog credentials carry the source account's permissions and
+ are not scoped to individual Gravitino tables. Fileset credentials use
+ path-based authorization and supply the paths required to generate tokens.
responses:
"200":
description: Returns the list of credential objects associated with specified metadata object.
@@ -128,4 +134,4 @@ components:
}
},
]
- }
\ No newline at end of file
+ }
diff --git a/docs/security/access-control.md b/docs/security/access-control.md
index 86669fcafc..026dd86dea 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -205,8 +205,8 @@ sets the scope of the grant. Binding a privilege to a type not listed for it is
| `REGISTER_MODEL` | Metalake, Catalog, Schema | Register models in any schema in scope |
| `LINK_MODEL_VERSION` | Metalake, Catalog, Schema, Model | Link versions to any model in scope |
| `USE_MODEL` | Metalake, Catalog, Schema, Model | Read the metadata of, and download versions of, any model in scope |
-| `USE_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model | Call `getSecrets` (cloud access-key pairs omitted unless also granted `INCLUDE_CREDENTIAL_SECRETS`); required with `INCLUDE_CREDENTIAL_SECRETS` for catalog `getCredentials` |
-| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model | With `USE_SECRETS`, include cloud access-key pairs in `getSecrets` and authorize catalog `getCredentials` |
+| `USE_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model | Call `getSecrets` (cloud access-key pairs omitted unless also granted `INCLUDE_CREDENTIAL_SECRETS`); required with `INCLUDE_CREDENTIAL_SECRETS` for static catalog credentials |
+| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model | With `USE_SECRETS`, include cloud access-key pairs in `getSecrets` and static credentials in catalog `getCredentials` |
| `REGISTER_FUNCTION` | Metalake, Catalog, Schema | Register functions in any schema in scope |
| `EXECUTE_FUNCTION` | Metalake, Catalog, Schema, Function | Read the metadata of, and execute, any function in scope |
| `MODIFY_FUNCTION` | Metalake, Catalog, Schema, Function | Alter or drop any function in scope |
@@ -294,10 +294,25 @@ Table statistics follow the table itself: reading them takes `SELECT_TABLE` or `
writing them takes `MODIFY_TABLE`. Model versions follow the model: `USE_MODEL` to read, owner to
alter or delete. Fetching plaintext secrets (`getSecrets`) requires owning the metalake or holding
`USE_SECRETS`. Cloud access-key pairs are included only when the caller is the metalake owner or also
-holds `INCLUDE_CREDENTIAL_SECRETS`. Catalog credential vending (`getCredentials`) requires metadata access plus both
-`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership. Missing either privilege
-returns a forbidden error. Fileset credential vending retains its path-based authorization. Callers who can load the object but lack
-`USE_SECRETS` receive an empty `getSecrets` result rather than a forbidden error.
+holds `INCLUDE_CREDENTIAL_SECRETS`. Catalog credential vending (`getCredentials`) requires metadata
+access. Unless every configured provider explicitly implements `SupportsDynamicCredential`, the
+catalog request additionally requires both `USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or
+metalake ownership. Unmarked providers retain these checks, including existing custom providers
+and mixed dynamic and unmarked configurations. Catalog requests do not partially return credentials.
+Catalog requests carry no storage path. Built-in path-only token providers therefore return no
+catalog credentials, and a token-only catalog probe succeeds with an empty result. Tokens are
+generated through the existing path-based fileset and Iceberg REST vending flows, with the
+authorized paths and storage privileges. Catalogs with no credentials also return an empty result.
+Callers who can load the object but lack `USE_SECRETS` receive an empty `getSecrets` result rather
+than a forbidden error.
+
+Credential providers that issue dynamic credentials without returning stored source credentials can
+opt into metadata-only catalog access by implementing
+`org.apache.gravitino.credential.SupportsDynamicCredential`. These providers must respect the
+supplied authorization context. Built-in token providers implement this interface; custom dynamic
+providers must explicitly add it to receive the same exemption. Existing providers without the marker
+continue to load through the unchanged SPI and retain secret-privilege checks. Provider authorization
+happens before credentials are generated, including for mixed-provider catalogs.
The View row applies to metadata operations through both the native Gravitino REST API and the
Iceberg REST Catalog when authorization is enabled. Listing first requires access to the schema and
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
index 7eb664f30d..caef5b2cc8 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/AuthorizationRequest.java
@@ -37,6 +37,8 @@ public @interface AuthorizationRequest {
/** Loads a view with authorized existence probing. */
LOAD_VIEW,
CREATE_SCHEMA,
- TEST_CATALOG_CONNECTION
+ TEST_CATALOG_CONNECTION,
+ /** Retrieves credentials with provider-specific authorization. */
+ GET_CREDENTIALS
}
}
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/ExpressionCondition.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/ExpressionCondition.java
index f1bd58c1c6..8a4b580a24 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/ExpressionCondition.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/annotations/ExpressionCondition.java
@@ -22,5 +22,7 @@ public enum ExpressionCondition {
NEVER,
REQUIRED_MODIFY_PRIVILEGES,
/** The request carries proposed changes that are not saved, for example in its request body. */
- HAS_PROPOSED_CHANGES
+ HAS_PROPOSED_CHANGES,
+ /** The request retrieves catalog credentials, with extra privileges for static providers. */
+ CATALOG_CREDENTIALS
}
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
index fdbe3f1e8f..a2313e9486 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
@@ -306,6 +306,14 @@ public class AuthorizationExpressionConstants {
ANY_INCLUDE_CREDENTIAL_SECRETS
""";
+ /** Both secret privileges, or metalake ownership, required for static catalog credentials. */
+ public static final String CATALOG_STATIC_CREDENTIALS_AUTHORIZATION_EXPRESSION =
+ "("
+ + FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION
+ + ") && ("
+ + FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION
+ + ")";
+
public static final String FILTER_TOPICS_AUTHORIZATION_EXPRESSION =
"""
ANY(OWNER, METALAKE, CATALOG, SCHEMA, TOPIC) ||
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
index 43d9627ad0..e5e36d3cd6 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
@@ -48,6 +48,7 @@ import org.apache.gravitino.exceptions.BadRequestException;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.IllegalMetadataObjectException;
import org.apache.gravitino.exceptions.IllegalNameIdentifierException;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NoSuchViewException;
@@ -312,6 +313,8 @@ public class GravitinoInterceptionService implements InterceptionService {
scope.bindIfRead(method, metalakeIdent, authorizationRequestContext);
}
return methodInvocation.proceed();
+ } catch (NoSuchCatalogException ex) {
+ return Utils.notFound(ex.getMessage(), ex);
} catch (BadRequestException ex) {
LOG.warn("Invalid authorization request", ex);
return Utils.illegalArguments(ex.getMessage(), ex);
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
index ea3a683525..5953c97ec4 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/AuthorizeExecutorFactory.java
@@ -41,6 +41,13 @@ public class AuthorizeExecutorFactory {
return switch (requestType) {
case COMMON -> new CommonAuthorizerExecutor(
expression, metadataContext, pathParams, entityType);
+ case GET_CREDENTIALS -> new CredentialAuthorizationExecutor(
+ expression,
+ metadataContext,
+ pathParams,
+ entityType,
+ secondaryExpression,
+ secondaryExpressionCondition);
case ASSOCIATE_TAG -> new AssociateTagAuthorizationExecutor(
expression, parameters, args, metadataContext, pathParams, entityType);
case RUN_JOB -> new RunJobAuthorizationExecutor(
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/CredentialAuthorizationExecutor.java b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/CredentialAuthorizationExecutor.java
new file mode 100644
index 0000000000..b738aebc84
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/authorization/CredentialAuthorizationExecutor.java
@@ -0,0 +1,81 @@
+/*
+ * 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.server.web.filter.authorization;
+
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.server.authorization.annotations.ExpressionCondition;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
+
+/** Authorizes credential retrieval using metadata access and provider capabilities. */
+public class CredentialAuthorizationExecutor extends CommonAuthorizerExecutor {
+ private final String staticCredentialExpression;
+ @Nullable private final AuthorizationExpressionEvaluator staticCredentialEvaluator;
+
+ /**
+ * Creates an executor using the expressions declared on the credential operation.
+ *
+ * @param expression the metadata access expression
+ * @param metadataContext the metadata identifiers
+ * @param pathParams the request path parameters
+ * @param entityType the requested metadata object type
+ * @param secondaryExpression the privileges required for static catalog credentials
+ * @param secondaryExpressionCondition when the static credential expression applies
+ */
+ public CredentialAuthorizationExecutor(
+ String expression,
+ Map<Entity.EntityType, NameIdentifier> metadataContext,
+ Map<String, Object> pathParams,
+ Optional<String> entityType,
+ String secondaryExpression,
+ ExpressionCondition secondaryExpressionCondition) {
+ super(expression, metadataContext, pathParams, entityType);
+ staticCredentialExpression = secondaryExpression;
+ staticCredentialEvaluator =
+ secondaryExpressionCondition == ExpressionCondition.CATALOG_CREDENTIALS
+ ? new AuthorizationExpressionEvaluator(secondaryExpression)
+ : null;
+ }
+
+ @Override
+ public boolean execute(AuthorizationRequestContext context) throws Exception {
+ boolean authorized = super.execute(context);
+ if (!authorized || entityType.filter(Entity.EntityType.CATALOG.name()::equals).isEmpty()) {
+ return authorized;
+ }
+ if (staticCredentialEvaluator != null
+ && staticCredentialEvaluator.evaluate(metadataContext, pathParams, context, entityType)) {
+ return true;
+ }
+ NameIdentifier catalog = metadataContext.get(Entity.EntityType.CATALOG);
+ context.setOriginalAuthorizationExpression(staticCredentialExpression);
+ return GravitinoEnv.getInstance()
+ .catalogManager()
+ .doWithCatalog(
+ catalog,
+ baseCatalog ->
+ baseCatalog.catalogCredentialManager().hasOnlyDynamicCredentialProviders());
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
index 9af4f0c639..ca413172d3 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
@@ -45,13 +45,14 @@ import org.apache.gravitino.credential.CredentialPrivilege;
import org.apache.gravitino.dto.credential.CredentialDTO;
import org.apache.gravitino.dto.responses.CredentialResponse;
import org.apache.gravitino.dto.util.DTOConverters;
-import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.metrics.MetricNames;
import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.annotations.AuthorizationFullName;
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
import org.apache.gravitino.server.authorization.annotations.AuthorizationObjectType;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;
+import org.apache.gravitino.server.authorization.annotations.ExpressionCondition;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.web.Utils;
import org.apache.gravitino.utils.MetadataObjectUtil;
@@ -82,11 +83,18 @@ public class MetadataObjectCredentialOperations {
@Produces("application/vnd.gravitino.v1+json")
@Timed(name = "get-credentials." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
@ResponseMetered(name = "get-credentials", absolute = true)
- @AuthorizationExpression(expression = AuthorizationExpressionConstants.CAN_ACCESS_METADATA)
+ @AuthorizationExpression(
+ expression = AuthorizationExpressionConstants.CAN_ACCESS_METADATA,
+ secondaryExpression =
+ AuthorizationExpressionConstants.CATALOG_STATIC_CREDENTIALS_AUTHORIZATION_EXPRESSION,
+ secondaryExpressionCondition = ExpressionCondition.CATALOG_CREDENTIALS)
public Response getCredentials(
@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
String metalake,
- @PathParam("type") @AuthorizationObjectType String type,
+ @PathParam("type")
+ @AuthorizationObjectType
+ @AuthorizationRequest(type = AuthorizationRequest.RequestType.GET_CREDENTIALS)
+ String type,
@PathParam("fullName") @AuthorizationFullName String fullName) {
LOG.info(
"Received get credentials request for object type: {}, full name: {} under metalake: {}",
@@ -109,22 +117,6 @@ public class MetadataObjectCredentialOperations {
NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);
Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);
- // Catalog credentials are not restricted to individual tables or paths. Metadata access
- // alone must not grant the catalog account's source privileges.
- if (object.type() == MetadataObject.Type.CATALOG
- && (!MetadataAuthzHelper.checkAccess(
- identifier,
- entityType,
- AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)
- || !MetadataAuthzHelper.checkAccess(
- identifier,
- entityType,
- AuthorizationExpressionConstants
- .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION))) {
- throw new ForbiddenException(
- "Catalog credentials require USE_SECRETS and INCLUDE_CREDENTIAL_SECRETS");
- }
-
Map<String, String> filteredFilesetHeaders =
Utils.filterFilesetCredentialHeaders(httpRequest);
// set the fileset info into the thread local context
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
index 7533eb1cb4..9c43c2550a 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
@@ -23,11 +23,13 @@ import static org.apache.gravitino.server.authorization.expression.Authorization
import static org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants.TEST_CATALOG_CONNECTION_WITH_CHANGES_AUTHORIZATION_EXPRESSION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -41,8 +43,10 @@ import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
+import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
@@ -61,9 +65,16 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.catalog.CatalogManager;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.credential.CatalogCredentialContext;
+import org.apache.gravitino.credential.CatalogCredentialManager;
+import org.apache.gravitino.credential.JdbcCredential;
+import org.apache.gravitino.credential.JdbcCredentialProvider;
+import org.apache.gravitino.credential.SupportsDynamicCredential;
import org.apache.gravitino.dto.requests.CatalogUpdateRequest;
import org.apache.gravitino.dto.requests.CatalogUpdatesRequest;
import org.apache.gravitino.dto.requests.JobRunRequest;
@@ -78,6 +89,7 @@ import org.apache.gravitino.dto.requests.TagsAssociateRequest;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NoSuchViewException;
@@ -102,6 +114,7 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationFullNa
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
import org.apache.gravitino.server.authorization.annotations.AuthorizationObjectType;
import org.apache.gravitino.server.authorization.annotations.AuthorizationRequest;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.web.ServerHealth;
import org.apache.gravitino.server.web.Utils;
import org.apache.gravitino.server.web.filter.authorization.AuthorizationExecutor;
@@ -110,6 +123,7 @@ import org.apache.gravitino.server.web.rest.CatalogOperations;
import org.apache.gravitino.server.web.rest.DomainMembershipOperations;
import org.apache.gravitino.server.web.rest.DomainOperations;
import org.apache.gravitino.server.web.rest.JobOperations;
+import org.apache.gravitino.server.web.rest.MetadataObjectCredentialOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectDomainOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectPolicyOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectSemanticModelOperations;
@@ -125,6 +139,7 @@ import org.apache.gravitino.server.web.rest.ViewOperations;
import org.apache.gravitino.tag.TagDispatcher;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.gravitino.utils.RequestContext;
+import org.apache.gravitino.utils.ThrowableFunction;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LogEvent;
@@ -147,12 +162,287 @@ import org.mockito.MockedStatic;
/** Test for {@link GravitinoInterceptionService}. */
public class TestGravitinoInterceptionService {
+ /**
+ * Models an existing custom provider that returns stored credentials without a capability marker.
+ */
+ public static class LegacyStaticCredentialProvider extends JdbcCredentialProvider {
+ private static final String CREDENTIAL_TYPE = "legacy-static";
+
+ @Override
+ public String credentialType() {
+ return CREDENTIAL_TYPE;
+ }
+ }
+
@AfterEach
public void clearRequestContext() {
RequestContext.resetOperationFailureFired();
RequestContext.clear();
}
+ /**
+ * Checks that token vending retains the standard catalog metadata authorization gate.
+ *
+ * @param useCatalog whether the caller can access the catalog
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void testCredentialsRequireCatalogMetadataAccess(boolean useCatalog) throws Throwable {
+ Method method =
+ MetadataObjectCredentialOperations.class.getMethod(
+ "getCredentials", String.class, String.class, String.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(new Object[] {"testMetalake", "catalog", "testCatalog"});
+ when(invocation.proceed()).thenReturn(Utils.ok("ok"));
+
+ Descriptor descriptor = mock(Descriptor.class);
+ when(descriptor.getImplementation())
+ .thenReturn(MetadataObjectCredentialOperations.class.getName());
+ Assertions.assertTrue(
+ new GravitinoInterceptionService().getDescriptorFilter().matches(descriptor));
+
+ try (Response response =
+ invokeWithAuthorizer(
+ catalogConnectionAuthorizer(useCatalog, false),
+ mock(EventBus.class),
+ invocation,
+ credentialCatalogManager("custom-session"))) {
+ assertEquals(useCatalog ? 200 : 403, response.getStatus());
+ }
+ if (useCatalog) {
+ verify(invocation).proceed();
+ } else {
+ verify(invocation, never()).proceed();
+ }
+ }
+
+ /**
+ * Checks that a catalog containing any static provider requires both secret privileges.
+ *
+ * @param providers the configured providers
+ * @param useSecrets whether the caller may use secrets
+ * @param includeSecrets whether the caller may receive static credential secrets
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "custom-stored,false,false", "custom-stored,false,true",
+ "custom-stored,true,false", "custom-stored,true,true",
+ "'custom-session,custom-stored',false,false", "'custom-session,custom-stored',false,true",
+ "'custom-session,custom-stored',true,false", "'custom-session,custom-stored',true,true"
+ })
+ public void testCatalogCredentialExecutor(
+ String providers, boolean useSecrets, boolean includeSecrets) throws Throwable {
+ MethodInvocation invocation = credentialInvocation("catalog");
+ GravitinoAuthorizer authorizer = credentialAuthorizer(useSecrets, includeSecrets);
+ when(invocation.proceed()).thenReturn(Utils.ok("ok"));
+ try (Response response =
+ invokeWithAuthorizer(
+ authorizer, mock(EventBus.class), invocation, credentialCatalogManager(providers))) {
+ assertEquals(useSecrets && includeSecrets ? 200 : 403, response.getStatus());
+ }
+ verify(invocation, times(useSecrets && includeSecrets ? 1 : 0)).proceed();
+ ArgumentCaptor<AuthorizationRequestContext> contexts =
+ ArgumentCaptor.forClass(AuthorizationRequestContext.class);
+ verify(authorizer, atLeastOnce()).authorize(any(), any(), any(), any(), contexts.capture());
+ for (AuthorizationRequestContext context : contexts.getAllValues()) {
+ Assertions.assertSame(contexts.getValue(), context);
+ }
+ }
+
+ /**
+ * Checks that dynamic-only and empty catalogs retain metadata-only access.
+ *
+ * @param providers the configured providers
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"", "custom-session"})
+ public void testCatalogProbeWithoutStaticProviders(String providers) throws Throwable {
+ MethodInvocation invocation = credentialInvocation("catalog");
+ when(invocation.proceed()).thenReturn(Utils.ok("ok"));
+ try (Response response =
+ invokeWithAuthorizer(
+ credentialAuthorizer(false, false),
+ mock(EventBus.class),
+ invocation,
+ credentialCatalogManager(providers))) {
+ assertEquals(200, response.getStatus());
+ verify(invocation).proceed();
+ }
+ }
+
+ /**
+ * Checks that a custom provider loaded through the unchanged SPI retains secret protection.
+ *
+ * @param useSecrets whether the caller may use secrets
+ * @param includeSecrets whether the caller may receive credential secrets
+ * @throws Throwable if the intercepted invocation fails unexpectedly
+ */
+ @ParameterizedTest
+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+ public void testLegacyStaticProviderRequiresBothSecretPrivileges(
+ boolean useSecrets, boolean includeSecrets) throws Throwable {
+ Map<String, String> properties =
+ Map.of(
+ "credential-providers",
+ LegacyStaticCredentialProvider.CREDENTIAL_TYPE,
+ JdbcCredential.GRAVITINO_JDBC_USER,
+ "legacy-user",
+ JdbcCredential.GRAVITINO_JDBC_PASSWORD,
+ "legacy-password");
+ try (CatalogCredentialManager credentials =
+ spy(new CatalogCredentialManager("testCatalog", properties))) {
+ Assertions.assertInstanceOf(
+ LegacyStaticCredentialProvider.class,
+ credentials.getCredentialProvider(LegacyStaticCredentialProvider.CREDENTIAL_TYPE).get());
+ Assertions.assertFalse(
+ credentials.getCredentialProvider(LegacyStaticCredentialProvider.CREDENTIAL_TYPE).get()
+ instanceof SupportsDynamicCredential);
+ Assertions.assertFalse(credentials.hasOnlyDynamicCredentialProviders());
+ MethodInvocation invocation = credentialInvocation("catalog");
+ when(invocation.proceed())
+ .thenAnswer(
+ ignored -> {
+ JdbcCredential credential =
+ Assertions.assertInstanceOf(
+ JdbcCredential.class,
+ credentials
+ .getCredential(
+ LegacyStaticCredentialProvider.CREDENTIAL_TYPE,
+ new CatalogCredentialContext("tester"))
+ .get());
+ Assertions.assertEquals("legacy-user", credential.jdbcUser());
+ Assertions.assertEquals("legacy-password", credential.jdbcPassword());
+ return Utils.ok("ok");
+ });
+ boolean authorized = useSecrets && includeSecrets;
+ try (Response response =
+ invokeWithAuthorizer(
+ credentialAuthorizer(useSecrets, includeSecrets),
+ mock(EventBus.class),
+ invocation,
+ credentialCatalogManager(credentials))) {
+ assertEquals(authorized ? 200 : 403, response.getStatus());
+ }
+ verify(invocation, times(authorized ? 1 : 0)).proceed();
+ verify(credentials, times(authorized ? 1 : 0)).getCredential(any(), any());
+ }
+ }
+
+ /** Checks standard denial and audit handling for static-only credential requests. */
+ @Test
+ public void testStaticCredentialsDeniedBeforeInvocation() throws Throwable {
+ MethodInvocation invocation = credentialInvocation("catalog");
+ EventBus eventBus = mock(EventBus.class);
+ try (Response response =
+ invokeWithAuthorizer(
+ credentialAuthorizer(false, false),
+ eventBus,
+ invocation,
+ credentialCatalogManager("custom-stored"))) {
+ assertEquals(403, response.getStatus());
+ verify(invocation, never()).proceed();
+ }
+ ArgumentCaptor<AuthorizationDenialFailureEvent> denial =
+ ArgumentCaptor.forClass(AuthorizationDenialFailureEvent.class);
+ verify(eventBus).dispatchEvent(denial.capture());
+ assertEquals(
+ AuthorizationExpressionConstants.CATALOG_STATIC_CREDENTIALS_AUTHORIZATION_EXPRESSION,
+ denial.getValue().expression());
+ }
+
+ /** Checks that metalake ownership remains sufficient for static credentials. */
+ @Test
+ public void testMetalakeOwnerCanReadStaticCredentials() throws Throwable {
+ GravitinoAuthorizer authorizer = credentialAuthorizer(false, false);
+ when(authorizer.isOwner(
+ any(),
+ any(),
+ ArgumentMatchers.argThat(object -> object.type() == MetadataObject.Type.METALAKE),
+ any()))
+ .thenReturn(true);
+ CatalogManager manager = credentialCatalogManager("custom-stored");
+ MethodInvocation invocation = credentialInvocation("catalog");
+ when(invocation.proceed()).thenReturn(Utils.ok("ok"));
+ try (Response response =
+ invokeWithAuthorizer(authorizer, mock(EventBus.class), invocation, manager)) {
+ assertEquals(200, response.getStatus());
+ }
+ verify(manager, never()).doWithCatalog(any(), any());
+ }
+
+ /**
+ * Checks existing deny policies for the secondary secret privilege expression.
+ *
+ * @param privilege the denied secret privilege
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"USE_SECRETS", "INCLUDE_CREDENTIAL_SECRETS"})
+ public void testStaticCredentialDenyPolicy(String privilege) throws Throwable {
+ GravitinoAuthorizer authorizer = credentialAuthorizer(true, true);
+ when(authorizer.deny(
+ any(), any(), any(), ArgumentMatchers.eq(Privilege.Name.valueOf(privilege)), any()))
+ .thenReturn(true);
+ MethodInvocation invocation = credentialInvocation("catalog");
+ try (Response response =
+ invokeWithAuthorizer(
+ authorizer,
+ mock(EventBus.class),
+ invocation,
+ credentialCatalogManager("custom-stored"))) {
+ assertEquals(403, response.getStatus());
+ verify(invocation, never()).proceed();
+ }
+ }
+
+ /**
+ * Checks that filesets and operation errors retain their existing behavior.
+ *
+ * @param type the requested metadata object type
+ * @param status the operation response status
+ */
+ @ParameterizedTest
+ @CsvSource({"catalog,200", "fileset,200", "catalog,400", "catalog,500"})
+ public void testCredentialExecutorPreservesOperationErrors(String type, int status)
+ throws Throwable {
+ MethodInvocation invocation = credentialInvocation(type);
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ when(authorizer.authorize(any(), any(), any(), any(), any()))
+ .thenAnswer(
+ call -> {
+ Privilege.Name privilege = call.getArgument(3);
+ return privilege != Privilege.Name.USE_SECRETS
+ && privilege != Privilege.Name.INCLUDE_CREDENTIAL_SECRETS;
+ });
+ try (Response original = Response.status(status).entity("unchanged").build()) {
+ when(invocation.proceed()).thenReturn(original);
+ try (Response response =
+ invokeWithAuthorizer(
+ authorizer,
+ mock(EventBus.class),
+ invocation,
+ credentialCatalogManager("custom-session"))) {
+ Assertions.assertSame(original, response);
+ }
+ }
+ }
+
+ /** Checks that a catalog disappearing during authorization is still reported as not found. */
+ @Test
+ public void testMissingCredentialCatalogReturnsNotFound() throws Throwable {
+ CatalogManager manager = mock(CatalogManager.class);
+ when(manager.doWithCatalog(any(), any()))
+ .thenThrow(new NoSuchCatalogException("Catalog missing"));
+ MethodInvocation invocation = credentialInvocation("catalog");
+ try (Response response =
+ invokeWithAuthorizer(
+ credentialAuthorizer(false, false), mock(EventBus.class), invocation, manager)) {
+ assertEquals(404, response.getStatus());
+ verify(invocation, never()).proceed();
+ }
+ }
+
@ParameterizedTest
@ValueSource(strings = {"table", "view"})
public void testDeniedSourceLookupDoesNotReachDispatcher(String type) throws Throwable {
@@ -1996,15 +2286,14 @@ public class TestGravitinoInterceptionService {
GravitinoAuthorizer authorizer = catalogConnectionAuthorizer(true, false);
MethodInvocation noBody = testExistingConnectionInvocation(null);
- Response noBodyResponse =
- invokeTestExistingConnection(authorizer, mock(EventBus.class), noBody);
+ Response noBodyResponse = invokeWithAuthorizer(authorizer, mock(EventBus.class), noBody);
assertEquals(Response.Status.OK.getStatusCode(), noBodyResponse.getStatus());
verify(noBody).proceed();
MethodInvocation emptyChanges =
testExistingConnectionInvocation(new CatalogUpdatesRequest(Collections.emptyList()));
Response emptyChangesResponse =
- invokeTestExistingConnection(authorizer, mock(EventBus.class), emptyChanges);
+ invokeWithAuthorizer(authorizer, mock(EventBus.class), emptyChanges);
assertEquals(Response.Status.OK.getStatusCode(), emptyChangesResponse.getStatus());
verify(emptyChanges).proceed();
}
@@ -2015,8 +2304,7 @@ public class TestGravitinoInterceptionService {
MethodInvocation invocation = testExistingConnectionInvocation(proposedCatalogChanges());
Response response =
- invokeTestExistingConnection(
- catalogConnectionAuthorizer(true, false), eventBus, invocation);
+ invokeWithAuthorizer(catalogConnectionAuthorizer(true, false), eventBus, invocation);
assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
verify(invocation, never()).proceed();
@@ -2035,7 +2323,7 @@ public class TestGravitinoInterceptionService {
MethodInvocation invocation = testExistingConnectionInvocation(proposedCatalogChanges());
Response response =
- invokeTestExistingConnection(
+ invokeWithAuthorizer(
catalogConnectionAuthorizer(false, true), mock(EventBus.class), invocation);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
@@ -2187,9 +2475,69 @@ public class TestGravitinoInterceptionService {
return authorizer;
}
- private Response invokeTestExistingConnection(
+ private MethodInvocation credentialInvocation(String type) throws NoSuchMethodException {
+ Method method =
+ MetadataObjectCredentialOperations.class.getMethod(
+ "getCredentials", String.class, String.class, String.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(
+ new Object[] {
+ "testMetalake",
+ type,
+ "catalog".equals(type) ? "testCatalog" : "testCatalog.schema.fileset"
+ });
+ return invocation;
+ }
+
+ private GravitinoAuthorizer credentialAuthorizer(boolean useSecrets, boolean includeSecrets) {
+ GravitinoAuthorizer authorizer = catalogConnectionAuthorizer(true, false);
+ when(authorizer.authorize(
+ any(), any(), any(), ArgumentMatchers.eq(Privilege.Name.USE_SECRETS), any()))
+ .thenReturn(useSecrets);
+ when(authorizer.authorize(
+ any(),
+ any(),
+ any(),
+ ArgumentMatchers.eq(Privilege.Name.INCLUDE_CREDENTIAL_SECRETS),
+ any()))
+ .thenReturn(includeSecrets);
+ return authorizer;
+ }
+
+ private CatalogManager credentialCatalogManager(String providers) {
+ CatalogCredentialManager credentials = mock(CatalogCredentialManager.class);
+ when(credentials.hasOnlyDynamicCredentialProviders())
+ .thenReturn(providers.isEmpty() || providers.equals("custom-session"));
+ return credentialCatalogManager(credentials);
+ }
+
+ private CatalogManager credentialCatalogManager(CatalogCredentialManager credentials) {
+ CatalogManager manager = mock(CatalogManager.class);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ when(catalog.catalogCredentialManager()).thenReturn(credentials);
+ when(manager.doWithCatalog(any(), any()))
+ .thenAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog, ?> operation = invocation.getArgument(1);
+ return operation.apply(catalog);
+ });
+ return manager;
+ }
+
+ private Response invokeWithAuthorizer(
GravitinoAuthorizer authorizer, EventBus eventBus, MethodInvocation invocation)
throws Throwable {
+ return invokeWithAuthorizer(authorizer, eventBus, invocation, null);
+ }
+
+ private Response invokeWithAuthorizer(
+ GravitinoAuthorizer authorizer,
+ EventBus eventBus,
+ MethodInvocation invocation,
+ @Nullable CatalogManager catalogManager)
+ throws Throwable {
try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
MockedStatic<GravitinoAuthorizerProvider> authorizerMocked =
mockStatic(GravitinoAuthorizerProvider.class);
@@ -2214,6 +2562,7 @@ public class TestGravitinoInterceptionService {
GravitinoEnv mockEnv = mock(GravitinoEnv.class);
envMocked.when(GravitinoEnv::getInstance).thenReturn(mockEnv);
when(mockEnv.eventBus()).thenReturn(eventBus);
+ when(mockEnv.catalogManager()).thenReturn(catalogManager);
// Use the real resource method so its annotations drive the authorization executor.
MethodInterceptor interceptor =
@@ -2247,7 +2596,8 @@ public class TestGravitinoInterceptionService {
ArgumentMatchers.eq("testMetalake"),
ArgumentMatchers.argThat(
metadataObject ->
- metadataObject.type() == MetadataObject.Type.CATALOG
+ metadataObject != null
+ && metadataObject.type() == MetadataObject.Type.CATALOG
&& "testCatalog".equals(metadataObject.name())),
ArgumentMatchers.eq(Privilege.Name.USE_CATALOG),
ArgumentMatchers.any()))
@@ -2257,7 +2607,8 @@ public class TestGravitinoInterceptionService {
ArgumentMatchers.eq("testMetalake"),
ArgumentMatchers.argThat(
metadataObject ->
- metadataObject.type() == MetadataObject.Type.CATALOG
+ metadataObject != null
+ && metadataObject.type() == MetadataObject.Type.CATALOG
&& "testCatalog".equals(metadataObject.name())),
ArgumentMatchers.any()))
.thenReturn(owner);
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestCredentialAuthorizationExecutor.java b/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestCredentialAuthorizationExecutor.java
new file mode 100644
index 0000000000..38ee586656
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/authorization/TestCredentialAuthorizationExecutor.java
@@ -0,0 +1,88 @@
+/*
+ * 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.server.web.filter.authorization;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.credential.CatalogCredentialManager;
+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.authorization.annotations.ExpressionCondition;
+import org.apache.gravitino.utils.ThrowableFunction;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+
+/** Tests conservative provider selection when no secondary privilege check is configured. */
+public class TestCredentialAuthorizationExecutor {
+ /**
+ * Checks that an unconfigured secondary expression never grants access to static providers.
+ *
+ * @param onlyDynamic whether all configured providers explicitly support dynamic credentials
+ * @throws Exception if authorization fails unexpectedly
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void testUnconfiguredStaticPrivilegeExpression(boolean onlyDynamic) throws Exception {
+ NameIdentifier catalog = NameIdentifier.of("metalake", "catalog");
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ when(provider.getGravitinoAuthorizer()).thenReturn(mock(GravitinoAuthorizer.class));
+ CatalogManager manager = mock(CatalogManager.class);
+ CatalogCredentialManager credentials = mock(CatalogCredentialManager.class);
+ when(credentials.hasOnlyDynamicCredentialProviders()).thenReturn(onlyDynamic);
+ BaseCatalog<?> baseCatalog = mock(BaseCatalog.class);
+ when(baseCatalog.catalogCredentialManager()).thenReturn(credentials);
+ when(manager.doWithCatalog(any(), any()))
+ .thenAnswer(
+ invocation -> {
+ ThrowableFunction<BaseCatalog, ?> operation = invocation.getArgument(1);
+ return operation.apply(baseCatalog);
+ });
+ GravitinoEnv env = mock(GravitinoEnv.class);
+ when(env.catalogManager()).thenReturn(manager);
+ try (MockedStatic<GravitinoAuthorizerProvider> providers =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ MockedStatic<GravitinoEnv> environments = mockStatic(GravitinoEnv.class)) {
+ providers.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ environments.when(GravitinoEnv::getInstance).thenReturn(env);
+ CredentialAuthorizationExecutor executor =
+ new CredentialAuthorizationExecutor(
+ "true",
+ Map.of(Entity.EntityType.CATALOG, catalog),
+ Map.of(),
+ Optional.of(Entity.EntityType.CATALOG.name()),
+ "false",
+ ExpressionCondition.NEVER);
+
+ Assertions.assertEquals(onlyDynamic, executor.execute(new AuthorizationRequestContext()));
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
index ede3595f4d..cc66978266 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
@@ -19,10 +19,7 @@
package org.apache.gravitino.server.web.rest;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.mockStatic;
-import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -31,8 +28,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.credential.Credential;
@@ -42,15 +37,12 @@ import org.apache.gravitino.dto.responses.CredentialResponse;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.rest.RESTUtils;
-import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
-import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-import org.mockito.MockedStatic;
public class TestMetadataObjectCredentialOperations extends JerseyTest {
@@ -92,48 +84,6 @@ public class TestMetadataObjectCredentialOperations extends JerseyTest {
return resourceConfig;
}
- /** Checks catalog secret privileges without changing fileset authorization. */
- @Test
- public void testCatalogCredentialsRequireBothSecretPrivileges() throws Exception {
- for (boolean useSecrets : new boolean[] {false, true}) {
- for (boolean includeCredentials : new boolean[] {false, true}) {
- CredentialOperationDispatcher dispatcher = mock(CredentialOperationDispatcher.class);
- MetadataObjectCredentialOperations operations =
- new MetadataObjectCredentialOperations(dispatcher);
- FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);
- try (MockedStatic<MetadataAuthzHelper> auth = mockStatic(MetadataAuthzHelper.class)) {
- auth.when(
- () ->
- MetadataAuthzHelper.checkAccess(
- any(),
- any(Entity.EntityType.class),
- eq(
- AuthorizationExpressionConstants
- .FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)))
- .thenReturn(useSecrets);
- auth.when(
- () ->
- MetadataAuthzHelper.checkAccess(
- any(),
- any(Entity.EntityType.class),
- eq(
- AuthorizationExpressionConstants
- .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION)))
- .thenReturn(includeCredentials);
- try (Response response = operations.getCredentials("test", "catalog", "catalog")) {
- Assertions.assertEquals(
- useSecrets && includeCredentials ? 200 : 403, response.getStatus());
- }
- if (!useSecrets || !includeCredentials) verifyNoInteractions(dispatcher);
- try (Response response =
- operations.getCredentials("test", "fileset", "catalog.schema.fileset")) {
- Assertions.assertEquals(200, response.getStatus());
- }
- }
- }
- }
- }
-
/** Checks credential client errors identify the requested object. */
@Test
public void testUnsupportedObjectAndProviderErrorsIdentifyTheObject() {
diff --git a/server/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider b/server/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider
new file mode 100644
index 0000000000..2fe117ac1d
--- /dev/null
+++ b/server/src/test/resources/META-INF/services/org.apache.gravitino.credential.CredentialProvider
@@ -0,0 +1,19 @@
+#
+# 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.
+#
+org.apache.gravitino.server.web.filter.TestGravitinoInterceptionService$LegacyStaticCredentialProvider