World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13538] fix(authz): Hide access key IDs and split USE_SECRET from USE_CREDENTIAL (#13539)
MaSai2f95e4674164
diff --git a/api/src/main/java/org/apache/gravitino/authorization/Privilege.java b/api/src/main/java/org/apache/gravitino/authorization/Privilege.javaindex c65db6806b..ada522eea6 100644--- a/api/src/main/java/org/apache/gravitino/authorization/Privilege.java+++ b/api/src/main/java/org/apache/gravitino/authorization/Privilege.java@@ -161,10 +161,17 @@ public interface Privilege {/** The privilege to list configured secrets providers. */VIEW_SECRET_PROVIDERS(0L, 1L << 36),/**- * The privilege to retrieve plaintext secrets and vend credentials for a metadata object via- * {@code getSecrets} / {@code getCredentials}.+ * The privilege required to call {@code getSecrets}. Without {@link+ * #INCLUDE_CREDENTIAL_SECRETS}, cloud access-key pairs are omitted from the result. Does not+ * authorize {@code getCredentials}.*/- USE_SECRET(0L, 1L << 37);+ USE_SECRETS(0L, 1L << 37),+ /**+ * When held together with {@link #USE_SECRETS}, includes cloud access-key pairs and other+ * credential secrets in the {@code getSecrets} result. Alone it does not authorize {@code+ * getSecrets}. Does not authorize {@code getCredentials}.+ */+ INCLUDE_CREDENTIAL_SECRETS(0L, 1L << 38);private final long highBits;private final long lowBits;diff --git a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java b/api/src/main/java/org/apache/gravitino/authorization/Privileges.javaindex 3466942b23..9519fe2e27 100644--- a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java+++ b/api/src/main/java/org/apache/gravitino/authorization/Privileges.java@@ -211,8 +211,10 @@ public class Privileges {// Secretscase VIEW_SECRET_PROVIDERS:return ViewSecretProviders.allow();- case USE_SECRET:- return UseSecret.allow();+ case USE_SECRETS:+ return UseSecrets.allow();+ case INCLUDE_CREDENTIAL_SECRETS:+ return IncludeCredentialSecrets.allow();// Job templatecase REGISTER_JOB_TEMPLATE:@@ -345,8 +347,10 @@ public class Privileges {// Secretscase VIEW_SECRET_PROVIDERS:return ViewSecretProviders.deny();- case USE_SECRET:- return UseSecret.deny();+ case USE_SECRETS:+ return UseSecrets.deny();+ case INCLUDE_CREDENTIAL_SECRETS:+ return IncludeCredentialSecrets.deny();// Job templatecase REGISTER_JOB_TEMPLATE:@@ -1414,32 +1418,76 @@ public class Privileges {}/**- * The privilege to retrieve plaintext secrets and vend credentials for a metadata object.+ * The privilege required to call {@code getSecrets}. Without {@link IncludeCredentialSecrets},+ * cloud access-key pairs are omitted from the result.*- * <p>Applies to both {@code getSecrets} and {@code getCredentials}. Callers that are not the- * metalake owner and lack this privilege receive an empty result rather than a forbidden error,- * once they can already access the metadata object.+ * <p>Intended for connectors that recover JDBC and similar secrets via {@code getSecrets}, and+ * recover cloud access keys via {@code getCredentials} (which requires no privilege). Callers+ * that are not the metalake owner and lack this privilege receive an empty {@code getSecrets}+ * result rather than a forbidden error, once they can already access the metadata object.*/- public static final class UseSecret extends GenericPrivilege<UseSecret> {+ public static final class UseSecrets extends GenericPrivilege<UseSecrets> {- private static final UseSecret ALLOW_INSTANCE = new UseSecret(Condition.ALLOW, Name.USE_SECRET);- private static final UseSecret DENY_INSTANCE = new UseSecret(Condition.DENY, Name.USE_SECRET);+ private static final UseSecrets ALLOW_INSTANCE =+ new UseSecrets(Condition.ALLOW, Name.USE_SECRETS);+ private static final UseSecrets DENY_INSTANCE =+ new UseSecrets(Condition.DENY, Name.USE_SECRETS);- private UseSecret(Condition condition, Name name) {+ private UseSecrets(Condition condition, Name name) {super(condition, name);}/*** @return The instance with allow condition of the privilege.*/- public static UseSecret allow() {+ public static UseSecrets allow() {return ALLOW_INSTANCE;}/*** @return The instance with deny condition of the privilege.*/- public static UseSecret deny() {+ public static UseSecrets deny() {+ return DENY_INSTANCE;+ }++ @Override+ public boolean canBindTo(MetadataObject.Type type) {+ return SECRET_SUPPORTED_TYPES.contains(type);+ }+ }++ /**+ * When held together with {@link UseSecrets}, includes cloud access-key pairs and other+ * credential secrets in the {@code getSecrets} result.+ *+ * <p>Does not authorize {@code getSecrets} or {@code getCredentials} by itself. Metalake owners+ * and holders of both privileges receive the full secrets map; holders of only {@link UseSecrets}+ * get cloud access-key pairs omitted.+ */+ public static final class IncludeCredentialSecrets+ extends GenericPrivilege<IncludeCredentialSecrets> {++ private static final IncludeCredentialSecrets ALLOW_INSTANCE =+ new IncludeCredentialSecrets(Condition.ALLOW, Name.INCLUDE_CREDENTIAL_SECRETS);+ private static final IncludeCredentialSecrets DENY_INSTANCE =+ new IncludeCredentialSecrets(Condition.DENY, Name.INCLUDE_CREDENTIAL_SECRETS);++ private IncludeCredentialSecrets(Condition condition, Name name) {+ super(condition, name);+ }++ /**+ * @return The instance with allow condition of the privilege.+ */+ public static IncludeCredentialSecrets allow() {+ return ALLOW_INSTANCE;+ }++ /**+ * @return The instance with deny condition of the privilege.+ */+ public static IncludeCredentialSecrets deny() {return DENY_INSTANCE;}diff --git a/api/src/main/java/org/apache/gravitino/credential/CredentialInfos.java b/api/src/main/java/org/apache/gravitino/credential/CredentialInfos.javanew file mode 100644index 0000000000..b63198c10d--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/credential/CredentialInfos.java@@ -0,0 +1,59 @@+/*+ * 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 com.google.common.collect.ImmutableMap;+import java.util.HashMap;+import java.util.Map;+import javax.annotation.Nullable;++/**+ * Helpers for merging {@link Credential#credentialInfo()} into connector configuration.+ *+ * <p>Catalog configs that are built once and cached must not absorb expiring (token) credentials.+ */+public final class CredentialInfos {++ private CredentialInfos() {}++ /**+ * Returns a map of non-expiring credential info entries suitable for one-shot connector config.+ *+ * <p>Skips null credentials, credentials with {@code expireTimeInMs != 0}, and null {@link+ * Credential#credentialInfo()}. Later credentials overwrite earlier keys.+ *+ * @param credentials credentials from {@link SupportsCredentials#getCredentials()}, may be null+ * @return merged non-expiring credential info; never null+ */+ public static Map<String, String> nonExpiringCredentialInfo(@Nullable Credential[] credentials) {+ if (credentials == null || credentials.length == 0) {+ return ImmutableMap.of();+ }+ Map<String, String> merged = new HashMap<>();+ for (Credential credential : credentials) {+ if (credential == null+ || credential.expireTimeInMs() != 0+ || credential.credentialInfo() == null) {+ continue;+ }+ merged.putAll(credential.credentialInfo());+ }+ return ImmutableMap.copyOf(merged);+ }+}diff --git a/api/src/main/java/org/apache/gravitino/secret/SupportsSecrets.java b/api/src/main/java/org/apache/gravitino/secret/SupportsSecrets.javaindex 1d0fd56856..db87435dfa 100644--- a/api/src/main/java/org/apache/gravitino/secret/SupportsSecrets.java+++ b/api/src/main/java/org/apache/gravitino/secret/SupportsSecrets.java@@ -28,29 +28,25 @@ import java.util.Map;* <ul>* <li>Every secret-URN property value, resolved via the secret manager (including keys that may* also be delivered via {@link org.apache.gravitino.credential.SupportsCredentials}).- * <li>Stored plaintext for property keys whose names look sensitive (contain {@code secret},+ * <li>Stored plaintext for every property declared {@code hidden} in entity metadata (no+ * sensitive-name keyword gate), so shortening the server sensitive-key keyword list cannot+ * leave a masked property without a recovery path.+ * <li>Stored plaintext for undeclared keys whose names look sensitive (contain {@code secret},* {@code password}, {@code token}, {@code credential}, {@code access}, or {@code account},- * case-insensitive) when the key is undeclared or declared {@code hidden}, so mistyped /- * undeclared credential properties remain usable after API responses mask them as {@code- * ******}. Declared non-hidden configuration keys are not returned even when the name- * matches.+ * case-insensitive), so mistyped / undeclared credential properties remain usable after API+ * responses mask them as {@code ******}.* </ul>*- * <p>Properties that are only declared {@code hidden} in property metadata, and whose names do- * <em>not</em> match the sensitive-name pattern above, are masked as {@code ******} on list/get but- * are <strong>not</strong> returned by {@link #getSecrets()}. Clients must not treat a remaining- * {@code ******} value as a usable credential for those keys.- *- * <p>Normal non-sensitive properties are not included; combine with {@code load*().properties()} on- * the client.+ * <p>Declared non-hidden configuration keys are not returned even when the name looks sensitive+ * (for example {@code credential-providers}). Normal non-sensitive properties are not included;+ * combine with {@code load*().properties()} on the client.*/public interface SupportsSecrets {/*** Returns plaintext secret properties for this metadata object.*- * <p>Does not recover values for properties that are only metadata-{@code hidden} without a- * sensitive-looking name or a secret URN. See the interface javadoc.+ * <p>See the interface javadoc for which keys are recovered.** @return a map of property key to plaintext value; never null, may be empty*/diff --git a/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java b/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.javaindex 82fd8711db..eb01e7ca1e 100644--- a/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java+++ b/api/src/test/java/org/apache/gravitino/authorization/TestSecurableObjects.java@@ -217,7 +217,8 @@ public class TestSecurableObjects {Privilege registerFunction = Privileges.RegisterFunction.allow();Privilege executeFunction = Privileges.ExecuteFunction.allow();Privilege modifyFunction = Privileges.ModifyFunction.allow();- Privilege useSecret = Privileges.UseSecret.allow();+ Privilege useSecrets = Privileges.UseSecrets.allow();+ Privilege includeCredentialSecrets = Privileges.IncludeCredentialSecrets.allow();Assertions.assertTrue(viewTag.canBindTo(MetadataObject.Type.METALAKE));Assertions.assertTrue(viewTag.canBindTo(MetadataObject.Type.TAG));@@ -440,18 +441,31 @@ public class TestSecurableObjects {Assertions.assertFalse(useModel.canBindTo(MetadataObject.Type.COLUMN));Assertions.assertTrue(useModel.canBindTo(MetadataObject.Type.MODEL));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.METALAKE));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.CATALOG));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.SCHEMA));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.TABLE));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.VIEW));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.TOPIC));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.FILESET));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.MODEL));- Assertions.assertTrue(useSecret.canBindTo(MetadataObject.Type.MODEL_VERSION));- Assertions.assertFalse(useSecret.canBindTo(MetadataObject.Type.ROLE));- Assertions.assertFalse(useSecret.canBindTo(MetadataObject.Type.COLUMN));- Assertions.assertFalse(useSecret.canBindTo(MetadataObject.Type.FUNCTION));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.METALAKE));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.CATALOG));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.SCHEMA));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.TABLE));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.VIEW));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.TOPIC));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.FILESET));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.MODEL));+ Assertions.assertTrue(useSecrets.canBindTo(MetadataObject.Type.MODEL_VERSION));+ Assertions.assertFalse(useSecrets.canBindTo(MetadataObject.Type.ROLE));+ Assertions.assertFalse(useSecrets.canBindTo(MetadataObject.Type.COLUMN));+ Assertions.assertFalse(useSecrets.canBindTo(MetadataObject.Type.FUNCTION));++ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.METALAKE));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.CATALOG));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.SCHEMA));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.TABLE));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.VIEW));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.TOPIC));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.FILESET));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.MODEL));+ Assertions.assertTrue(includeCredentialSecrets.canBindTo(MetadataObject.Type.MODEL_VERSION));+ Assertions.assertFalse(includeCredentialSecrets.canBindTo(MetadataObject.Type.ROLE));+ Assertions.assertFalse(includeCredentialSecrets.canBindTo(MetadataObject.Type.COLUMN));+ Assertions.assertFalse(includeCredentialSecrets.canBindTo(MetadataObject.Type.FUNCTION));Assertions.assertTrue(createTag.canBindTo(MetadataObject.Type.METALAKE));Assertions.assertFalse(createTag.canBindTo(MetadataObject.Type.CATALOG));diff --git a/api/src/test/java/org/apache/gravitino/credential/TestCredentialInfos.java b/api/src/test/java/org/apache/gravitino/credential/TestCredentialInfos.javanew file mode 100644index 0000000000..dd05559b27--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/credential/TestCredentialInfos.java@@ -0,0 +1,61 @@+/*+ * 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.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.Map;+import org.junit.jupiter.api.Test;++public class TestCredentialInfos {++ @Test+ void testSkipsExpiringAndNulls() {+ Credential staticCred = new JdbcCredential("user", "pass");+ Credential expiring =+ new S3TokenCredential("ak", "sk", "session", System.currentTimeMillis() + 60_000L);++ Map<String, String> merged =+ CredentialInfos.nonExpiringCredentialInfo(+ new Credential[] {null, expiring, staticCred, null});++ assertEquals("user", merged.get(JdbcCredential.GRAVITINO_JDBC_USER));+ assertEquals("pass", merged.get(JdbcCredential.GRAVITINO_JDBC_PASSWORD));+ assertFalse(merged.containsKey(S3TokenCredential.GRAVITINO_S3_TOKEN));+ assertFalse(merged.containsKey(S3TokenCredential.GRAVITINO_S3_SESSION_ACCESS_KEY_ID));+ }++ @Test+ void testNullOrEmpty() {+ assertTrue(CredentialInfos.nonExpiringCredentialInfo(null).isEmpty());+ assertTrue(CredentialInfos.nonExpiringCredentialInfo(new Credential[0]).isEmpty());+ }++ @Test+ void testLaterStaticOverwritesEarlier() {+ Credential first = new JdbcCredential("u1", "p1");+ Credential second = new JdbcCredential("u2", "p2");+ Map<String, String> merged =+ CredentialInfos.nonExpiringCredentialInfo(new Credential[] {first, second});+ assertEquals("u2", merged.get(JdbcCredential.GRAVITINO_JDBC_USER));+ assertEquals("p2", merged.get(JdbcCredential.GRAVITINO_JDBC_PASSWORD));+ }+}diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.javaindex 7e1c6d4791..0163c43110 100644--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java@@ -37,8 +37,8 @@ public final class GlueConstants {public static final String AWS_GLUE_CATALOG_ID = "aws-glue-catalog-id";/**- * AWS access key ID for static credential authentication (optional, not hidden). This is an- * account identifier, not a secret; {@link #AWS_SECRET_ACCESS_KEY} is the hidden half.+ * AWS access key ID for static credential authentication (optional, hidden). Identifier half of+ * the static credential pair; {@link #AWS_SECRET_ACCESS_KEY} is the secret half.*/public static final String AWS_ACCESS_KEY_ID = AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID;diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/AWSProperties.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/AWSProperties.javaindex e42842b4f6..8cc99a910b 100644--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/AWSProperties.java+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/AWSProperties.java@@ -21,7 +21,7 @@ package org.apache.gravitino.storage;/** Property names for AWS static credentials shared across catalogs. */public final class AWSProperties {- /** AWS access key ID. Not hidden. */+ /** AWS access key ID. Hidden (identifier half of a static credential pair). */public static final String GRAVITINO_AWS_ACCESS_KEY_ID = "aws-access-key-id";/** AWS secret access key. Hidden. */diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.javaindex 962c87d770..400c46fb14 100644--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java@@ -24,16 +24,23 @@ import java.util.HashMap;import java.util.Map;import java.util.Set;import javax.annotation.Nullable;+import org.apache.gravitino.catalog.lakehouse.paimon.PaimonConstants;/**- * Gravitino property keys for cloud static <em>secret</em> credentials.+ * Gravitino property keys for cloud static credentials (access-key pairs and related secrets).** <p>GVFS must not consume these keys from REST catalog/schema/fileset {@code properties()}- * responses (which may be masked as {@code ******}). Secret plaintext is recovered via {@code- * getSecrets()}. Non-secret identifiers such as {@code s3-access-key-id} / {@code- * gcs-service-account-file} remain in {@code properties()} and are merged normally. Clients may- * also supply credentials via local Hadoop {@code Configuration} or {@code getCredentials()} when- * credential vending is enabled.+ * responses (which may be masked as {@code ******}). Plaintext for hidden static credentials,+ * including {@code s3-access-key-id}, is recovered via {@code getSecrets()} when the caller holds+ * {@code USE_SECRETS} and {@code INCLUDE_CREDENTIAL_SECRETS}, or via {@code getCredentials()} (no+ * dedicated privilege). Masked placeholders are dropped by {@link #omitStaticCredentialProperties}.+ * Callers with only {@code USE_SECRETS} receive {@code getSecrets()} with cloud access-key pairs+ * omitted via {@link #omitCloudAccessKeyPairProperties}.+ *+ * <p>{@code azure-storage-account-name} is intentionally left non-hidden (and not listed here):+ * unlike S3/OSS/COS access key IDs, the account name is already disclosed in ADLS URIs such as+ * {@code abfss://[email protected]}, so masking it on load/list adds no+ * confidentiality. Only {@code azure-storage-account-key} is treated as a secret half.*/public final class CloudStorageCredentialPropertyKeys {@@ -41,18 +48,40 @@ public final class CloudStorageCredentialPropertyKeys {public static final String MASKED_PROPERTY_VALUE = "******";/**- * Secret-bearing static credential keys only. Access key IDs and GCS service-account file paths- * are intentionally excluded: they are declared non-hidden and must stay available from {@code- * properties()}.+ * Static cloud credential property keys omitted from REST {@code properties()} merges for GVFS+ * (alongside masked placeholders).*/private static final Set<String> STATIC_CREDENTIAL_KEYS =ImmutableSet.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID,OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET,AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY,AzureProperties.GRAVITINO_AZURE_CLIENT_SECRET,+ COSProperties.GRAVITINO_COS_ACCESS_KEY_ID,COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET);+ /**+ * Cloud access-key pair (and Azure static secret) keys omitted from {@code getSecrets()} when the+ * caller has {@code USE_SECRETS} but not {@code INCLUDE_CREDENTIAL_SECRETS}. JDBC secrets are+ * intentionally not listed so connectors can still recover them via {@code getSecrets()}.+ */+ private static final Set<String> CLOUD_ACCESS_KEY_PAIR_KEYS =+ ImmutableSet.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID,+ OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET,+ COSProperties.GRAVITINO_COS_ACCESS_KEY_ID,+ COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET,+ AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID,+ AWSProperties.GRAVITINO_AWS_SECRET_ACCESS_KEY,+ AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY,+ AzureProperties.GRAVITINO_AZURE_CLIENT_SECRET,+ PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_ID,+ PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_SECRET);+private CloudStorageCredentialPropertyKeys() {}/**@@ -65,6 +94,18 @@ public final class CloudStorageCredentialPropertyKeys {return key != null && STATIC_CREDENTIAL_KEYS.contains(key);}+ /**+ * Returns whether the property key is a cloud access-key pair (or Azure static secret) that+ * {@code USE_SECRETS} must not see via {@code getSecrets()} without {@code+ * INCLUDE_CREDENTIAL_SECRETS}.+ *+ * @param key the property key+ * @return true when the key must be omitted for use-secret-only callers+ */+ public static boolean isCloudAccessKeyPairKey(@Nullable String key) {+ return key != null && CLOUD_ACCESS_KEY_PAIR_KEYS.contains(key);+ }+/*** Returns a copy of {@code properties} with static credential keys and masked placeholders* removed. Used when merging REST metadata into GVFS client configuration.@@ -92,8 +133,37 @@ public final class CloudStorageCredentialPropertyKeys {return ImmutableMap.copyOf(filtered);}+ /**+ * Returns a copy of {@code secrets} with cloud access-key pair keys removed. Used when filtering+ * {@code getSecrets()} for callers that hold {@code USE_SECRETS} but not {@code+ * INCLUDE_CREDENTIAL_SECRETS}.+ *+ * @param secrets plaintext secrets map+ * @return secrets without cloud access-key pairs+ */+ public static Map<String, String> omitCloudAccessKeyPairProperties(+ @Nullable Map<String, String> secrets) {+ if (secrets == null || secrets.isEmpty()) {+ return ImmutableMap.of();+ }+ Map<String, String> filtered = new HashMap<>();+ for (Map.Entry<String, String> entry : secrets.entrySet()) {+ String key = entry.getKey();+ if (key == null || isCloudAccessKeyPairKey(key)) {+ continue;+ }+ filtered.put(key, entry.getValue());+ }+ return ImmutableMap.copyOf(filtered);+ }+/** Returns the static credential property keys. */public static Set<String> staticCredentialKeys() {return STATIC_CREDENTIAL_KEYS;}++ /** Returns cloud access-key pair keys omitted for {@code USE_SECRETS} {@code getSecrets}. */+ public static Set<String> cloudAccessKeyPairKeys() {+ return CLOUD_ACCESS_KEY_PAIR_KEYS;+ }}diff --git a/catalogs/catalog-common/src/test/java/org/apache/gravitino/storage/TestCloudStorageCredentialPropertyKeys.java b/catalogs/catalog-common/src/test/java/org/apache/gravitino/storage/TestCloudStorageCredentialPropertyKeys.javaindex b4affbee94..7319467126 100644--- a/catalogs/catalog-common/src/test/java/org/apache/gravitino/storage/TestCloudStorageCredentialPropertyKeys.java+++ b/catalogs/catalog-common/src/test/java/org/apache/gravitino/storage/TestCloudStorageCredentialPropertyKeys.java@@ -49,32 +49,47 @@ public class TestCloudStorageCredentialPropertyKeys {assertEquals("https://s3.amazonaws.com", filtered.get(S3Properties.GRAVITINO_S3_ENDPOINT));assertEquals("cn-hangzhou", filtered.get(OSSProperties.GRAVITINO_OSS_REGION));- // Access key ID is non-hidden plaintext in properties(); GVFS keeps it.- assertEquals("AKIATEST", filtered.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ // Access key IDs and secrets are stripped from properties(); recover via getSecrets /+ // getCredentials.+ assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));assertFalse(filtered.containsKey("masked-any-key"));}+ @Test+ void testOmitMaskedAccessKeyIds() {+ Map<String, String> input =+ Map.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ CloudStorageCredentialPropertyKeys.MASKED_PROPERTY_VALUE,+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ "secret");++ Map<String, String> filtered =+ CloudStorageCredentialPropertyKeys.omitStaticCredentialProperties(input);++ assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));+ }+@Testvoid testStaticCredentialKeyDetection() {assertTrue(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET));- assertFalse(+ assertTrue(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));assertFalse(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(COSProperties.GRAVITINO_COS_REGION));- // Azure client secret is a cloud-storage static credential and is stripped.assertTrue(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(AzureProperties.GRAVITINO_AZURE_CLIENT_SECRET));// Glue/Paimon-DLF secrets are catalog/metastore-connection credentials, not cloud-storage- // secrets in the fileset properties map this filter governs; they never reach it (declared- // hidden and outside FilesetCatalogPropertiesMetadata), so this set must not claim them.+ // secrets in the fileset properties map this filter governs.assertFalse(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(GlueConstants.AWS_SECRET_ACCESS_KEY));@@ -84,8 +99,6 @@ public class TestCloudStorageCredentialPropertyKeys {assertFalse(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(PaimonConstants.GRAVITINO_DLF_SECURITY_TOKEN));-- // Access key IDs are non-hidden identifiers, not secrets; they behave like s3/oss/cos IDs.assertFalse(CloudStorageCredentialPropertyKeys.isStaticCredentialKey(GlueConstants.AWS_ACCESS_KEY_ID));assertFalse(@@ -94,7 +107,7 @@ public class TestCloudStorageCredentialPropertyKeys {}@Test- void testAzureClientSecretStrippedButAccessKeyIdsSurvive() {+ void testAzureClientSecretStrippedButGlueAccessKeyIdsSurvive() {Map<String, String> input =Map.of(AzureProperties.GRAVITINO_AZURE_CLIENT_SECRET, "aad-secret",@@ -104,11 +117,45 @@ public class TestCloudStorageCredentialPropertyKeys {Map<String, String> filtered =CloudStorageCredentialPropertyKeys.omitStaticCredentialProperties(input);- // azure-client-secret is the sole branch-added cloud-storage secret this filter strips.assertFalse(filtered.containsKey(AzureProperties.GRAVITINO_AZURE_CLIENT_SECRET));-- // Access key IDs are non-hidden identifiers and must survive in properties().+ // Glue/DLF IDs are not in the fileset static cloud set; unmasked values survive here.assertEquals("ak", filtered.get(GlueConstants.AWS_ACCESS_KEY_ID));assertEquals("dlf-ak", filtered.get(PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_ID));}++ @Test+ void testOmitCloudAccessKeyPairProperties() {+ Map<String, String> secrets =+ Map.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ "AKIATEST",+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ "secret",+ "jdbc-password",+ "db-pass",+ "custom-token",+ "tok");++ Map<String, String> filtered =+ CloudStorageCredentialPropertyKeys.omitCloudAccessKeyPairProperties(secrets);++ assertEquals("db-pass", filtered.get("jdbc-password"));+ assertEquals("tok", filtered.get("custom-token"));+ assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertFalse(filtered.containsKey(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));+ }++ @Test+ void testCloudAccessKeyPairKeyDetection() {+ assertTrue(+ CloudStorageCredentialPropertyKeys.isCloudAccessKeyPairKey(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertTrue(+ CloudStorageCredentialPropertyKeys.isCloudAccessKeyPairKey(+ AWSProperties.GRAVITINO_AWS_SECRET_ACCESS_KEY));+ assertTrue(+ CloudStorageCredentialPropertyKeys.isCloudAccessKeyPairKey(+ PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_SECRET));+ assertFalse(CloudStorageCredentialPropertyKeys.isCloudAccessKeyPairKey("jdbc-password"));+ }}diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogCredential.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogCredential.javaindex 72f9326c52..9226549f13 100644--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogCredential.java+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogCredential.java@@ -97,11 +97,14 @@ public class TestFilesetCatalogCredential {FilesetCatalogImpl catalog = newCatalog(properties);Map<String, String> masked = catalog.properties();- Assertions.assertEquals("s3-ak", masked.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ Assertions.assertEquals(+ HiddenPropertyMaskUtils.MASKED_VALUE, masked.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,masked.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- Assertions.assertEquals("oss-ak", masked.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));+ Assertions.assertEquals(+ HiddenPropertyMaskUtils.MASKED_VALUE,+ masked.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,masked.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET));@@ -110,7 +113,9 @@ public class TestFilesetCatalogCredential {Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,masked.get(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY));- Assertions.assertEquals("cos-ak", masked.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));+ Assertions.assertEquals(+ HiddenPropertyMaskUtils.MASKED_VALUE,+ masked.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,masked.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET));diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCloudPropertiesMetadata.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCloudPropertiesMetadata.javaindex fe20c37d71..1cc9e1060a 100644--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCloudPropertiesMetadata.java+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCloudPropertiesMetadata.java@@ -53,12 +53,12 @@ public class TestFilesetCloudPropertiesMetadata {@ParameterizedTest@MethodSource("filesetPropertiesMetadata")void testCloudCredentialsAreHidden(PropertiesMetadata metadata) {- assertFalse(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- assertFalse(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET));assertTrue(metadata.isHiddenProperty(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY));- assertFalse(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET));}@@ -85,7 +85,9 @@ public class TestFilesetCloudPropertiesMetadata {HiddenPropertyMaskUtils.maskHiddenProperties(properties, metadata);assertEquals("s3a://bucket/path", response.get(FilesetCatalogPropertiesMetadata.LOCATION));- assertEquals("AKIATEST", response.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals(+ HiddenPropertyMaskUtils.MASKED_VALUE,+ response.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,response.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.javaindex eed35fa2fc..b9831c9acc 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java@@ -72,11 +72,11 @@ class TestGlueCatalogPropertiesMetadata {}@Test- void testCredentialsAreOptionalAndAccessKeyIdIsVisible() {+ void testCredentialsAreOptionalAndHidden() {assertFalse(metadata.isRequiredProperty(AWS_ACCESS_KEY_ID));assertFalse(metadata.isRequiredProperty(AWS_SECRET_ACCESS_KEY));- // Access key ID is an identifier, same as s3-access-key-id; only the secret is hidden.- assertFalse(metadata.isHiddenProperty(AWS_ACCESS_KEY_ID));+ // Both halves of the static pair are hidden, same as s3-access-key-id / s3-secret-access-key.+ assertTrue(metadata.isHiddenProperty(AWS_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(AWS_SECRET_ACCESS_KEY));// Same PropertyEntry instances as the shared definition, not a Glue-local copy.assertSame(diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.javaindex 508b33dda1..ee91894c26 100644--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java@@ -113,7 +113,7 @@ class TestHiveCatalogOperations {org.apache.gravitino.credential.CredentialConstants.COS_TOKEN_EXPIRE_IN_SECS));Assertions.assertTrue(propertyEntryMap.containsKey(S3Properties.GRAVITINO_S3_ROLE_ARN));Assertions.assertTrue(propertyEntryMap.containsKey(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));- Assertions.assertFalse(+ Assertions.assertTrue(propertyEntryMap.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID).isHidden());Assertions.assertTrue(propertyEntryMap.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET).isHidden());diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalog.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalog.javaindex 65bf8eb897..7ac02124f7 100644--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalog.java+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/JdbcCatalog.java@@ -152,6 +152,25 @@ public abstract class JdbcCatalog extends BaseCatalog<JdbcCatalog> {return resolved;}+ /**+ * Ensures the JDBC provider stays listed even when {@code credential-providers} was set+ * explicitly. {@code super} skips {@link #addCatalogSpecificCredentialProviders} in that case.+ * JDBC does not conflict with path-based storage providers, so it remains recoverable via {@code+ * getCredentials} alongside an explicit list.+ *+ * @return catalog properties with credential providers+ */+ @Override+ public Map<String, String> propertiesWithCredentialProviders() {+ Map<String, String> props = super.propertiesWithCredentialProviders();+ String jdbcUser = props.get(JdbcConfig.USERNAME.getKey());+ String jdbcPassword = props.get(JdbcConfig.PASSWORD.getKey());+ if (StringUtils.isNotBlank(jdbcUser) && jdbcPassword != null) {+ ensureCredentialProviderListed(props, JdbcCredential.JDBC_CREDENTIAL_TYPE);+ }+ return props;+ }+@Overrideprotected void addCatalogSpecificCredentialProviders(Map<String, String> properties, List<String> credentialProviders) {diff --git a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogCredential.java b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogCredential.javaindex 50a85aa174..9577be3e16 100644--- a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogCredential.java+++ b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/TestJdbcCatalogCredential.java@@ -277,11 +277,10 @@ public class TestJdbcCatalogCredential {}@Test- void testJdbcCatalogExplicitCredentialProvidersNotOverridden() {+ void testJdbcCatalogExplicitCredentialProvidersStillGetsJdbc() {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- // Test that explicit credential-providers setting is not overriddenMap<String, String> explicitProps = Maps.newHashMap();explicitProps.put(JdbcConfig.JDBC_URL.getKey(), "jdbc:mysql://localhost:3306/test");explicitProps.put(JdbcConfig.JDBC_DRIVER.getKey(), "com.mysql.cj.jdbc.Driver");@@ -304,8 +303,8 @@ public class TestJdbcCatalogCredential {explicitCatalog.withCatalogConf(explicitProps).withCatalogEntity(explicitEntity);Map<String, String> properties = explicitCatalog.propertiesWithCredentialProviders();- // Should keep explicit credential providers, not overrideString credentialProviders = properties.get(CredentialConstants.CREDENTIAL_PROVIDERS);- Assertions.assertEquals("custom-provider", credentialProviders);+ Assertions.assertTrue(credentialProviders.contains("custom-provider"));+ Assertions.assertTrue(credentialProviders.contains(JdbcCredential.JDBC_CREDENTIAL_TYPE));}}diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.javaindex 935112c66d..b30235201c 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java@@ -111,6 +111,18 @@ public class IcebergCatalog extends BaseCatalog<IcebergCatalog> {// Iceberg is security-first: disable s3:ListBucket on bare location prefix so a vended// credential cannot enumerate sibling keys. This is catalog-type policy, not user-configurable.props.put(CredentialConstants.S3_CREDENTIAL_LIST_LOCATION_PREFIX, "false");+ // super() skips addCatalogSpecificCredentialProviders when credential-providers is already+ // set; keep jdbc listed so getCredentials can still vend JDBC credentials alongside an+ // explicit provider list (jdbc does not conflict with path-based storage providers).+ String catalogBackend = props.get(IcebergConstants.CATALOG_BACKEND);+ if (catalogBackend != null+ && IcebergCatalogBackend.JDBC.name().equalsIgnoreCase(catalogBackend)) {+ String jdbcUser = props.get(IcebergConstants.GRAVITINO_JDBC_USER);+ String jdbcPassword = props.get(IcebergConstants.GRAVITINO_JDBC_PASSWORD);+ if (StringUtils.isNotBlank(jdbcUser) && jdbcPassword != null) {+ ensureCredentialProviderListed(props, JdbcCredential.JDBC_CREDENTIAL_TYPE);+ }+ }return props;}diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.javaindex 2c8d702594..91150b0ec2 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java@@ -370,11 +370,10 @@ public class TestIcebergCatalog {}@Test- void testExplicitCredentialProvidersNotOverridden() {+ void testExplicitCredentialProvidersStillGetsJdbc() {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- // Test that explicit credential-providers setting is not overriddenMap<String, String> explicitProps = Maps.newHashMap();explicitProps.put(IcebergConstants.CATALOG_BACKEND, "jdbc");explicitProps.put(IcebergConstants.URI, "jdbc:sqlite::memory:");@@ -397,9 +396,9 @@ public class TestIcebergCatalog {new IcebergCatalog().withCatalogConf(explicitProps).withCatalogEntity(explicitEntity);Map<String, String> properties = explicitCatalog.propertiesWithCredentialProviders();- // Should keep explicit credential providers, not overrideString credentialProviders = properties.get(CredentialConstants.CREDENTIAL_PROVIDERS);- Assertions.assertEquals("custom-provider", credentialProviders);+ Assertions.assertTrue(credentialProviders.contains("custom-provider"));+ Assertions.assertTrue(credentialProviders.contains(JdbcCredential.JDBC_CREDENTIAL_TYPE));}@Testdiff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogPropertiesMetadata.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogPropertiesMetadata.javaindex 33921b1c54..75d64d295a 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogPropertiesMetadata.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogPropertiesMetadata.java@@ -46,10 +46,10 @@ public class TestIcebergCatalogPropertiesMetadata {}@Test- void testCloudAccessKeyIdsAreVisibleAndSecretsAreHidden() {- Assertions.assertFalse(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ void testCloudAccessKeyIdsAndSecretsAreHidden() {+ Assertions.assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));Assertions.assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- Assertions.assertFalse(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));+ Assertions.assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));Assertions.assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET));}diff --git a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogPropertiesMetadata.java b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogPropertiesMetadata.javaindex cd8d37ddcb..bdfe09903a 100644--- a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogPropertiesMetadata.java+++ b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogPropertiesMetadata.java@@ -35,14 +35,15 @@ public class TestPaimonCatalogPropertiesMetadata {@Testvoid testSensitivePropertiesAreHidden() {assertTrue(metadata.isHiddenProperty(PaimonCatalogPropertiesMetadata.GRAVITINO_JDBC_PASSWORD));- assertFalse(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- assertFalse(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET));assertTrue(metadata.isHiddenProperty(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY));- assertFalse(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET));- // REST bearer token and DLF secrets are hidden; DLF access-key-id matches OSS/S3 (visible).+ // REST bearer token and DLF secret halves are hidden; DLF access-key-id stays visible until+ // a dedicated credential type lands.assertTrue(metadata.isHiddenProperty(PaimonConstants.TOKEN));assertFalse(metadata.isHiddenProperty(PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(PaimonConstants.GRAVITINO_DLF_ACCESS_KEY_SECRET));diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/FilesetAuthorizationIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/FilesetAuthorizationIT.javaindex 1c4a53c39e..a651dda514 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/FilesetAuthorizationIT.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/FilesetAuthorizationIT.java@@ -371,7 +371,7 @@ public class FilesetAuthorizationIT extends BaseRestApiAuthorizationIT {@Test@Order(8)- public void testUseSecretPrivilegeForGetSecrets() {+ public void testUseSecretsPrivilegeForGetSecrets() {String filesetName = "secret_fileset";String secretKey = "access_token";String secretValue = "plain-token-value";@@ -404,7 +404,8 @@ public class FilesetAuthorizationIT extends BaseRestApiAuthorizationIT {assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, readableFileset.properties().get(secretKey));assertEquals("visible-value", readableFileset.properties().get("visible-key"));- // Can load the object but lacks USE_SECRET → empty secrets (not ForbiddenException).+ // Can load the object but lacks USE_SECRETS → empty secrets+ // (not ForbiddenException).Map<String, String> secretsWithoutPrivilege = readableFileset.supportsSecrets().getSecrets();assertTrue(secretsWithoutPrivilege.isEmpty());@@ -413,7 +414,7 @@ public class FilesetAuthorizationIT extends BaseRestApiAuthorizationIT {MetadataObject schemaObject =MetadataObjects.of(ImmutableList.of(CATALOG, SCHEMA), MetadataObject.Type.SCHEMA);gravitinoMetalake.grantPrivilegesToRole(- role, schemaObject, ImmutableList.of(Privileges.UseSecret.allow()));+ role, schemaObject, ImmutableList.of(Privileges.UseSecrets.allow()));assertEquals(secretValue,normalFilesetCatalog@@ -424,16 +425,16 @@ public class FilesetAuthorizationIT extends BaseRestApiAuthorizationIT {// DENY on the fileset overrides schema-level allow → empty again.gravitinoMetalake.grantPrivilegesToRole(- role, filesetObject, ImmutableList.of(Privileges.UseSecret.deny()));+ role, filesetObject, ImmutableList.of(Privileges.UseSecrets.deny()));assertTrue(normalFilesetCatalog.loadFileset(filesetIdent).supportsSecrets().getSecrets().isEmpty());gravitinoMetalake.revokePrivilegesFromRole(- role, schemaObject, ImmutableSet.of(Privileges.UseSecret.allow()));+ role, schemaObject, ImmutableSet.of(Privileges.UseSecrets.allow()));gravitinoMetalake.revokePrivilegesFromRole(role,filesetObject,- ImmutableSet.of(Privileges.ReadFileset.allow(), Privileges.UseSecret.deny()));+ ImmutableSet.of(Privileges.ReadFileset.allow(), Privileges.UseSecrets.deny()));adminFilesetCatalog.dropFileset(filesetIdent);}diff --git a/clients/client-python/gravitino/api/authorization/privileges.py b/clients/client-python/gravitino/api/authorization/privileges.pyindex 41402b9e63..fe14715d9a 100644--- a/clients/client-python/gravitino/api/authorization/privileges.py+++ b/clients/client-python/gravitino/api/authorization/privileges.py@@ -201,8 +201,11 @@ class Privilege(ABC):VIEW_SECRET_PROVIDERS = (0, 1 << 36)"""The privilege to list configured secrets providers."""- USE_SECRET = (0, 1 << 37)- """The privilege to retrieve plaintext secrets and vend credentials."""+ USE_SECRETS = (0, 1 << 37)+ """Required to call getSecrets; cloud AK/SK omitted without INCLUDE_CREDENTIAL_SECRETS."""++ INCLUDE_CREDENTIAL_SECRETS = (0, 1 << 38)+ """With USE_SECRETS, include cloud credential secrets in the getSecrets result."""def __init__(self, high_bits: int, low_bits: int) -> None:"""@@ -1680,27 +1683,53 @@ class ViewSecretProviders(GenericPrivilege):return obj_type == MetadataObject.Type.METALAKE-class UseSecret(GenericPrivilege):- """The privilege to retrieve plaintext secrets and vend credentials."""+class UseSecrets(GenericPrivilege):+ """Required to call getSecrets; cloud AK/SK omitted without INCLUDE_CREDENTIAL_SECRETS."""++ _ALLOW_INSTANCE: Optional["UseSecrets"] = None+ _DENY_INSTANCE: Optional["UseSecrets"] = None++ @staticmethod+ def allow() -> Privilege:+ if UseSecrets._ALLOW_INSTANCE is None:+ UseSecrets._ALLOW_INSTANCE = UseSecrets(+ Privilege.Condition.ALLOW, Privilege.Name.USE_SECRETS+ )+ return UseSecrets._ALLOW_INSTANCE++ @staticmethod+ def deny() -> Privilege:+ if UseSecrets._DENY_INSTANCE is None:+ UseSecrets._DENY_INSTANCE = UseSecrets(+ Privilege.Condition.DENY, Privilege.Name.USE_SECRETS+ )+ return UseSecrets._DENY_INSTANCE++ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:+ return obj_type in Privileges.SECRET_SUPPORTED_TYPES+++class IncludeCredentialSecrets(GenericPrivilege):+ """With USE_SECRETS, include cloud credential secrets in the getSecrets result."""- _ALLOW_INSTANCE: Optional["UseSecret"] = None- _DENY_INSTANCE: Optional["UseSecret"] = None+ _ALLOW_INSTANCE: Optional["IncludeCredentialSecrets"] = None+ _DENY_INSTANCE: Optional["IncludeCredentialSecrets"] = None@staticmethoddef allow() -> Privilege:- if UseSecret._ALLOW_INSTANCE is None:- UseSecret._ALLOW_INSTANCE = UseSecret(- Privilege.Condition.ALLOW, Privilege.Name.USE_SECRET+ if IncludeCredentialSecrets._ALLOW_INSTANCE is None:+ IncludeCredentialSecrets._ALLOW_INSTANCE = IncludeCredentialSecrets(+ Privilege.Condition.ALLOW, Privilege.Name.INCLUDE_CREDENTIAL_SECRETS)- return UseSecret._ALLOW_INSTANCE+ return IncludeCredentialSecrets._ALLOW_INSTANCE@staticmethoddef deny() -> Privilege:- if UseSecret._DENY_INSTANCE is None:- UseSecret._DENY_INSTANCE = UseSecret(- Privilege.Condition.DENY, Privilege.Name.USE_SECRET+ if IncludeCredentialSecrets._DENY_INSTANCE is None:+ IncludeCredentialSecrets._DENY_INSTANCE = IncludeCredentialSecrets(+ Privilege.Condition.DENY, Privilege.Name.INCLUDE_CREDENTIAL_SECRETS)- return UseSecret._DENY_INSTANCE+ return IncludeCredentialSecrets._DENY_INSTANCEdef can_bind_to(self, obj_type: MetadataObject.Type) -> bool:return obj_type in Privileges.SECRET_SUPPORTED_TYPES@@ -1743,7 +1772,8 @@ class Privileges:Privilege.Name.REGISTER_FUNCTION: RegisterFunction,Privilege.Name.EXECUTE_FUNCTION: ExecuteFunction,Privilege.Name.MODIFY_FUNCTION: ModifyFunction,- Privilege.Name.USE_SECRET: UseSecret,+ Privilege.Name.USE_SECRETS: UseSecrets,+ Privilege.Name.INCLUDE_CREDENTIAL_SECRETS: IncludeCredentialSecrets,}TABLE_SUPPORTED_TYPES = {diff --git a/clients/client-python/gravitino/api/catalog_change.py b/clients/client-python/gravitino/api/catalog_change.pyindex c80cd9675c..b6c14de16c 100644--- a/clients/client-python/gravitino/api/catalog_change.py+++ b/clients/client-python/gravitino/api/catalog_change.py@@ -313,8 +313,7 @@ class CatalogChange(ABC):if not isinstance(other, CatalogChange.SetSecretBinding):return Falsereturn (- self._property == other.property()- and self._binding == other.binding()+ self._property == other.property() and self._binding == other.binding())def __hash__(self):diff --git a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py b/clients/client-python/gravitino/filesystem/gvfs_base_operations.pyindex 71cac7801d..56d8351bbf 100644--- a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py+++ b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py@@ -22,6 +22,7 @@ import timefrom abc import ABC, abstractmethodfrom pathlib import PurePosixPathfrom typing import Dict, Tuple, Optional, List+from urllib.error import URLErrorfrom urllib.parse import urlparsefrom cachetools import TTLCache, LRUCache@@ -40,7 +41,10 @@ from gravitino.client.fileset_catalog import FilesetCatalogfrom gravitino.client.gravitino_client_config import GravitinoClientConfigfrom gravitino.exceptions.base import (GravitinoRuntimeException,+ NoSuchCredentialException,NoSuchLocationNameException,+ NotFoundException,+ RESTException,)from gravitino.filesystem.gvfs_config import GVFSConfigfrom gravitino.filesystem.gvfs_storage_handler import get_storage_handler_by_path@@ -57,6 +61,16 @@ PROTOCOL_NAME = "gvfs"TIME_WITHOUT_EXPIRATION = sys.maxsize+# Maps Gravitino credentialInfo / catalog property keys to Python GVFS option names.+_CREDENTIAL_INFO_TO_GVFS_KEYS = {+ "s3-access-key-id": GVFSConfig.GVFS_FILESYSTEM_S3_ACCESS_KEY,+ "s3-secret-access-key": GVFSConfig.GVFS_FILESYSTEM_S3_SECRET_KEY,+ "oss-access-key-id": GVFSConfig.GVFS_FILESYSTEM_OSS_ACCESS_KEY,+ "oss-secret-access-key": GVFSConfig.GVFS_FILESYSTEM_OSS_SECRET_KEY,+ "azure-storage-account-name": GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_NAME,+ "azure-storage-account-key": GVFSConfig.GVFS_FILESYSTEM_AZURE_ACCOUNT_KEY,+}+class FileSystemCacheKey:"""@@ -500,9 +514,11 @@ class BaseGVFSOperations(ABC):) -> Dict[str, str]:"""Merge properties from catalog, schema, fileset, options, and configs.- Combines default load*.properties() with get_secrets() so every secret URN- (including keys that may also appear in credential vending) becomes plaintext- for FS access. Typed credentials remain available via get_credentials.+ Combines default load*.properties() with get_secrets() for non-credential+ secrets, and static catalog get_credentials().credential_info()+ (expire_time_in_ms == 0 only) for cloud/JDBC credential fields. Typed path+ credentials remain available via get_credentials on the fileset when+ credential vending is enabled.:param fileset_ident: The fileset identifier:param actual_location: The actual storage location@@ -517,6 +533,7 @@ class BaseGVFSOperations(ABC):)fileset_props = dict(catalog.properties() or {})fileset_props.update(catalog.get_secrets())+ self._merge_static_catalog_credentials(fileset_props, catalog)fileset_props.update(schema.properties() or {})fileset_props.update(schema.get_secrets())fileset_props.update(fileset.properties() or {})@@ -529,6 +546,67 @@ class BaseGVFSOperations(ABC):fileset_props.update(user_defined_configs)return fileset_props+ def _merge_static_catalog_credentials(+ self, fileset_props: Dict[str, str], catalog+ ) -> None:+ """Overlay static catalog credential_info into fileset_props.++ Called when a filesystem is created, so results are not cached here — rotated+ keys are picked up on the next filesystem build.+ """+ loaded = self._load_static_catalog_credential_info(catalog)+ if loaded:+ fileset_props.update(loaded)++ @staticmethod+ def _load_static_catalog_credential_info(catalog) -> Optional[Dict[str, str]]:+ """Load expire==0 credential_info and map keys to GVFS option names.++ Returns an empty dict when credentials are unsupported or absent.+ Returns None on transient REST failure.+ """+ static_info: Dict[str, str] = {}+ try:+ supports_credentials = catalog.support_credentials()+ for credential in supports_credentials.get_credentials() or []:+ if credential is None:+ continue+ if credential.expire_time_in_ms() != 0:+ continue+ info = credential.credential_info() or {}+ for key, value in info.items():+ if value is None:+ continue+ static_info[key] = value+ gvfs_key = _CREDENTIAL_INFO_TO_GVFS_KEYS.get(key)+ if gvfs_key:+ static_info[gvfs_key] = value+ except (+ AttributeError,+ NotImplementedError,+ TypeError,+ NotFoundException,+ NoSuchCredentialException,+ ) as exc:+ logger.debug(+ "Catalog does not support credential recovery via get_credentials: %s",+ exc,+ )+ except RESTException as exc:+ logger.warning(+ "Failed to load static credentials via get_credentials; continuing without them: %s",+ exc,+ )+ return None+ except URLError as exc:+ # Transport failures (e.g. connection refused) are not wrapped as RESTException.+ logger.warning(+ "Failed to load static credentials via get_credentials; continuing without them: %s",+ exc,+ )+ return None+ return static_info+def _get_actual_filesystem_by_location_name(self, fileset_ident: NameIdentifier, location_name: str) -> AbstractFileSystem:diff --git a/clients/client-python/tests/unittests/test_filesystem_cache.py b/clients/client-python/tests/unittests/test_filesystem_cache.pyindex 5e9b4f4a66..400b726455 100644--- a/clients/client-python/tests/unittests/test_filesystem_cache.py+++ b/clients/client-python/tests/unittests/test_filesystem_cache.py@@ -43,6 +43,10 @@ from gravitino.filesystem.gvfs_config import GVFSConfigfrom tests.unittests import mock_base+@patch(+ "gravitino.client.fileset_catalog.FilesetCatalog.get_credentials",+ return_value=[],+)@patch("gravitino.client.generic_fileset.GenericFileset.get_credentials",return_value=[],@@ -182,8 +186,8 @@ class TestFileSystemCache(unittest.TestCase):self.assertEqual(len(results), 10, "All threads should complete")self.assertTrue(all(results), "All threads should see file exists")- # With thread-specific caching (like fsspec), each thread gets its own entry- # This is different from Java GVFS but matches Python ecosystem conventions+ # Main-thread touch() plus one entry per worker thread (thread_id is in the+ # cache key). Default TTLCache maxsize is 20, so all of them can remain.# pylint: disable=protected-accesscache_size = len(fs._operations._filesystem_cache)self.assertGreaterEqual(@@ -193,8 +197,9 @@ class TestFileSystemCache(unittest.TestCase):)self.assertLessEqual(cache_size,- 10,- f"Expected at most 10 cached filesystems (one per thread), but found {cache_size}",+ 11,+ f"Expected at most 11 cached filesystems (main thread + 10 workers), "+ f"but found {cache_size}",)def test_thread_isolation(self, *mock_methods):diff --git a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.pyindex e13319dd9d..f26f3aaaf4 100644--- a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py+++ b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py@@ -16,7 +16,9 @@# under the License.import unittestfrom unittest.mock import MagicMock, patch+from urllib.error import URLError+from gravitino.exceptions.base import NotFoundException, RESTExceptionfrom gravitino.filesystem.gvfs_default_operations import DefaultGVFSOperationsfrom gravitino.name_identifier import NameIdentifier@@ -25,6 +27,26 @@ from gravitino.name_identifier import NameIdentifierclass TestGVFSMergeSecrets(unittest.TestCase):"""Unit tests for _merge_fileset_properties including get_secrets()."""+ def _merge_with_catalog(self, operations, catalog):+ schema = MagicMock()+ fileset = MagicMock()+ catalog.as_schemas.return_value.load_schema.return_value = schema+ schema.properties.return_value = {}+ schema.get_secrets.return_value = {}+ catalog.as_fileset_catalog.return_value.load_fileset.return_value = fileset+ fileset.properties.return_value = {}+ fileset.get_secrets.return_value = {}++ client = MagicMock()+ client.load_catalog.return_value = catalog++ with patch.object(operations, "_get_gravitino_client", return_value=client):+ with patch.object(operations, "_get_user_defined_configs", return_value={}):+ return operations._merge_fileset_properties(+ NameIdentifier.of("ml", "catalog", "schema", "fs"),+ "s3://bucket/data",+ )+def test_merge_secrets(self):operations = DefaultGVFSOperations(server_uri="http://localhost:8090", metalake_name="ml", options={}@@ -120,6 +142,148 @@ class TestGVFSMergeSecrets(unittest.TestCase):self.assertEqual(merged["f-secret"], "fs")self.assertEqual(len(merged), 3)+ def test_static_catalog_credentials_map_to_gvfs_keys(self):+ operations = DefaultGVFSOperations(+ server_uri="http://localhost:8090", metalake_name="ml", options={}+ )++ catalog = MagicMock()+ schema = MagicMock()+ fileset = MagicMock()+ catalog.name.return_value = "catalog"+ catalog.properties.return_value = {}+ catalog.get_secrets.return_value = {}+ catalog.as_schemas.return_value.load_schema.return_value = schema+ schema.properties.return_value = {}+ schema.get_secrets.return_value = {}+ catalog.as_fileset_catalog.return_value.load_fileset.return_value = fileset+ fileset.properties.return_value = {}+ fileset.get_secrets.return_value = {}++ credential = MagicMock()+ credential.expire_time_in_ms.return_value = 0+ credential.credential_info.return_value = {+ "s3-access-key-id": "AKIATEST",+ "s3-secret-access-key": "secret",+ }+ catalog.support_credentials.return_value.get_credentials.return_value = [+ credential+ ]++ client = MagicMock()+ client.load_catalog.return_value = catalog++ with patch.object(operations, "_get_gravitino_client", return_value=client):+ with patch.object(operations, "_get_user_defined_configs", return_value={}):+ merged = operations._merge_fileset_properties(+ NameIdentifier.of("ml", "catalog", "schema", "fs"),+ "s3://bucket/data",+ )++ self.assertEqual(merged["s3-access-key-id"], "AKIATEST")+ self.assertEqual(merged["s3_access_key_id"], "AKIATEST")+ self.assertEqual(merged["s3-secret-access-key"], "secret")+ self.assertEqual(merged["s3_secret_access_key"], "secret")+ catalog.support_credentials.return_value.get_credentials.assert_called_once()++ # No permanent static-credential cache: each merge reloads get_credentials.+ with patch.object(operations, "_get_gravitino_client", return_value=client):+ with patch.object(operations, "_get_user_defined_configs", return_value={}):+ operations._merge_fileset_properties(+ NameIdentifier.of("ml", "catalog", "schema", "fs"),+ "s3://bucket/data",+ )+ self.assertEqual(+ catalog.support_credentials.return_value.get_credentials.call_count, 2+ )++ def test_rest_failure_retries_static_credentials_on_next_merge(self):+ operations = DefaultGVFSOperations(+ server_uri="http://localhost:8090", metalake_name="ml", options={}+ )++ catalog = MagicMock()+ catalog.name.return_value = "catalog"+ catalog.properties.return_value = {}+ catalog.get_secrets.return_value = {}++ credential = MagicMock()+ credential.expire_time_in_ms.return_value = 0+ credential.credential_info.return_value = {+ "s3-access-key-id": "AKIATEST",+ "s3-secret-access-key": "secret-after-retry",+ }+ supports = MagicMock()+ supports.get_credentials.side_effect = [+ RESTException("transient failure"),+ [credential],+ ]+ catalog.support_credentials.return_value = supports++ first = self._merge_with_catalog(operations, catalog)+ self.assertNotIn("s3-access-key-id", first)++ second = self._merge_with_catalog(operations, catalog)+ self.assertEqual(second["s3-access-key-id"], "AKIATEST")+ self.assertEqual(second["s3_access_key_id"], "AKIATEST")+ self.assertEqual(supports.get_credentials.call_count, 2)++ def test_get_credentials_failures_do_not_abort_merge(self):+ for exc in (+ NotFoundException("credentials endpoint missing"),+ URLError("connection refused"),+ ):+ with self.subTest(exc=type(exc).__name__):+ operations = DefaultGVFSOperations(+ server_uri="http://localhost:8090", metalake_name="ml", options={}+ )+ catalog = MagicMock()+ catalog.name.return_value = "catalog"+ catalog.properties.return_value = {+ "s3-endpoint": "http://s3.example.com"+ }+ catalog.get_secrets.return_value = {}+ catalog.support_credentials.return_value.get_credentials.side_effect = (+ exc+ )++ merged = self._merge_with_catalog(operations, catalog)+ self.assertEqual(merged["s3-endpoint"], "http://s3.example.com")+ self.assertNotIn("s3-access-key-id", merged)++ def test_skips_expiring_credentials(self):+ operations = DefaultGVFSOperations(+ server_uri="http://localhost:8090", metalake_name="ml", options={}+ )+ catalog = MagicMock()+ catalog.name.return_value = "catalog"+ catalog.properties.return_value = {}+ catalog.get_secrets.return_value = {}++ token = MagicMock()+ token.expire_time_in_ms.return_value = 1_700_000_000_000+ token.credential_info.return_value = {+ "s3-access-key-id": "SESSION",+ "s3-secret-access-key": "session-secret",+ "s3-session-token": "tok",+ }+ static = MagicMock()+ static.expire_time_in_ms.return_value = 0+ static.credential_info.return_value = {+ "s3-access-key-id": "AKIATEST",+ "s3-secret-access-key": "static-secret",+ }+ catalog.support_credentials.return_value.get_credentials.return_value = [+ token,+ static,+ ]++ merged = self._merge_with_catalog(operations, catalog)+ self.assertEqual(merged["s3-access-key-id"], "AKIATEST")+ self.assertEqual(merged["s3_access_key_id"], "AKIATEST")+ self.assertEqual(merged["s3-secret-access-key"], "static-secret")+ self.assertNotIn("s3-session-token", merged)+if __name__ == "__main__":unittest.main()diff --git a/clients/client-python/tests/unittests/test_gvfs_with_hook.py b/clients/client-python/tests/unittests/test_gvfs_with_hook.pyindex 900c5ac065..07074c7684 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_hook.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_hook.py@@ -329,6 +329,10 @@ class MockGVFSHook(GravitinoVirtualFileSystemHook):super().on_modified_failure(path, exception)+@patch(+ "gravitino.client.fileset_catalog.FilesetCatalog.get_credentials",+ return_value=[],+)@patch("gravitino.client.generic_fileset.GenericFileset.get_credentials",return_value=[],diff --git a/clients/client-python/tests/unittests/test_gvfs_with_local.py b/clients/client-python/tests/unittests/test_gvfs_with_local.pyindex 88c6003fb9..d7537e7502 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_local.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_local.py@@ -59,6 +59,10 @@ def generate_unique_random_string(length):return random_string+@patch(+ "gravitino.client.fileset_catalog.FilesetCatalog.get_credentials",+ return_value=[],+)@patch("gravitino.client.generic_fileset.GenericFileset.get_credentials",return_value=[],diff --git a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.javaindex 5598a7965f..ae9c6c4ffd 100644--- a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java+++ b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java@@ -73,11 +73,14 @@ import org.apache.gravitino.catalog.hadoop.fs.HDFSFileSystemProxy;import org.apache.gravitino.catalog.hadoop.fs.SupportsCredentialVending;import org.apache.gravitino.client.GravitinoClient;import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.GravitinoRuntimeException;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchFilesetException;import org.apache.gravitino.exceptions.NoSuchLocationNameException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetCatalog;import org.apache.gravitino.secret.SupportsSecrets;@@ -157,6 +160,7 @@ public abstract class BaseGVFSOperations implements Closeable {private final boolean enableCredentialVending;private final boolean autoCreateLocation;+/** A key class for caching FileSystem instances based on scheme, authority, and configuration. */public static class FileSystemCacheKey {private final String scheme;@@ -974,6 +978,7 @@ public abstract class BaseGVFSOperations implements Closeable {Map<String, String> all = new HashMap<>();putPropsAndSecrets(all, catalog.properties(), catalog.supportsSecrets());+ putStaticCatalogCredentialInfo(all, catalog);putPropsAndSecrets(all, schema.properties(), schema.supportsSecrets());putPropsAndSecrets(all, fileset.properties(), fileset.supportsSecrets());all.putAll(extractNonDefaultConfig(conf));@@ -990,6 +995,64 @@ public abstract class BaseGVFSOperations implements Closeable {}}+ /**+ * Merges static ({@code expireTimeInMs == 0}) {@link Credential#credentialInfo()} from catalog+ * {@code getCredentials} into GVFS configuration. Invoked when a filesystem is created, so+ * results are not cached here — rotated keys are picked up on the next filesystem build. Expiring+ * credentials are skipped; path token vending uses a separate fileset path.+ */+ private void putStaticCatalogCredentialInfo(Map<String, String> target, Catalog catalog) {+ if (catalog == null) {+ return;+ }+ Map<String, String> loaded = loadStaticCatalogCredentialInfo(catalog);+ if (loaded != null && !loaded.isEmpty()) {+ target.putAll(loaded);+ }+ }++ /**+ * Loads static catalog credential info.+ *+ * @return a map of static credential info (may be empty), or {@code null} if loading failed+ * transiently+ */+ @Nullable+ private static Map<String, String> loadStaticCatalogCredentialInfo(Catalog catalog) {+ Map<String, String> staticInfo = new HashMap<>();+ try {+ SupportsCredentials supportsCredentials = catalog.supportsCredentials();+ if (supportsCredentials == null) {+ return staticInfo;+ }+ Credential[] credentials = supportsCredentials.getCredentials();+ if (credentials == null) {+ return staticInfo;+ }+ for (Credential credential : credentials) {+ if (credential == null+ || credential.expireTimeInMs() != 0+ || credential.credentialInfo() == null) {+ continue;+ }+ staticInfo.putAll(credential.credentialInfo());+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ LOG.debug(+ "Catalog {} does not support credential recovery via getCredentials: {}",+ catalog.name(),+ e.toString());+ } catch (RESTException e) {+ LOG.warn(+ "Failed to load static credentials for catalog {} via getCredentials; continuing without"+ + " them: {}",+ catalog.name(),+ e.toString());+ return null;+ }+ return staticInfo;+ }+private Map<String, String> getNecessaryProperties(Map<String, String> properties) {return properties.entrySet().stream().filter(property -> CATALOG_NECESSARY_PROPERTIES_TO_KEEP.contains(property.getKey()))diff --git a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/GravitinoMockServerBase.java b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/GravitinoMockServerBase.javaindex aa8b1b6784..1e21365a50 100644--- a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/GravitinoMockServerBase.java+++ b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/GravitinoMockServerBase.java@@ -33,8 +33,10 @@ import org.apache.gravitino.Version;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.dto.CatalogDTO;import org.apache.gravitino.dto.MetalakeDTO;+import org.apache.gravitino.dto.credential.CredentialDTO;import org.apache.gravitino.dto.file.FilesetDTO;import org.apache.gravitino.dto.responses.CatalogResponse;+import org.apache.gravitino.dto.responses.CredentialResponse;import org.apache.gravitino.dto.responses.FilesetResponse;import org.apache.gravitino.dto.responses.MetalakeResponse;import org.apache.gravitino.dto.responses.SecretsResponse;@@ -69,6 +71,7 @@ public abstract class GravitinoMockServerBase {port = mockServer.getLocalPort();mockAPIVersion();mockEmptySecretsAPI();+ mockEmptyCredentialsAPI();}@AfterEach@@ -76,6 +79,7 @@ public abstract class GravitinoMockServerBase {mockServer.reset();mockAPIVersion();mockEmptySecretsAPI();+ mockEmptyCredentialsAPI();}@AfterAll@@ -151,6 +155,23 @@ public abstract class GravitinoMockServerBase {}}+ /** Mocks metadata-object credentials endpoints used by {@code getAllProperties}. */+ protected static void mockEmptyCredentialsAPI() {+ try {+ String emptyCredentialsJson =+ MAPPER.writeValueAsString(new CredentialResponse(new CredentialDTO[] {}));+ mockServer+ .when(+ HttpRequest.request()+ .withMethod("GET")+ .withPath("/api/metalakes/.*/objects/.*/.*/credentials"),+ Times.unlimited())+ .respond(HttpResponse.response().withStatusCode(SC_OK).withBody(emptyCredentialsJson));+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }+ }+protected static void mockMetalakeDTO(String name, String comment) {MetalakeDTO mockMetalake =MetalakeDTO.builder()diff --git a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.javaindex 8b43487571..a612485d76 100644--- a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java+++ b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java@@ -30,9 +30,15 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Schema;import org.apache.gravitino.SupportsSchemas;import org.apache.gravitino.client.GravitinoClient;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.S3SecretKeyCredential;+import org.apache.gravitino.credential.S3TokenCredential;+import org.apache.gravitino.credential.SupportsCredentials;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetCatalog;import org.apache.gravitino.secret.SupportsSecrets;+import org.apache.gravitino.storage.CloudStorageCredentialPropertyKeys;import org.apache.gravitino.storage.S3Properties;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FSDataInputStream;@@ -225,32 +231,99 @@ public class TestBaseGVFSOperationsSecrets {}@Test- public void testKeepsPlaintextAccessKeyIdFromRestProperties() throws Exception {+ public void testRecoversAccessKeyPairFromGetCredentialsWhenPropertiesAreMasked()+ throws Exception {+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials())+ .thenReturn(+ new Credential[] {new S3SecretKeyCredential("AKIATEST", "secret-from-getCredentials")});+ Catalog catalog =+ mockCatalogWithCredentials(+ Map.of(+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ CloudStorageCredentialPropertyKeys.MASKED_PROPERTY_VALUE,+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ CloudStorageCredentialPropertyKeys.MASKED_PROPERTY_VALUE,+ "s3-endpoint",+ "http://s3.example.com"),+ credentials);++ Map<String, String> all = getAllProperties(catalog);++ assertEquals("AKIATEST", all.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals(+ "secret-from-getCredentials", all.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));+ assertEquals("http://s3.example.com", all.get("s3-endpoint"));+ }++ @Test+ public void testRestFailureDoesNotCacheEmptyStaticCredentials() throws Exception {+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials())+ .thenThrow(new RESTException("transient failure"))+ .thenReturn(new Credential[] {new S3SecretKeyCredential("AKIATEST", "secret-after-retry")});+ Catalog catalog =+ mockCatalogWithCredentials(Map.of("s3-endpoint", "http://s3.example.com"), credentials);++ TestOps ops = opsFor(catalog);+ NameIdentifier ident = NameIdentifier.of("ml", "catalog", "schema", "fs");++ Map<String, String> first = ops.getAllProperties(ident);+ assertFalse(first.containsKey(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals("http://s3.example.com", first.get("s3-endpoint"));++ Map<String, String> second = ops.getAllProperties(ident);+ assertEquals("AKIATEST", second.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals("secret-after-retry", second.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));+ }++ @Test+ public void testSkipsExpiringCredentialsFromGetCredentials() throws Exception {+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials())+ .thenReturn(+ new Credential[] {+ new S3TokenCredential("SESSION", "session-secret", "tok", 1_700_000_000_000L),+ new S3SecretKeyCredential("AKIATEST", "static-secret")+ });+ Catalog catalog =+ mockCatalogWithCredentials(Map.of("s3-endpoint", "http://s3.example.com"), credentials);++ Map<String, String> all = getAllProperties(catalog);++ assertEquals("AKIATEST", all.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals("static-secret", all.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));+ assertFalse(all.containsKey("s3-session-token"));+ }++ private static Map<String, String> getAllProperties(Catalog catalog) throws Exception {+ return opsFor(catalog).getAllProperties(NameIdentifier.of("ml", "catalog", "schema", "fs"));+ }++ private static TestOps opsFor(Catalog catalog) {Configuration conf = new Configuration();conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY, "ml");conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,"http://localhost:8090");+ GravitinoClient client = mock(GravitinoClient.class);+ when(client.loadCatalog("catalog")).thenReturn(catalog);+ return new TestOps(conf, client);+ }+ /** Mocks catalog/schema/fileset chain with the given catalog props and credentials. */+ private static Catalog mockCatalogWithCredentials(+ Map<String, String> catalogProps, SupportsCredentials credentials) {Catalog catalog = mock(Catalog.class);Schema schema = mock(Schema.class);Fileset fileset = mock(Fileset.class);SupportsSchemas schemas = mock(SupportsSchemas.class);FilesetCatalog filesetCatalog = mock(FilesetCatalog.class);- SupportsSecrets catalogSecrets = mock(SupportsSecrets.class);- when(catalog.properties())- .thenReturn(- Map.of(- S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,- "AKIATEST",- S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,- "******",- "s3-endpoint",- "http://s3.example.com"));- when(catalog.supportsSecrets()).thenReturn(catalogSecrets);- when(catalogSecrets.getSecrets())- .thenReturn(Map.of(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY, "secret-from-getSecrets"));+ when(catalog.name()).thenReturn("catalog");+ when(catalog.properties()).thenReturn(catalogProps);+ when(catalog.supportsSecrets()).thenReturn(null);+ when(catalog.supportsCredentials()).thenReturn(credentials);when(catalog.asSchemas()).thenReturn(schemas);when(schemas.loadSchema("schema")).thenReturn(schema);when(schema.properties()).thenReturn(Map.of());@@ -259,17 +332,7 @@ public class TestBaseGVFSOperationsSecrets {when(filesetCatalog.loadFileset(NameIdentifier.of("schema", "fs"))).thenReturn(fileset);when(fileset.properties()).thenReturn(Map.of());when(fileset.supportsSecrets()).thenReturn(null);-- GravitinoClient client = mock(GravitinoClient.class);- when(client.loadCatalog("catalog")).thenReturn(catalog);-- TestOps ops = new TestOps(conf, client);- Map<String, String> all =- ops.getAllProperties(NameIdentifier.of("ml", "catalog", "schema", "fs"));-- assertEquals("AKIATEST", all.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));- assertEquals("secret-from-getSecrets", all.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- assertEquals("http://s3.example.com", all.get("s3-endpoint"));+ return catalog;}private static final class TestOps extends BaseGVFSOperations {diff --git a/core/src/main/java/org/apache/gravitino/cloud/storage/AWSPropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/cloud/storage/AWSPropertiesMetadata.javaindex 4c8cb94df4..10b3455194 100644--- a/core/src/main/java/org/apache/gravitino/cloud/storage/AWSPropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/cloud/storage/AWSPropertiesMetadata.java@@ -28,7 +28,7 @@ import org.apache.gravitino.storage.AWSProperties;/** Shared AWS credential {@link PropertyEntry} definitions for catalog properties metadata. */public final class AWSPropertiesMetadata {- /** AWS access key ID. Not hidden. */+ /** AWS access key ID. Hidden (identifier half of a static credential pair). */public static final PropertyEntry<String> AWS_ACCESS_KEY_ID =stringOptionalPropertyEntry(AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID,@@ -36,7 +36,7 @@ public final class AWSPropertiesMetadata {+ " When omitted the default credential chain is used.",false /* immutable */,null /* defaultValue */,- false /* hidden */);+ true /* hidden */);/** AWS secret access key. Hidden. */public static final PropertyEntry<String> AWS_SECRET_ACCESS_KEY =diff --git a/core/src/main/java/org/apache/gravitino/cloud/storage/AzurePropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/cloud/storage/AzurePropertiesMetadata.javaindex a4c3827191..d7ad34adb3 100644--- a/core/src/main/java/org/apache/gravitino/cloud/storage/AzurePropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/cloud/storage/AzurePropertiesMetadata.java@@ -32,6 +32,7 @@ public class AzurePropertiesMetadata {ImmutableMap.<String, PropertyEntry<?>>builder().put(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_NAME,+ // Intentionally non-hidden: the account name already appears in abfss:// URIs.stringOptionalPropertyEntry(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_NAME,"Azure storage account name",diff --git a/core/src/main/java/org/apache/gravitino/cloud/storage/COSPropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/cloud/storage/COSPropertiesMetadata.javaindex 06156b2550..9e042fb738 100644--- a/core/src/main/java/org/apache/gravitino/cloud/storage/COSPropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/cloud/storage/COSPropertiesMetadata.java@@ -39,7 +39,7 @@ public class COSPropertiesMetadata {"COS access key ID (Tencent Cloud SecretId)",false /* immutable */,null /* defaultValue */,- false /* hidden */))+ true /* hidden */)).put(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET,stringOptionalPropertyEntry(diff --git a/core/src/main/java/org/apache/gravitino/cloud/storage/OSSPropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/cloud/storage/OSSPropertiesMetadata.javaindex 09585f3b92..719f5443ff 100644--- a/core/src/main/java/org/apache/gravitino/cloud/storage/OSSPropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/cloud/storage/OSSPropertiesMetadata.java@@ -37,7 +37,7 @@ public class OSSPropertiesMetadata {"OSS access key ID",false /* immutable */,null /* defaultValue */,- false /* hidden */))+ true /* hidden */)).put(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET,stringOptionalPropertyEntry(diff --git a/core/src/main/java/org/apache/gravitino/cloud/storage/S3PropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/cloud/storage/S3PropertiesMetadata.javaindex f6771fe7ec..7f20841558 100644--- a/core/src/main/java/org/apache/gravitino/cloud/storage/S3PropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/cloud/storage/S3PropertiesMetadata.java@@ -38,7 +38,7 @@ public class S3PropertiesMetadata {"S3 access key ID",false /* immutable */,null /* defaultValue */,- false /* hidden */))+ true /* hidden */)).put(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,stringOptionalPropertyEntry(diff --git a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.javaindex 5b0b664045..801fd3bf45 100644--- a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java+++ b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java@@ -535,6 +535,9 @@ public abstract class BaseCatalog<T extends BaseCatalog>props = Maps.newHashMap(secretManager.toPlaintextProperties(props));}if (StringUtils.isNotBlank(props.get(CredentialConstants.CREDENTIAL_PROVIDERS))) {+ // Explicit credential-providers wins: do not auto-append detected static providers (e.g.+ // s3-secret-key beside s3-token), which breaks path-based credential selection. Catalogs that+ // must keep jdbc/aws/dlf listed call ensureCredentialProviderListed in their overrides.return props;}List<String> credentialProviders = new ArrayList<>();@@ -559,6 +562,30 @@ public abstract class BaseCatalog<T extends BaseCatalog>addStorageCredentialProviders(properties, credentialProviders);}+ /**+ * Appends {@code credentialType} to {@link CredentialConstants#CREDENTIAL_PROVIDERS} when it is+ * not already listed. Used by subclasses that must keep catalog-specific providers (jdbc / aws /+ * dlf) available even when the property was set explicitly (so {@link+ * #addCatalogSpecificCredentialProviders} was skipped).+ *+ * @param props mutable catalog properties+ * @param credentialType provider type name to ensure+ */+ protected static void ensureCredentialProviderListed(+ Map<String, String> props, String credentialType) {+ String providers = props.get(CredentialConstants.CREDENTIAL_PROVIDERS);+ if (StringUtils.isBlank(providers)) {+ props.put(CredentialConstants.CREDENTIAL_PROVIDERS, credentialType);+ return;+ }+ for (String part : providers.split(",")) {+ if (credentialType.equals(part.trim())) {+ return;+ }+ }+ props.put(CredentialConstants.CREDENTIAL_PROVIDERS, providers + "," + credentialType);+ }+/*** Returns whether hidden credentials should be backfilled into catalog properties for backward* compatibility with connectors that do not support credential vending. Controlled by@@ -579,18 +606,44 @@ public abstract class BaseCatalog<T extends BaseCatalog>String s3SecretAccessKey = properties.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY);if (StringUtils.isNotBlank(s3AccessKeyId) && StringUtils.isNotBlank(s3SecretAccessKey)) {credentialProviders.add(S3SecretKeyCredential.S3_SECRET_KEY_CREDENTIAL_TYPE);+ } else if (StringUtils.isNotBlank(s3AccessKeyId) || StringUtils.isNotBlank(s3SecretAccessKey)) {+ LOG.warn(+ "Incomplete S3 static credential pair: both {} and {} are required to recover via"+ + " getCredentials; found accessKeyIdBlank={}, secretAccessKeyBlank={}",+ S3Properties.GRAVITINO_S3_ACCESS_KEY_ID,+ S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY,+ StringUtils.isBlank(s3AccessKeyId),+ StringUtils.isBlank(s3SecretAccessKey));}String ossAccessKeyId = properties.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID);String ossSecretAccessKey = properties.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET);if (StringUtils.isNotBlank(ossAccessKeyId) && StringUtils.isNotBlank(ossSecretAccessKey)) {credentialProviders.add(OSSSecretKeyCredential.OSS_SECRET_KEY_CREDENTIAL_TYPE);+ } else if (StringUtils.isNotBlank(ossAccessKeyId)+ || StringUtils.isNotBlank(ossSecretAccessKey)) {+ LOG.warn(+ "Incomplete OSS static credential pair: both {} and {} are required to recover via"+ + " getCredentials; found accessKeyIdBlank={}, secretAccessKeyBlank={}",+ OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID,+ OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET,+ StringUtils.isBlank(ossAccessKeyId),+ StringUtils.isBlank(ossSecretAccessKey));}String azureAccountName = properties.get(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_NAME);String azureAccountKey = properties.get(AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY);if (StringUtils.isNotBlank(azureAccountName) && StringUtils.isNotBlank(azureAccountKey)) {credentialProviders.add(AzureAccountKeyCredential.AZURE_ACCOUNT_KEY_CREDENTIAL_TYPE);+ } else if (StringUtils.isNotBlank(azureAccountName)+ || StringUtils.isNotBlank(azureAccountKey)) {+ LOG.warn(+ "Incomplete Azure static credential pair: both {} and {} are required to recover via"+ + " getCredentials; found accountNameBlank={}, accountKeyBlank={}",+ AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_NAME,+ AzureProperties.GRAVITINO_AZURE_STORAGE_ACCOUNT_KEY,+ StringUtils.isBlank(azureAccountName),+ StringUtils.isBlank(azureAccountKey));}String gcsServiceAccountFile = properties.get(GCSProperties.GRAVITINO_GCS_SERVICE_ACCOUNT_FILE);@@ -602,6 +655,15 @@ public abstract class BaseCatalog<T extends BaseCatalog>String cosSecretAccessKey = properties.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET);if (StringUtils.isNotBlank(cosAccessKeyId) && StringUtils.isNotBlank(cosSecretAccessKey)) {credentialProviders.add(COSSecretKeyCredential.COS_SECRET_KEY_CREDENTIAL_TYPE);+ } else if (StringUtils.isNotBlank(cosAccessKeyId)+ || StringUtils.isNotBlank(cosSecretAccessKey)) {+ LOG.warn(+ "Incomplete COS static credential pair: both {} and {} are required to recover via"+ + " getCredentials; found accessKeyIdBlank={}, secretAccessKeyBlank={}",+ COSProperties.GRAVITINO_COS_ACCESS_KEY_ID,+ COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET,+ StringUtils.isBlank(cosAccessKeyId),+ StringUtils.isBlank(cosSecretAccessKey));}}diff --git a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.javaindex 9788966b95..d3e1c11c81 100644--- a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java+++ b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java@@ -45,10 +45,10 @@ import org.apache.gravitino.secret.SecretPropertyUtils;* in-use}, {@code numFiles}).* </ul>*- * <p>Recovery via {@code getSecrets} covers secret-URN values and sensitive-named keys only. A- * property that is merely declared {@code hidden} (and whose name does not look sensitive) remains- * {@code ******} after merging {@code properties()} with {@code getSecrets()}; that API does not- * return it. See {@code org.apache.gravitino.secret.SupportsSecrets}.+ * <p>Recovery via {@code getSecrets} covers secret-URN values, declared {@code hidden} keys (except+ * credential-vending keys), and sensitive-named undeclared keys. Credential property keys are+ * recovered via {@code getCredentials()} instead. See {@code+ * org.apache.gravitino.secret.SupportsSecrets}.** <p><b>Write (create / alter)</b>: reject any value equal to {@link #MASKED_VALUE} so the* placeholder is never persisted. Reserved / immutable rejection remains in {@codediff --git a/core/src/main/java/org/apache/gravitino/secret/FallbackPropertiesMetadata.java b/core/src/main/java/org/apache/gravitino/secret/FallbackPropertiesMetadata.javaindex e7c334d269..1ba4872e58 100644--- a/core/src/main/java/org/apache/gravitino/secret/FallbackPropertiesMetadata.java+++ b/core/src/main/java/org/apache/gravitino/secret/FallbackPropertiesMetadata.java@@ -29,14 +29,18 @@ import org.apache.gravitino.connector.PropertyEntry;** <p>Registers shared base + credential-vending + cloud-storage entries ({@link* CloudPropertiesMetadata#STORAGE_PROPERTY_ENTRIES}) so officially non-hidden keys (for example- * {@code credential-providers}, {@code s3-access-key-id}) are not fuzzy-recovered into {@code- * getSecrets}. Undeclared sensitive-named keys still use fuzzy recovery; declared hidden secrets- * (for example {@code s3-secret-access-key}) remain recoverable.+ * {@code credential-providers}, {@code s3-token-expire-in-secs}) are not fuzzy-recovered into+ * {@code getSecrets}. Undeclared sensitive-named keys still use fuzzy recovery. Declared hidden+ * cloud credential keys (for example {@code s3-access-key-id}, {@code s3-secret-access-key}) are+ * recovered via {@code getSecrets} when the caller holds {@code USE_SECRETS} and {@code+ * INCLUDE_CREDENTIAL_SECRETS} (or is metalake owner); callers with only {@code USE_SECRETS} get+ * those cloud keys via {@code getCredentials} instead.** <p>Does not include the AWS access-key pair. That pair is a Glue catalog property merged only via* {@link org.apache.gravitino.connector.BaseCatalogPropertiesMetadata}, matching fileset and schema* metadata which also omit it. A catalog path that hits this fallback therefore treats {@code- * aws-access-key-id} as undeclared (fuzzy mask / recover), the same as a fileset or schema.+ * aws-access-key-id} as undeclared for masking; sensitive-named undeclared keys still fuzzy-recover+ * into {@code getSecrets}.*/final class FallbackPropertiesMetadata extends BasePropertiesMetadata {@@ -45,8 +49,6 @@ final class FallbackPropertiesMetadata extends BasePropertiesMetadata {private static final Map<String, PropertyEntry<?>> CLOUD_PROPERTY_ENTRIES =CloudPropertiesMetadata.STORAGE_PROPERTY_ENTRIES;- private FallbackPropertiesMetadata() {}-@Overrideprotected Map<String, PropertyEntry<?>> specificPropertyEntries() {return CLOUD_PROPERTY_ENTRIES;diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.javaindex b1bece5bce..5b4f6341e0 100644--- a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java+++ b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java@@ -31,6 +31,7 @@ import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.connector.PropertiesMetadata;import org.apache.gravitino.connector.PropertyEntry;+import org.apache.gravitino.storage.CloudStorageCredentialPropertyKeys;/*** Helpers for secret-related entity property handling and request validation.@@ -81,16 +82,20 @@ public final class SecretPropertyUtils {}/**- * Returns whether a sensitive-named inline property should be recovered via {@code getSecrets}.+ * Returns whether an inline (non-URN) property should be recovered via {@code getSecrets}.** <p>Secret-manager URNs are always recovered separately. For inline plaintext:** <ul>* <li>{@code metadata == null}: do <strong>not</strong> recover (URN-only). Used when the* catalog does not expose properties metadata for the entity type.- * <li>otherwise: recover only undeclared keys or declared {@code hidden} keys. Declared- * non-hidden configuration (for example {@code credential-providers}, {@code- * s3-access-key-id}) stays in {@code properties()} and is excluded here.+ * <li>declared {@code hidden}: always recover, without the sensitive-keyword gate — so+ * shortening {@link Configs#SENSITIVE_KEY_KEYWORDS} cannot leave a masked property without+ * a recovery path.+ * <li>undeclared: recover only when the key name matches {@link #isSensitivePropertyKey}+ * (historical fuzzy recovery).+ * <li>declared non-hidden: never recover here (for example {@code credential-providers} stays+ * in {@code properties()}).* </ul>** <p>Callers that need historical fuzzy recovery without real metadata should pass an empty@@ -103,13 +108,13 @@ public final class SecretPropertyUtils {*/public static boolean shouldRecoverSensitiveNamedSecret(String key, @Nullable PropertiesMetadata metadata) {- if (!isSensitivePropertyKey(key)) {- return false;- }if (metadata == null) {return false;}- return !metadata.containsProperty(key) || metadata.isHiddenProperty(key);+ if (metadata.containsProperty(key)) {+ return metadata.isHiddenProperty(key);+ }+ return isSensitivePropertyKey(key);}/**@@ -148,21 +153,15 @@ public final class SecretPropertyUtils {* <ol>* <li>Include every entry where {@link #isSecretProperty} is true, resolving the secret URN via* {@link SecretManager#readSecret}.- * <li>Include every entry whose key matches {@link #isSensitivePropertyKey} and whose value is- * not a secret URN, when {@link #shouldRecoverSensitiveNamedSecret} is true (undeclared or- * declared hidden). Declared non-hidden keys are excluded even when the name looks- * sensitive. When {@code metadata} is {@code null}, sensitive-named plaintext is not- * recovered (URN-only).+ * <li>Include every inline entry when {@link #shouldRecoverSensitiveNamedSecret} is true:+ * declared {@code hidden} (no keyword gate), or undeclared with a sensitive-looking name.+ * Declared non-hidden keys are excluded even when the name looks sensitive. When {@code+ * metadata} is {@code null}, inline plaintext is not recovered (URN-only).* </ol>*- * <p>Declared {@code hidden} properties are <strong>not</strong> included merely because they are- * hidden. A hidden key is recovered only when it is a secret URN or its name matches {@link- * #isSensitivePropertyKey} (for example {@code jdbc-password}). A hidden key whose name does not- * look sensitive (for example a path-like {@code auth-file}) stays masked as {@code ******} on- * list/get and is absent from this map.- *- * <p>Normal non-sensitive properties are not included. Clients merge this map over masked {@code- * properties()} so undeclared credential keys remain usable without leaking on list/get.+ * <p>Normal non-sensitive, non-hidden properties are not included. Clients merge this map over+ * masked {@code properties()} so hidden and undeclared credential keys remain usable without+ * leaking on list/get.** @param secretManager secret manager used to resolve URNs* @param rawProperties raw entity properties (may be null)@@ -365,4 +364,17 @@ public final class SecretPropertyUtils {entry.getValue() != null, "secretReferences[%s] must not be null", key);}}++ /**+ * Omits cloud access-key pair properties from a plaintext secrets map for {@code USE_SECRETS}+ * callers. Delegates to {@link+ * CloudStorageCredentialPropertyKeys#omitCloudAccessKeyPairProperties}.+ *+ * @param secrets plaintext secrets+ * @return secrets without cloud AK/SK pairs+ */+ public static Map<String, String> omitCloudAccessKeyPairSecrets(+ @Nullable Map<String, String> secrets) {+ return CloudStorageCredentialPropertyKeys.omitCloudAccessKeyPairProperties(secrets);+ }}diff --git a/core/src/test/java/org/apache/gravitino/cloud/storage/TestCloudPropertiesMetadata.java b/core/src/test/java/org/apache/gravitino/cloud/storage/TestCloudPropertiesMetadata.javaindex 87234c9793..e484ed3947 100644--- a/core/src/test/java/org/apache/gravitino/cloud/storage/TestCloudPropertiesMetadata.java+++ b/core/src/test/java/org/apache/gravitino/cloud/storage/TestCloudPropertiesMetadata.java@@ -43,7 +43,7 @@ public class TestCloudPropertiesMetadata {assertTrue(metadata.containsKey(S3Properties.GRAVITINO_S3_REGION));assertTrue(metadata.containsKey(S3Properties.GRAVITINO_S3_ROLE_ARN));assertFalse(metadata.get(S3Properties.GRAVITINO_S3_ENDPOINT).isHidden());- assertFalse(metadata.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID).isHidden());+ assertTrue(metadata.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID).isHidden());assertTrue(metadata.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY).isHidden());}@@ -53,6 +53,8 @@ public class TestCloudPropertiesMetadata {assertTrue(metadata.containsKey(OSSProperties.GRAVITINO_OSS_ENDPOINT));assertTrue(metadata.containsKey(OSSProperties.GRAVITINO_OSS_ROLE_ARN));assertFalse(metadata.get(OSSProperties.GRAVITINO_OSS_REGION).isHidden());+ assertTrue(metadata.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_ID).isHidden());+ assertTrue(metadata.get(OSSProperties.GRAVITINO_OSS_ACCESS_KEY_SECRET).isHidden());}@Test@@ -72,7 +74,7 @@ public class TestCloudPropertiesMetadata {assertTrue(metadata.containsKey(COSProperties.GRAVITINO_COS_ROLE_ARN));assertTrue(metadata.containsKey(COSProperties.GRAVITINO_COS_EXTERNAL_ID));assertTrue(metadata.containsKey(COSProperties.GRAVITINO_COS_APP_ID));- assertFalse(metadata.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID).isHidden());+ assertTrue(metadata.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_ID).isHidden());assertTrue(metadata.get(COSProperties.GRAVITINO_COS_ACCESS_KEY_SECRET).isHidden());}@@ -114,7 +116,7 @@ public class TestCloudPropertiesMetadata {var metadata = AWSPropertiesMetadata.PROPERTY_ENTRIES;assertTrue(metadata.containsKey(AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID));assertTrue(metadata.containsKey(AWSProperties.GRAVITINO_AWS_SECRET_ACCESS_KEY));- assertFalse(metadata.get(AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID).isHidden());+ assertTrue(metadata.get(AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID).isHidden());assertFalse(metadata.get(AWSProperties.GRAVITINO_AWS_ACCESS_KEY_ID).isRequired());assertTrue(metadata.get(AWSProperties.GRAVITINO_AWS_SECRET_ACCESS_KEY).isHidden());assertFalse(metadata.get(AWSProperties.GRAVITINO_AWS_SECRET_ACCESS_KEY).isRequired());diff --git a/core/src/test/java/org/apache/gravitino/connector/TestBaseCatalogPropertiesMetadata.java b/core/src/test/java/org/apache/gravitino/connector/TestBaseCatalogPropertiesMetadata.javaindex 4baa7a51f6..0bddf8a099 100644--- a/core/src/test/java/org/apache/gravitino/connector/TestBaseCatalogPropertiesMetadata.java+++ b/core/src/test/java/org/apache/gravitino/connector/TestBaseCatalogPropertiesMetadata.java@@ -51,14 +51,14 @@ public class TestBaseCatalogPropertiesMetadata {void testSharedCloudCredentialKeysAreDeclaredForAllCatalogs() {assertTrue(metadata.containsProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertTrue(metadata.containsProperty(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));- assertFalse(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));}@Testvoid testConnectorCredentialKeysAreDeclaredForAllCatalogs() {assertTrue(metadata.containsProperty("aws-access-key-id"));- assertFalse(metadata.isHiddenProperty("aws-access-key-id"));+ assertTrue(metadata.isHiddenProperty("aws-access-key-id"));assertTrue(metadata.isHiddenProperty("aws-secret-access-key"));assertFalse(metadata.containsProperty("jdbc-user"));assertFalse(metadata.containsProperty("jdbc-password"));@@ -77,7 +77,7 @@ public class TestBaseCatalogPropertiesMetadata {return ImmutableMap.of("aws-access-key-id",PropertyEntry.stringOptionalPropertyEntry(- "aws-access-key-id", "AWS access key ID", false, null, false),+ "aws-access-key-id", "AWS access key ID", false, null, true),"aws-secret-access-key",PropertyEntry.stringOptionalPropertyEntry("aws-secret-access-key", "AWS secret access key", false, null, true));@@ -95,8 +95,9 @@ public class TestBaseCatalogPropertiesMetadata {Map<String, String> masked =HiddenPropertyMaskUtils.maskHiddenProperties(properties, glueLikeMetadata);- assertEquals("AKIAEXAMPLE", masked.get("aws-access-key-id"));- assertEquals("AKIAEXAMPLE", masked.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, masked.get("aws-access-key-id"));+ assertEquals(+ HiddenPropertyMaskUtils.MASKED_VALUE, masked.get(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE,masked.get(S3Properties.GRAVITINO_S3_SECRET_ACCESS_KEY));@@ -115,12 +116,12 @@ public class TestBaseCatalogPropertiesMetadata {"Catalog-owned S3 access key ID",false,null,- true));+ false));}};assertTrue(catalogMetadata.containsProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));- assertTrue(catalogMetadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));- assertFalse(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertFalse(catalogMetadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));+ assertTrue(metadata.isHiddenProperty(S3Properties.GRAVITINO_S3_ACCESS_KEY_ID));}}diff --git a/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java b/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.javaindex 379e48dcbd..8a36cdd273 100644--- a/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java+++ b/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java@@ -43,6 +43,74 @@ import org.junit.jupiter.api.Test;*/public class TestBaseCatalogCredentialSecrets {+ @Test+ void testS3SecretKeyAutoDetectedWithoutExplicitProviders() {+ Map<String, String> entityProps =+ Map.of(+ S3SecretKeyCredential.GRAVITINO_S3_STATIC_ACCESS_KEY_ID,+ "AKIATEST",+ S3SecretKeyCredential.GRAVITINO_S3_STATIC_SECRET_ACCESS_KEY,+ "secret-sk");++ CatalogEntity entity =+ CatalogEntity.builder()+ .withId(2L)+ .withName("s3-static-catalog")+ .withNamespace(Namespace.of("metalake"))+ .withType(Catalog.Type.FILESET)+ .withProvider("test")+ .withProperties(entityProps)+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();++ TestCatalog catalog = new TestCatalog().withCatalogEntity(entity).withCatalogConf(entityProps);++ Map<String, String> withProviders = catalog.propertiesWithCredentialProviders();+ Assertions.assertTrue(+ withProviders+ .get(CredentialConstants.CREDENTIAL_PROVIDERS)+ .contains(S3SecretKeyCredential.S3_SECRET_KEY_CREDENTIAL_TYPE));+ Assertions.assertEquals(+ "AKIATEST", withProviders.get(S3SecretKeyCredential.GRAVITINO_S3_STATIC_ACCESS_KEY_ID));+ Assertions.assertEquals(+ "secret-sk",+ withProviders.get(S3SecretKeyCredential.GRAVITINO_S3_STATIC_SECRET_ACCESS_KEY));+ }++ @Test+ void testExplicitProvidersAreNotOverriddenByStaticDetection() {+ Map<String, String> entityProps =+ Map.of(+ CredentialConstants.CREDENTIAL_PROVIDERS,+ "s3-token",+ S3SecretKeyCredential.GRAVITINO_S3_STATIC_ACCESS_KEY_ID,+ "AKIATEST",+ S3SecretKeyCredential.GRAVITINO_S3_STATIC_SECRET_ACCESS_KEY,+ "secret-sk");++ CatalogEntity entity =+ CatalogEntity.builder()+ .withId(3L)+ .withName("s3-token-and-static")+ .withNamespace(Namespace.of("metalake"))+ .withType(Catalog.Type.FILESET)+ .withProvider("test")+ .withProperties(entityProps)+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();++ TestCatalog catalog = new TestCatalog().withCatalogEntity(entity).withCatalogConf(entityProps);++ Map<String, String> withProviders = catalog.propertiesWithCredentialProviders();+ String providers = withProviders.get(CredentialConstants.CREDENTIAL_PROVIDERS);+ Assertions.assertEquals("s3-token", providers);+ Assertions.assertFalse(+ providers.contains(S3SecretKeyCredential.S3_SECRET_KEY_CREDENTIAL_TYPE),+ "must not append s3-secret-key beside s3-token (path-based vending rejects mixed providers)");+ }+@Testvoid testPropertiesWithCredentialProvidersResolvesEntityUrn() throws Exception {try (SecretManager secretManager = memorySecretManager()) {diff --git a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyOperationDispatcher.javaindex 7a6f10325f..ca9b36197b 100644--- a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyOperationDispatcher.java@@ -64,7 +64,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchprivate static final String SCHEMA = "secret_schema";private static final Map<String, String> SECRET_PROPS =- ImmutableMap.of("k1", "v1", "jdbc-password", "s3cr3t", "visible", "ok");+ ImmutableMap.of("k1", "v1", "custom-token", "s3cr3t", "visible", "ok");private static SecretPropertyOperationDispatcher secretDispatcher;private static SchemaOperationDispatcher schemaOperationDispatcher;@@ -122,7 +122,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchMap<String, String> secrets =secretDispatcher.getSecrets(NameIdentifier.of(metalake), Entity.EntityType.METALAKE);- Assertions.assertEquals("s3cr3t", secrets.get("jdbc-password"));+ Assertions.assertEquals("s3cr3t", secrets.get("custom-token"));Assertions.assertFalse(secrets.containsKey("visible"));}@@ -134,7 +134,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchtableIdent, columns, "comment", SECRET_PROPS, new Transform[0]);Map<String, String> secrets = secretDispatcher.getSecrets(tableIdent, Entity.EntityType.TABLE);- Assertions.assertEquals("s3cr3t", secrets.get("jdbc-password"));+ Assertions.assertEquals("s3cr3t", secrets.get("custom-token"));Assertions.assertFalse(secrets.containsKey("visible"));}@@ -144,7 +144,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchtopicOperationDispatcher.createTopic(topicIdent, "comment", null, SECRET_PROPS);Map<String, String> secrets = secretDispatcher.getSecrets(topicIdent, Entity.EntityType.TOPIC);- Assertions.assertEquals("s3cr3t", secrets.get("jdbc-password"));+ Assertions.assertEquals("s3cr3t", secrets.get("custom-token"));Assertions.assertFalse(secrets.containsKey("visible"));}@@ -159,7 +159,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchviewIdent, "comment", new Column[0], representations, null, null, SECRET_PROPS);Map<String, String> secrets = secretDispatcher.getSecrets(viewIdent, Entity.EntityType.VIEW);- Assertions.assertEquals("s3cr3t", secrets.get("jdbc-password"));+ Assertions.assertEquals("s3cr3t", secrets.get("custom-token"));Assertions.assertFalse(secrets.containsKey("visible"));}@@ -170,7 +170,7 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatchmodelOperationDispatcher.registerModel(modelIdent, "comment", SECRET_PROPS);Map<String, String> secrets = secretDispatcher.getSecrets(modelIdent, Entity.EntityType.MODEL);- Assertions.assertEquals("s3cr3t", secrets.get("jdbc-password"));+ Assertions.assertEquals("s3cr3t", secrets.get("custom-token"));Assertions.assertFalse(secrets.containsKey("visible"));}@@ -190,15 +190,17 @@ public class TestSecretPropertyOperationDispatcher extends TestOperationDispatch// Official non-hidden keys stay out of getSecrets.Assertions.assertFalse(SecretPropertyUtils.shouldRecoverSensitiveNamedSecret("credential-providers", metadata));- Assertions.assertFalse(+ // Declared hidden cloud credentials fuzzy-recover into getSecrets (USE_SECRETS / owner).+ Assertions.assertTrue(SecretPropertyUtils.shouldRecoverSensitiveNamedSecret("s3-access-key-id", metadata));- // Declared hidden secrets and undeclared sensitive names still fuzzy-recover.Assertions.assertTrue(SecretPropertyUtils.shouldRecoverSensitiveNamedSecret("s3-secret-access-key", metadata));+ // Undeclared sensitive names still fuzzy-recover.Assertions.assertTrue(SecretPropertyUtils.shouldRecoverSensitiveNamedSecret("custom-token", metadata));// AWS access-key pair is catalog-only (BaseCatalogPropertiesMetadata), not in this entity- // fallback — same exclusion as fileset/schema STORAGE_PROPERTY_ENTRIES.+ // fallback — same exclusion as fileset/schema STORAGE_PROPERTY_ENTRIES. Undeclared sensitive+ // names still fuzzy-recover.Assertions.assertFalse(metadata.containsProperty("aws-access-key-id"));Assertions.assertFalse(metadata.containsProperty("aws-secret-access-key"));Assertions.assertTrue(diff --git a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.javaindex f50e85ad4d..97c67d5bdf 100644--- a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java@@ -24,6 +24,7 @@ import java.util.List;import java.util.Map;import java.util.Properties;import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;import org.apache.gravitino.connector.PropertiesMetadata;import org.apache.gravitino.connector.PropertyEntry;import org.apache.gravitino.secret.memory.InMemorySecretsProvider;@@ -209,51 +210,47 @@ public class TestSecretPropertyUtils {}@Test- void testBuildSecretsExcludesDeclaredNonHiddenSensitiveKeys() {+ void testBuildSecretsRecoversDeclaredHiddenWithoutKeywordGate() {+ Config config = new Config(false) {};+ // Drop "access" / "password" / "secret" so keyword fuzzy recovery cannot rescue these keys.+ config.set(Configs.SENSITIVE_KEY_KEYWORDS, List.of("token"));+ SecretPropertyUtils.configureSensitiveKeyKeywords(config);try (SecretManager sm = memorySecretManager()) {PropertiesMetadata metadata =new PropertiesMetadata() {@Overridepublic Map<String, PropertyEntry<?>> propertyEntries() {return ImmutableMap.of(- "credential-providers",- PropertyEntry.stringOptionalPropertyEntry(- "credential-providers", "providers", false, null, false),- "azure-storage-account-name",- PropertyEntry.stringOptionalPropertyEntry(- "azure-storage-account-name", "account", false, null, false),"s3-access-key-id",PropertyEntry.stringOptionalPropertyEntry(- "s3-access-key-id", "ak", false, null, false),- "jdbc-password",- PropertyEntry.stringOptionalPropertyEntry(- "jdbc-password", "password", false, null, true),- "s3-secret-access-key",+ "s3-access-key-id", "ak", false, null, true),+ "auth-file",+ PropertyEntry.stringOptionalPropertyEntry("auth-file", "path", false, null, true),+ "credential-providers",PropertyEntry.stringOptionalPropertyEntry(- "s3-secret-access-key", "sk", false, null, true));+ "credential-providers", "providers", false, null, false));}};Map<String, String> entityProps =Map.of(- "credential-providers",- "s3-token",- "azure-storage-account-name",- "abs-account","s3-access-key-id","AKIA",- "jdbc-password",- "inline-secret",- "s3-secret-access-key",- "super-secret",+ "auth-file",+ "/path/to/key",+ "credential-providers",+ "s3-token","custom-token",- "tok");+ "tok",+ "undeclared-access-key",+ "should-not-recover");Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm, entityProps, metadata);- Assertions.assertFalse(secrets.containsKey("credential-providers"));- Assertions.assertFalse(secrets.containsKey("azure-storage-account-name"));- Assertions.assertFalse(secrets.containsKey("s3-access-key-id"));- Assertions.assertEquals("inline-secret", secrets.get("jdbc-password"));- Assertions.assertEquals("super-secret", secrets.get("s3-secret-access-key"));+ Assertions.assertEquals("AKIA", secrets.get("s3-access-key-id"));+ Assertions.assertEquals("/path/to/key", secrets.get("auth-file"));Assertions.assertEquals("tok", secrets.get("custom-token"));+ Assertions.assertFalse(secrets.containsKey("credential-providers"));+ Assertions.assertFalse(+ secrets.containsKey("undeclared-access-key"),+ "undeclared keys still require a sensitive keyword match");}}diff --git a/design-docs/gravitino-glue-catalog.md b/design-docs/gravitino-glue-catalog.mdindex 1dc1b19456..c64f449325 100644--- a/design-docs/gravitino-glue-catalog.md+++ b/design-docs/gravitino-glue-catalog.md@@ -127,8 +127,8 @@ Glue is a separate AWS service from S3. The Glue region and credentials may diff| Property | Required | Default | Description || ----------------------- | -------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `aws-region` | Yes | — | AWS region for the Glue Data Catalog |-| `aws-access-key-id` | No | Default credential chain | AWS access key for Glue API authentication. Visible in cleartext to catalog readers. |-| `aws-secret-access-key` | No | Default credential chain | AWS secret key for Glue API authentication. Hidden from catalog readers; returned as `******`. |+| `aws-access-key-id` | No | Default credential chain | AWS access key for Glue API authentication. Hidden from catalog readers; returned as `******`. Plaintext via `getSecrets` with `USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`. Also remapped to `s3-*` for storage credential vending. |+| `aws-secret-access-key` | No | Default credential chain | AWS secret key for Glue API authentication. Hidden from catalog readers; returned as `******`. Plaintext via `getSecrets` with `USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`. || `aws-glue-catalog-id` | Yes | — | Glue catalog ID. Required because an AWS account can have multiple Glue catalogs (e.g., default catalog and federated S3 Tables catalog). || `aws-glue-endpoint` | No | AWS default regional endpoint | Custom Glue endpoint URL (for VPC endpoints or LocalStack testing). || `default-table-format` | No | `iceberg` | Default format for tables created via Gravitino's `createTable()` API. Accepted values: `iceberg`, `hive`. |diff --git a/docs/apache-hive-catalog.md b/docs/apache-hive-catalog.mdindex 73b0952e7a..f2e6041793 100644--- a/docs/apache-hive-catalog.md+++ b/docs/apache-hive-catalog.md@@ -83,7 +83,7 @@ When using Gravitino authorization for Hive with Apache Ranger, see the [AuthoriRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as credential-vending keys are hidden from the default load catalog response. Retrieve secret-manager-backed properties (including keys that overlap with credential vending) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) remains available for typed credential delivery.+Sensitive catalog properties such as credential-vending keys are hidden from the default load catalog response. Recover credential fields via the [credential vending API](security/credential-vending.md) (`getCredentials`). Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/fileset-catalog-with-cos.md b/docs/fileset-catalog-with-cos.mdindex cff8e3e9cf..135d693092 100644--- a/docs/fileset-catalog-with-cos.md+++ b/docs/fileset-catalog-with-cos.md@@ -52,9 +52,13 @@ underscores while the catalog and the Java client use hyphens.| `cos-token-expire-in-secs` | `cos_token_expire_in_secs` | The COS STS token expire time in seconds. Must not exceed the role's max session duration. Only meaningful when `credential-providers` includes `cos-token`. Defaults to `3600`. | No |:::note-`default-filesystem-provider` and `filesystem-providers` are deprecated. The fileset catalog-automatically loads the filesystem providers found on the classpath, including the built-in-providers and the cloud providers carried by a bundle jar such as `gravitino-tencent-bundle`.+- `cos-access-key-id` and `cos-secret-access-key` are hidden from the default load/list catalog+ response (`******`). Recover them via the [credential vending API](./security/credential-vending.md)+ (`getCredentials` / `COSSecretKeyCredential`). Other non-credential secrets use+ `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.+- `default-filesystem-provider` and `filesystem-providers` are deprecated. The fileset catalog+ automatically loads the filesystem providers found on the classpath, including the built-in+ providers and the cloud providers carried by a bundle jar such as `gravitino-tencent-bundle`.::::::notediff --git a/docs/fileset-catalog-with-oss.md b/docs/fileset-catalog-with-oss.mdindex b6fa0a4766..c2fe45ef41 100644--- a/docs/fileset-catalog-with-oss.md+++ b/docs/fileset-catalog-with-oss.md@@ -46,6 +46,13 @@ underscores while the catalog and the Java client use hyphens.| `oss-secret-access-key` | `oss_secret_access_key` | Secret key of the Aliyun OSS service. | Yes || `credential-providers` | (n/a) | The credential provider types, separated by comma. Possible values are `oss-token`, `oss-secret-key`. Setting it enables credential vending, so clients no longer need the credentials above. See [credential vending](./security/credential-vending.md#oss) for the extra properties each provider takes. | No |+:::note+`oss-access-key-id` and `oss-secret-access-key` are hidden from the default load/list catalog+response (`******`). Recover them via the [credential vending API](./security/credential-vending.md)+(`getCredentials` / `OSSSecretKeyCredential`). Other non-credential secrets use+`getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.+:::+Schema and fileset properties are documented on the shared page: see[schema properties](./fileset-catalog.md#schema-properties) and[fileset properties](./fileset-catalog.md#fileset-properties).diff --git a/docs/fileset-catalog-with-s3.md b/docs/fileset-catalog-with-s3.mdindex 39ea40e600..b09fbdf2b2 100644--- a/docs/fileset-catalog-with-s3.md+++ b/docs/fileset-catalog-with-s3.md@@ -51,6 +51,10 @@ underscores while the catalog and the Java client use hyphens.| `credential-providers` | (n/a) | The credential provider types, separated by comma. Possible values are `s3-token`, `s3-secret-key`, `aws-irsa`. Setting it enables credential vending, so clients no longer need the credentials above. See [credential vending](./security/credential-vending.md#s3) for the extra properties each provider takes. | No |:::note+- `s3-access-key-id` and `s3-secret-access-key` are hidden from the default load/list catalog+ response (`******`). Recover them via the [credential vending API](./security/credential-vending.md)+ (`getCredentials` / `S3SecretKeyCredential`). Other non-credential secrets use+ `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.- The location must start with `s3a://`, not `s3://`. The `hadoop-aws` library does not support the`s3://` scheme.- For MinIO and other S3-compatible services, set `s3-endpoint` to that service. If it requiresdiff --git a/docs/fileset-catalog.md b/docs/fileset-catalog.mdindex 6d09890620..caf1fc8847 100644--- a/docs/fileset-catalog.md+++ b/docs/fileset-catalog.md@@ -50,10 +50,10 @@ the Fileset catalog has the following properties:Refer to [Credential vending](./security/credential-vending.md) for more details about credential vending.Sensitive catalog properties such as cloud access keys are hidden from the default load catalog-response. Retrieve secret-manager-backed properties (including keys stored as secret URNs) via-`getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The-[credential vending API](security/credential-vending.md) remains available for typed credential-delivery.+response. Recover credential fields via the [credential vending API](security/credential-vending.md)+(`getCredentials`). Other non-credential secrets (secret-manager URNs, declared `hidden`+properties, undeclared sensitive-named keys) use `getSecrets` /+`GET .../objects/{type}/{fullName}/secrets`.### HDFS Filesetdiff --git a/docs/jdbc-doris-catalog.md b/docs/jdbc-doris-catalog.mdindex e7403807f8..2417f79642 100644--- a/docs/jdbc-doris-catalog.md+++ b/docs/jdbc-doris-catalog.md@@ -99,7 +99,7 @@ Returning null for DATETIME type precision. Driver version: mysql-connector-javaRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/jdbc-hologres-catalog.md b/docs/jdbc-hologres-catalog.mdindex d41af01324..7b6ab04652 100644--- a/docs/jdbc-hologres-catalog.md+++ b/docs/jdbc-hologres-catalog.md@@ -62,7 +62,7 @@ Hologres uses the PostgreSQL JDBC Driver (version 42.3.2 or later recommended).Refer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/jdbc-mysql-catalog.md b/docs/jdbc-mysql-catalog.mdindex 0e8aa5dbe9..12156b4854 100644--- a/docs/jdbc-mysql-catalog.md+++ b/docs/jdbc-mysql-catalog.md@@ -98,7 +98,7 @@ Returning null for TIMESTAMP type precision. Driver version: mysql-connector-javRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/jdbc-oceanbase-catalog.md b/docs/jdbc-oceanbase-catalog.mdindex 61ebf2e0ec..0896fa6983 100644--- a/docs/jdbc-oceanbase-catalog.md+++ b/docs/jdbc-oceanbase-catalog.md@@ -99,7 +99,7 @@ Returning null for TIMESTAMP type precision. Driver version: mysql-connector-javRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/jdbc-postgresql-catalog.md b/docs/jdbc-postgresql-catalog.mdindex dcdf9428ec..8fd3cf0cf9 100644--- a/docs/jdbc-postgresql-catalog.md+++ b/docs/jdbc-postgresql-catalog.md@@ -63,7 +63,7 @@ In PostgreSQL, the database corresponds to the Gravitino catalog, and the schemaRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/jdbc-starrocks-catalog.md b/docs/jdbc-starrocks-catalog.mdindex 427715b087..d3c976c450 100644--- a/docs/jdbc-starrocks-catalog.md+++ b/docs/jdbc-starrocks-catalog.md@@ -83,7 +83,7 @@ Returning null for DATETIME type precision. Driver version: mysql-connector-javaRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including `jdbc-password` when stored as a secret URN) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover `jdbc-user` / `jdbc-password` via the [credential vending API](security/credential-vending.md) (`getCredentials` / `JdbcCredential`); `jdbc-user` also remains in `properties()` when not hidden. Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/lakehouse-iceberg-catalog.md b/docs/lakehouse-iceberg-catalog.mdindex 5ebe5bbcbb..9b57d22a74 100644--- a/docs/lakehouse-iceberg-catalog.md+++ b/docs/lakehouse-iceberg-catalog.md@@ -258,7 +258,7 @@ Gravitino provides the build-in `org.apache.gravitino.iceberg.common.cache.LocalRefer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.:::note-Sensitive catalog properties such as `jdbc-password` and cloud credential keys are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Retrieve secret-manager-backed properties (including keys that overlap with credential vending) via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. The [credential vending API](security/credential-vending.md) remains available for typed credential delivery.+Sensitive catalog properties such as `jdbc-password` and cloud credential keys are hidden from the default load catalog response (`jdbc-user` is returned in plaintext). Recover JDBC and cloud credential fields via the [credential vending API](security/credential-vending.md) (`getCredentials`). Other non-credential secrets (secret-manager URNs, declared `hidden` properties, undeclared sensitive-named keys) use `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`.:::## Schemadiff --git a/docs/open-api/roles.yaml b/docs/open-api/roles.yamlindex d8f4b88146..8495eec254 100644--- a/docs/open-api/roles.yaml+++ b/docs/open-api/roles.yaml@@ -215,7 +215,8 @@ components:- REGISTER_MODEL- LINK_MODEL_VERSION- USE_MODEL- - USE_SECRET+ - USE_SECRETS+ - INCLUDE_CREDENTIAL_SECRETS- REGISTER_FUNCTION- EXECUTE_FUNCTION- MODIFY_FUNCTIONdiff --git a/docs/security/access-control.md b/docs/security/access-control.mdindex 99f23ac2df..24e05dd454 100755--- a/docs/security/access-control.md+++ b/docs/security/access-control.md@@ -202,7 +202,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_SECRET` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model, ModelVersion | Retrieve plaintext secrets and vend credentials for objects in scope |+| `USE_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model, ModelVersion | Call `getSecrets` (cloud access-key pairs omitted unless also granted `INCLUDE_CREDENTIAL_SECRETS`) |+| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog, Schema, Table, View, Topic, Fileset, Model, ModelVersion | With `USE_SECRETS`, include cloud access-key pairs in the `getSecrets` result || `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 |@@ -284,9 +285,11 @@ ownership, the same as altering it, because the caller chooses what the server cTable statistics follow the table itself: reading them takes `SELECT_TABLE` or `MODIFY_TABLE`,writing them takes `MODIFY_TABLE`. Model versions follow the model: `USE_MODEL` to read, owner to-alter or delete. Fetching plaintext secrets (`getSecrets`) or vend credentials (`getCredentials`)-requires owning the metalake or holding the `USE_SECRET` privilege. Callers who can load the object-but lack that access receive an empty result rather than a forbidden error.+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`. Vend credentials (`getCredentials`) requires no dedicated+privilege beyond being able to load the object. Callers who can load the object but lack+`USE_SECRETS` receive an empty `getSecrets` result rather than a forbidden error.The View row applies to metadata operations through both the native Gravitino REST API and theIceberg REST Catalog when authorization is enabled. Listing first requires access to the schema anddiff --git a/docs/security/credential-vending.md b/docs/security/credential-vending.mdindex 8e78eaced5..839f8ab953 100755--- a/docs/security/credential-vending.md+++ b/docs/security/credential-vending.md@@ -134,6 +134,31 @@ JDBC catalogs additionally infer `jdbc-user-password` from `jdbc-user` and `jdbcFour providers have no inference rule and must always be set explicitly: `s3-token`, `oss-token`, `adls-token`, and `aws-irsa`. In particular, setting `s3-role-arn` without `credential-providers` does not enable `s3-token`. The catalog falls back to `s3-secret-key` and vends the static access key instead, which is long-lived and not scoped to the table path. Set `credential-providers` explicitly whenever you want token-based vending.+### Static providers and `getCredentials` privilege risk++Static providers such as `s3-secret-key`, `oss-secret-key`, `cos-secret-key`, `azure-account-key`,+and `jdbc-user-password` return the configured long-lived plaintext keys from+`getCredentials` / `GET .../credentials`. That endpoint does **not** require a dedicated privilege+beyond being able to load the metadata object (unlike `getSecrets`, which requires `USE_SECRETS`,+with cloud access-key pairs gated by `INCLUDE_CREDENTIAL_SECRETS`).++**Risk:** any principal that can load a catalog (or fileset) configured with these static providers+can retrieve the same static AK/SK or JDBC password that Gravitino uses server-side.++**Temporary mitigation** until provider-level authorization is tightened:++- Prefer short-lived token providers (`s3-token`, `oss-token`, `adls-token`, `gcs-token`,+ `cos-token`, `aws-irsa`) over static `*-secret-key` / `azure-account-key` / `jdbc-user-password`+ whenever possible.+- When static providers are unavoidable, grant load / use privileges only to trusted principals+ (connectors and operators that must recover credentials).+- Do not treat `getCredentials` as a secrets-protected API for static keys; use `USE_SECRETS` /+ `INCLUDE_CREDENTIAL_SECRETS` and `getSecrets` when you need privilege-gated plaintext access.++A follow-up should track a lasting fix (for example privilege checks specific to static+credentials, or refusing to vend static secret-key credentials through `getCredentials` when+authorization is enabled).+## S3### `s3-token`@@ -480,7 +505,7 @@ Bundle jars on Maven Central:## Upgrading From a Release Earlier Than 1.3.0-Sensitive catalog properties such as `s3-access-key-id`, `s3-secret-access-key`, and `jdbc-password` are masked or excluded from the default `GET /api/metalakes/{metalake}/catalogs/{catalog}` response (`jdbc-user` and `azure-storage-account-name` are returned in plaintext). Retrieve secret-manager-backed properties and sensitive-named inline values via `getSecrets` / `GET .../objects/{type}/{fullName}/secrets`. That API does **not** recover properties that are only declared `hidden` in metadata when their names do not look sensitive; those stay as `******` after merging with `properties()`. The credentials API (`getCredentials` / `JdbcCredential`) remains available for typed credential delivery. Clients written against earlier releases that read those properties directly from the default load lose access to them.+Sensitive catalog properties such as `s3-access-key-id`, `s3-secret-access-key`, `jdbc-password`, `aws-access-key-id` / `aws-secret-access-key` (Glue), and `dlf-access-key-id` / `dlf-access-key-secret` (Paimon DLF) are masked or excluded from the default `GET /api/metalakes/{metalake}/catalogs/{catalog}` response (`jdbc-user` and `azure-storage-account-name` are returned in plaintext when not hidden). Plaintext secrets are available via `getSecrets` when the caller holds `USE_SECRETS` (or is metalake owner); cloud access-key pairs are included only with `INCLUDE_CREDENTIAL_SECRETS` (or metalake owner). Connectors typically use `USE_SECRETS` plus `getCredentials` / `GET .../credentials` (no dedicated privilege) to recover S3/OSS/COS/Azure/JDBC cloud keys (Glue AWS API keys and Paimon DLF pairs remain `USE_SECRETS` + `INCLUDE_CREDENTIAL_SECRETS` / `getSecrets` until dedicated credential types land). Vended-only fields such as `s3-session-token` are not catalog properties. Clients written against earlier releases that read those properties directly from the default load lose access to them.For a zero-downtime migration, set the following in `gravitino.conf`:diff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStore.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStore.javaindex 968e5673e0..5d212ab3c1 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStore.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/store/GravitinoCatalogStore.java@@ -220,6 +220,7 @@ public class GravitinoCatalogStore extends AbstractCatalogStore {}private static Map<String, String> propsWithSecrets(Catalog catalog) {- return PropertyUtils.propertiesWithSecrets(catalog.properties(), catalog::supportsSecrets);+ return PropertyUtils.propertiesWithSecretsAndCredentials(+ catalog.properties(), catalog::supportsSecrets, catalog::supportsCredentials);}}diff --git a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/PropertyUtils.java b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/PropertyUtils.javaindex 9c5f34d766..9116ddc2da 100644--- a/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/PropertyUtils.java+++ b/flink-connector/flink-common/src/main/java/org/apache/gravitino/flink/connector/utils/PropertyUtils.java@@ -23,16 +23,24 @@ import java.util.HashMap;import java.util.Map;import java.util.function.Supplier;import java.util.stream.Collectors;+import javax.annotation.Nullable;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.CredentialInfos;+import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.secret.SupportsSecrets;import org.apache.hadoop.conf.Configuration;import org.apache.paimon.options.Options;import org.apache.paimon.utils.HadoopUtils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/** Utility methods for Flink connector properties. */public class PropertyUtils {+ private static final Logger LOG = LoggerFactory.getLogger(PropertyUtils.class);+public static final String HIVE_PREFIX = "hive.";public static final String HADOOP_PREFIX = "hadoop.";public static final String FS_PREFIX = "fs.";@@ -40,35 +48,71 @@ public class PropertyUtils {/*** Merges masked entity {@code properties} with plaintext from {@link- * SupportsSecrets#getSecrets()}.+ * SupportsSecrets#getSecrets()} and {@link Credential#credentialInfo()} from {@link+ * SupportsCredentials#getCredentials()}.** <p>When secrets are unavailable — stubs that do not implement {@link SupportsSecrets}, or older- * Gravitino servers that return {@link NotFoundException} / {@link RESTException} for {@code- * /secrets} — returns a mutable copy of {@code properties} unchanged so list/get still works.+ * Gravitino servers that return {@link NotFoundException} — returns a mutable copy of {@code+ * properties}. Transport failures ({@link RESTException}) from {@code getSecrets} are not+ * swallowed: connectors must not start with masked {@code ******} values. Credential overlays+ * still tolerate {@link RESTException} for older servers that lack {@code /credentials}.** @param properties masked or raw properties (may be null)* @param supportsSecretsSupplier supplier of {@link SupportsSecrets}, typically {@code* entity::supportsSecrets}- * @return a new mutable map with secrets overlaid when available+ * @return a new mutable map with secrets and credential info overlaid when available*/public static Map<String, String> propertiesWithSecrets(Map<String, String> properties, Supplier<SupportsSecrets> supportsSecretsSupplier) {+ return propertiesWithSecretsAndCredentials(properties, supportsSecretsSupplier, null);+ }++ /**+ * Merges masked entity {@code properties} with {@code getSecrets()} and static ({@code+ * expireTimeInMs == 0}) {@code getCredentials().credentialInfo()}.+ *+ * @param properties masked or raw properties (may be null)+ * @param supportsSecretsSupplier supplier of {@link SupportsSecrets}+ * @param supportsCredentialsSupplier supplier of {@link SupportsCredentials}, or null to skip+ * @return a new mutable map with overlays when available+ */+ public static Map<String, String> propertiesWithSecretsAndCredentials(+ Map<String, String> properties,+ Supplier<SupportsSecrets> supportsSecretsSupplier,+ @Nullable Supplier<SupportsCredentials> supportsCredentialsSupplier) {Map<String, String> merged =new HashMap<>(properties == null ? Collections.emptyMap() : properties);- if (supportsSecretsSupplier == null) {- return merged;- }- try {- SupportsSecrets supportsSecrets = supportsSecretsSupplier.get();- if (supportsSecrets == null) {- return merged;+ if (supportsSecretsSupplier != null) {+ try {+ SupportsSecrets supportsSecrets = supportsSecretsSupplier.get();+ if (supportsSecrets != null) {+ Map<String, String> secrets = supportsSecrets.getSecrets();+ if (secrets != null && !secrets.isEmpty()) {+ merged.putAll(secrets);+ }+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Stubs may not implement SupportsSecrets; older servers lack /secrets.+ LOG.debug("Skipping getSecrets while resolving Flink catalog properties: {}", e.toString());}- Map<String, String> secrets = supportsSecrets.getSecrets();- if (secrets != null && !secrets.isEmpty()) {- merged.putAll(secrets);+ }+ if (supportsCredentialsSupplier != null) {+ try {+ SupportsCredentials supportsCredentials = supportsCredentialsSupplier.get();+ if (supportsCredentials != null) {+ Credential[] credentials = supportsCredentials.getCredentials();+ merged.putAll(CredentialInfos.nonExpiringCredentialInfo(credentials));+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Stubs may not implement SupportsCredentials; older servers lack /credentials.+ LOG.debug(+ "Skipping getCredentials while resolving Flink catalog properties: {}", e.toString());+ } catch (RESTException e) {+ LOG.warn(+ "Failed to resolve getCredentials while building Flink catalog properties; continuing"+ + " without static credential info: {}",+ e.toString());}- } catch (UnsupportedOperationException | NotFoundException | RESTException ignored) {- // Stubs may not implement SupportsSecrets; older servers lack /secrets.}return merged;}diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.javaindex fc83d072cd..046422b2ce 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java@@ -38,6 +38,9 @@ import org.apache.flink.table.catalog.exceptions.CatalogException;import org.apache.flink.table.factories.Factory;import org.apache.gravitino.Catalog;import org.apache.gravitino.Config;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.JdbcCredential;+import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.flink.connector.CatalogPropertiesConverter;import org.apache.gravitino.flink.connector.catalog.BaseCatalogFactory;import org.apache.gravitino.flink.connector.catalog.GravitinoCatalogManager;@@ -152,11 +155,15 @@ public class TestGravitinoCatalogStore {public void testMergeSecrets() {Catalog catalog = mock(Catalog.class);SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);when(gravitinoCatalogMockManager.getGravitinoCatalogInfo("sec")).thenReturn(catalog);when(catalog.provider()).thenReturn("test-provider");when(catalog.properties()).thenReturn(Map.of("visible", "v1"));when(catalog.supportsSecrets()).thenReturn(supportsSecrets);- when(supportsSecrets.getSecrets()).thenReturn(Map.of("jdbc-password", "secret"));+ when(supportsSecrets.getSecrets()).thenReturn(Map.of("custom-token", "secret"));+ when(catalog.supportsCredentials()).thenReturn(supportsCredentials);+ when(supportsCredentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("u", "jdbc-secret")});BaseCatalogFactory factory = mock(BaseCatalogFactory.class);CatalogPropertiesConverter converter = mock(CatalogPropertiesConverter.class);@@ -180,7 +187,8 @@ public class TestGravitinoCatalogStore {Optional<CatalogDescriptor> descriptor = store.getCatalog("sec");assertTrue(descriptor.isPresent());- assertEquals("secret", descriptor.get().getConfiguration().toMap().get("jdbc-password"));+ assertEquals("secret", descriptor.get().getConfiguration().toMap().get("custom-token"));+ assertEquals("jdbc-secret", descriptor.get().getConfiguration().toMap().get("jdbc-password"));assertEquals("v1", descriptor.get().getConfiguration().toMap().get("visible"));}@@ -188,11 +196,15 @@ public class TestGravitinoCatalogStore {public void testMergeSecretsNullProps() {Catalog catalog = mock(Catalog.class);SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);when(gravitinoCatalogMockManager.getGravitinoCatalogInfo("sec-null")).thenReturn(catalog);when(catalog.provider()).thenReturn("test-provider");when(catalog.properties()).thenReturn(null);when(catalog.supportsSecrets()).thenReturn(supportsSecrets);- when(supportsSecrets.getSecrets()).thenReturn(Map.of("jdbc-password", "secret"));+ when(supportsSecrets.getSecrets()).thenReturn(Map.of("custom-token", "secret"));+ when(catalog.supportsCredentials()).thenReturn(supportsCredentials);+ when(supportsCredentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("u", "jdbc-secret")});BaseCatalogFactory factory = mock(BaseCatalogFactory.class);CatalogPropertiesConverter converter = mock(CatalogPropertiesConverter.class);@@ -216,32 +228,37 @@ public class TestGravitinoCatalogStore {Optional<CatalogDescriptor> descriptor = store.getCatalog("sec-null");assertTrue(descriptor.isPresent());- assertEquals("secret", descriptor.get().getConfiguration().toMap().get("jdbc-password"));+ assertEquals("secret", descriptor.get().getConfiguration().toMap().get("custom-token"));+ assertEquals("jdbc-secret", descriptor.get().getConfiguration().toMap().get("jdbc-password"));}@Testpublic void testMergeMemorySecrets() {try (SecretManager sm = memorySecretManager()) {Map<String, String> entityProps = new HashMap<>();- entityProps.put("jdbc-user", "root");+ entityProps.put("custom-token", "placeholder");java.util.List<SecretMaterial> writes =sm.assembleSecretMaterials(- Map.of("jdbc-user", "root"),+ Map.of(),entityProps,"catalog",2L,- Map.of("jdbc-password", new SecretBinding("memory", "mem-pwd")),+ Map.of("custom-token", new SecretBinding("memory", "mem-tok")),Map.of());sm.writeSecrets(writes);Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm, entityProps);Catalog catalog = mock(Catalog.class);SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);when(gravitinoCatalogMockManager.getGravitinoCatalogInfo("mem")).thenReturn(catalog);when(catalog.provider()).thenReturn("test-provider");when(catalog.properties()).thenReturn(Map.of("jdbc-url", "jdbc:mysql://localhost/db"));when(catalog.supportsSecrets()).thenReturn(supportsSecrets);when(supportsSecrets.getSecrets()).thenReturn(secrets);+ when(catalog.supportsCredentials()).thenReturn(supportsCredentials);+ when(supportsCredentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("root", "mem-pwd")});BaseCatalogFactory factory = mock(BaseCatalogFactory.class);CatalogPropertiesConverter converter = mock(CatalogPropertiesConverter.class);@@ -266,6 +283,7 @@ public class TestGravitinoCatalogStore {Optional<CatalogDescriptor> descriptor = store.getCatalog("mem");assertTrue(descriptor.isPresent());assertEquals("mem-pwd", descriptor.get().getConfiguration().toMap().get("jdbc-password"));+ assertEquals("mem-tok", descriptor.get().getConfiguration().toMap().get("custom-token"));}}diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/TestPropertyUtils.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/TestPropertyUtils.javaindex 22af863a99..8dc85d0e1e 100644--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/TestPropertyUtils.java+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/utils/TestPropertyUtils.java@@ -19,6 +19,9 @@package org.apache.gravitino.flink.connector.utils;import java.util.Map;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.S3SecretKeyCredential;+import org.apache.gravitino.credential.S3TokenCredential;import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.secret.SupportsSecrets;@@ -49,14 +52,14 @@ public class TestPropertyUtils {}@Test- void testPropertiesWithSecretsSwallowsRestException() {+ void testPropertiesWithSecretsPropagatesRestException() {SupportsSecrets broken =() -> {throw new RESTException("connection failed");};- Map<String, String> merged =- PropertyUtils.propertiesWithSecrets(Map.of("k", "v"), () -> broken);- Assertions.assertEquals("v", merged.get("k"));+ Assertions.assertThrows(+ RESTException.class,+ () -> PropertyUtils.propertiesWithSecrets(Map.of("k", "v"), () -> broken));}@Test@@ -76,4 +79,22 @@ public class TestPropertyUtils {PropertyUtils.propertiesWithSecrets(null, () -> () -> Map.of("secret", "x"));Assertions.assertEquals("x", merged.get("secret"));}++ @Test+ void testPropertiesWithSecretsAndCredentialsSkipsExpiringCredentials() {+ Credential staticCred = new S3SecretKeyCredential("AKIATEST", "static-secret");+ Credential tokenCred =+ new S3TokenCredential("SESSION", "session-secret", "tok", 1_700_000_000_000L);+ Map<String, String> merged =+ PropertyUtils.propertiesWithSecretsAndCredentials(+ Map.of("s3-endpoint", "http://s3.example.com"),+ () -> () -> Map.of(),+ () -> () -> new Credential[] {tokenCred, staticCred});+ Assertions.assertEquals(+ "AKIATEST", merged.get(S3SecretKeyCredential.GRAVITINO_S3_STATIC_ACCESS_KEY_ID));+ Assertions.assertEquals(+ "static-secret", merged.get(S3SecretKeyCredential.GRAVITINO_S3_STATIC_SECRET_ACCESS_KEY));+ Assertions.assertFalse(merged.containsKey(S3TokenCredential.GRAVITINO_S3_TOKEN));+ Assertions.assertEquals("http://s3.example.com", merged.get("s3-endpoint"));+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.javaindex eb48c38ff5..8a4ccc8801 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/provider/DynamicIcebergConfigProvider.java@@ -23,7 +23,6 @@ import static org.apache.gravitino.connector.BaseCatalog.CATALOG_BYPASS_PREFIX;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import java.io.Closeable;-import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Optional;@@ -38,15 +37,20 @@ import org.apache.gravitino.client.DefaultOAuth2TokenProvider;import org.apache.gravitino.client.GravitinoClient;import org.apache.gravitino.client.GravitinoClient.ClientBuilder;import org.apache.gravitino.connector.BaseCatalog;-import org.apache.gravitino.credential.JdbcCredential;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.CredentialInfos;import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.exceptions.NoSuchCatalogException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.iceberg.common.IcebergConfig;import org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerContext;import org.apache.gravitino.secret.SupportsSecrets;import org.apache.gravitino.server.web.JettyServerConfig;import org.apache.gravitino.utils.MapUtils;import org.apache.gravitino.utils.NameIdentifierUtil;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** This provider proxy Gravitino lakehouse-iceberg catalogs.@@ -57,6 +61,8 @@ import org.apache.gravitino.utils.NameIdentifierUtil;*/public class DynamicIcebergConfigProvider implements IcebergConfigProvider {+ private static final Logger LOG = LoggerFactory.getLogger(DynamicIcebergConfigProvider.class);+private String gravitinoMetalake;private Optional<String> defaultDynamicCatalogName;private Map<String, String> properties;@@ -108,8 +114,9 @@ public class DynamicIcebergConfigProvider implements IcebergConfigProvider {"lakehouse-iceberg".equals(catalog.provider()),String.format("Catalog %s is not an Iceberg catalog", catalog.name()));- // Auxiliary: BaseCatalog + SecretManager plaintext. Standalone: properties + getSecrets,- // then JdbcCredential overlays so credentials win.+ // Auxiliary: BaseCatalog + SecretManager plaintext. Standalone: properties + getSecrets for+ // non-credential secrets, then static (expireTimeInMs == 0) getCredentials().credentialInfo()+ // for cloud/JDBC fields (expiring tokens are skipped; this config has no refresh path).if (catalog instanceof BaseCatalog) {BaseCatalog<?> baseCatalog = (BaseCatalog<?>) catalog;Map<String, String> props =@@ -130,19 +137,29 @@ public class DynamicIcebergConfigProvider implements IcebergConfigProvider {props.putAll(secrets);}}- } catch (UnsupportedOperationException ignored) {- // Catalog does not support secret property operations.+ } catch (UnsupportedOperationException | NotFoundException e) {+ LOG.debug(+ "Skipping getSecrets while resolving Iceberg catalog {}: {}",+ catalog.name(),+ e.toString());}- if (catalog instanceof SupportsCredentials) {- Arrays.stream(((SupportsCredentials) catalog).getCredentials())- .filter(c -> c instanceof JdbcCredential)- .map(c -> (JdbcCredential) c)- .findFirst()- .ifPresent(- jdbc -> {- props.put(IcebergConstants.GRAVITINO_JDBC_USER, jdbc.jdbcUser());- props.put(IcebergConstants.GRAVITINO_JDBC_PASSWORD, jdbc.jdbcPassword());- });+ try {+ SupportsCredentials supportsCredentials = catalog.supportsCredentials();+ if (supportsCredentials != null) {+ Credential[] credentials = supportsCredentials.getCredentials();+ props.putAll(CredentialInfos.nonExpiringCredentialInfo(credentials));+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ LOG.debug(+ "Skipping getCredentials while resolving Iceberg catalog {}: {}",+ catalog.name(),+ e.toString());+ } catch (RESTException e) {+ LOG.warn(+ "Failed to resolve getCredentials for Iceberg catalog {}; continuing without static"+ + " credential info: {}",+ catalog.name(),+ e.toString());}return props;}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.javaindex 18ddf24ca9..44089c0a55 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java@@ -611,8 +611,13 @@ public class TestDynamicIcebergConfigProvider {String metalakeName = "test_metalake";String catalogName = "jdbc_catalog";- Catalog mockCatalog = Mockito.mock(Catalog.class);- SupportsSecrets supportsSecrets = Mockito.mock(SupportsSecrets.class);+ Catalog mockCatalog =+ Mockito.mock(+ Catalog.class,+ Mockito.withSettings()+ .extraInterfaces(SupportsCredentials.class, SupportsSecrets.class));+ SupportsSecrets supportsSecrets = (SupportsSecrets) mockCatalog;+ SupportsCredentials supportsCredentials = (SupportsCredentials) mockCatalog;Mockito.when(mockCatalog.provider()).thenReturn("lakehouse-iceberg");Mockito.when(mockCatalog.properties()).thenReturn(@@ -624,8 +629,10 @@ public class TestDynamicIcebergConfigProvider {}});Mockito.when(mockCatalog.supportsSecrets()).thenReturn(supportsSecrets);- Mockito.when(supportsSecrets.getSecrets())- .thenReturn(Map.of(IcebergConstants.GRAVITINO_JDBC_PASSWORD, "secret-pwd"));+ Mockito.when(supportsSecrets.getSecrets()).thenReturn(Map.of("custom-token", "tok"));+ Mockito.when(mockCatalog.supportsCredentials()).thenReturn(supportsCredentials);+ Mockito.when(supportsCredentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("iceberg", "secret-pwd")});Map<String, String> properties = new HashMap<>();properties.put(IcebergConstants.GRAVITINO_URI, "http://localhost:8090");@@ -640,6 +647,10 @@ public class TestDynamicIcebergConfigProvider {Assertions.assertEquals("secret-pwd",config.get().getIcebergCatalogProperties().get(IcebergConstants.GRAVITINO_JDBC_PASSWORD));+ Assertions.assertEquals(+ "iceberg",+ config.get().getIcebergCatalogProperties().get(IcebergConstants.GRAVITINO_JDBC_USER));+ Assertions.assertEquals("tok", config.get().getIcebergCatalogProperties().get("custom-token"));}@Test@@ -665,13 +676,8 @@ public class TestDynamicIcebergConfigProvider {}});Mockito.when(mockCatalog.supportsSecrets()).thenReturn(supportsSecrets);- Mockito.when(supportsSecrets.getSecrets())- .thenReturn(- Map.of(- IcebergConstants.GRAVITINO_JDBC_USER,- "from-secret",- IcebergConstants.GRAVITINO_JDBC_PASSWORD,- "secret-pwd"));+ Mockito.when(supportsSecrets.getSecrets()).thenReturn(Map.of("shared", "from-secret"));+ Mockito.when(mockCatalog.supportsCredentials()).thenReturn(supportsCredentials);Mockito.when(supportsCredentials.getCredentials()).thenReturn(new Credential[] {new JdbcCredential("cred-user", "cred-pwd")});@@ -688,30 +694,34 @@ public class TestDynamicIcebergConfigProvider {Map<String, String> icebergProps = config.get().getIcebergCatalogProperties();Assertions.assertEquals("cred-user", icebergProps.get(IcebergConstants.GRAVITINO_JDBC_USER));Assertions.assertEquals("cred-pwd", icebergProps.get(IcebergConstants.GRAVITINO_JDBC_PASSWORD));+ Assertions.assertEquals("from-secret", icebergProps.get("shared"));}@Testpublic void testMergeMemorySecrets() {try (SecretManager sm = memorySecretManager()) {Map<String, String> entityProps = new HashMap<>();- entityProps.put(IcebergConstants.GRAVITINO_JDBC_USER, "root");+ entityProps.put("custom-token", "placeholder");List<SecretMaterial> writes =sm.assembleSecretMaterials(- Map.of(IcebergConstants.GRAVITINO_JDBC_USER, "root"),+ Map.of(),entityProps,"catalog",3L,- Map.of(- IcebergConstants.GRAVITINO_JDBC_PASSWORD,- new SecretBinding("memory", "mem-jdbc-pwd")),+ Map.of("custom-token", new SecretBinding("memory", "mem-custom-tok")),Map.of());sm.writeSecrets(writes);Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm, entityProps);String metalakeName = "test_metalake";String catalogName = "jdbc_catalog";- Catalog mockCatalog = Mockito.mock(Catalog.class);- SupportsSecrets supportsSecrets = Mockito.mock(SupportsSecrets.class);+ Catalog mockCatalog =+ Mockito.mock(+ Catalog.class,+ Mockito.withSettings()+ .extraInterfaces(SupportsCredentials.class, SupportsSecrets.class));+ SupportsSecrets supportsSecrets = (SupportsSecrets) mockCatalog;+ SupportsCredentials supportsCredentials = (SupportsCredentials) mockCatalog;Mockito.when(mockCatalog.provider()).thenReturn("lakehouse-iceberg");Mockito.when(mockCatalog.properties()).thenReturn(@@ -723,6 +733,9 @@ public class TestDynamicIcebergConfigProvider {});Mockito.when(mockCatalog.supportsSecrets()).thenReturn(supportsSecrets);Mockito.when(supportsSecrets.getSecrets()).thenReturn(secrets);+ Mockito.when(mockCatalog.supportsCredentials()).thenReturn(supportsCredentials);+ Mockito.when(supportsCredentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("root", "mem-jdbc-pwd")});Map<String, String> properties = new HashMap<>();properties.put(IcebergConstants.GRAVITINO_URI, "http://localhost:8090");@@ -737,6 +750,8 @@ public class TestDynamicIcebergConfigProvider {Assertions.assertEquals("mem-jdbc-pwd",config.get().getIcebergCatalogProperties().get(IcebergConstants.GRAVITINO_JDBC_PASSWORD));+ Assertions.assertEquals(+ "mem-custom-tok", config.get().getIcebergCatalogProperties().get("custom-token"));}}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.javaindex 8bb75fa0d0..a8f093e112 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@@ -277,14 +277,27 @@ public class AuthorizationExpressionConstants {""";/**- * Soft check for retrieving plaintext secrets or vend credentials. Only the metalake owner or a- * principal with {@code USE_SECRET} may receive non-empty results; others get an empty response- * rather than a forbidden error.+ * Soft check required to call {@code getSecrets}. Only the metalake owner or a principal with+ * {@code USE_SECRETS} may receive secrets; others get an empty response rather than a forbidden+ * error. Whether cloud access-key pairs are included depends on {@link+ * #FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION}.*/public static final String FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION ="""METALAKE::OWNER ||- ANY_USE_SECRET+ ANY_USE_SECRETS+ """;++ /**+ * Soft check that, together with {@link #FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION}, includes+ * cloud access-key pairs in the {@code getSecrets} result. Alone it does not authorize {@code+ * getSecrets}. Metalake owners and holders of {@code INCLUDE_CREDENTIAL_SECRETS} receive the+ * unfiltered map when they also pass the {@code USE_SECRETS} check.+ */+ public static final String FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION =+ """+ METALAKE::OWNER ||+ ANY_INCLUDE_CREDENTIAL_SECRETS""";public static final String FILTER_TOPICS_AUTHORIZATION_EXPRESSION =diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.javaindex 82c54c5574..6732b44fbb 100644--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConverter.java@@ -296,10 +296,17 @@ public class AuthorizationExpressionConverter {+ "!(ANY(DENY_USE_MODEL, METALAKE, CATALOG, SCHEMA, MODEL)))");expression =expression.replaceAll(- "ANY_USE_SECRET",- "((ANY(USE_SECRET, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"- + " MODEL_VERSION)) && !(ANY(DENY_USE_SECRET, METALAKE, CATALOG, SCHEMA, TABLE,"+ "ANY_USE_SECRETS",+ "((ANY(USE_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"+ + " MODEL_VERSION)) && !(ANY(DENY_USE_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE,"+ " VIEW, TOPIC, FILESET, MODEL, MODEL_VERSION)))");+ expression =+ expression.replaceAll(+ "ANY_INCLUDE_CREDENTIAL_SECRETS",+ "((ANY(INCLUDE_CREDENTIAL_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC,"+ + " FILESET, MODEL, MODEL_VERSION)) && !(ANY(DENY_INCLUDE_CREDENTIAL_SECRETS,"+ + " METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"+ + " MODEL_VERSION)))");expression =expression.replaceAll("ANY_LINK_MODEL_VERSION",diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.javaindex d176ffdbbc..c14fb8e421 100644--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestAuthorizationExpressionConverter.java@@ -131,15 +131,27 @@ public class TestAuthorizationExpressionConverter {}@Test- public void testReplaceAnyPrivilegeForAnyUseSecret() {- String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_USE_SECRET");+ public void testReplaceAnyPrivilegeForAnyUseSecretss() {+ String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_USE_SECRETS");Assertions.assertEquals(- "((ANY(USE_SECRET, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"- + " MODEL_VERSION)) && !(ANY(DENY_USE_SECRET, METALAKE, CATALOG, SCHEMA, TABLE,"+ "((ANY(USE_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"+ + " MODEL_VERSION)) && !(ANY(DENY_USE_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE,"+ " VIEW, TOPIC, FILESET, MODEL, MODEL_VERSION)))",replaced);}+ @Test+ public void testReplaceAnyPrivilegeForAnyIncludeCredentialSecretss() {+ String replaced =+ AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_INCLUDE_CREDENTIAL_SECRETS");+ Assertions.assertEquals(+ "((ANY(INCLUDE_CREDENTIAL_SECRETS, METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC,"+ + " FILESET, MODEL, MODEL_VERSION)) && !(ANY(DENY_INCLUDE_CREDENTIAL_SECRETS,"+ + " METALAKE, CATALOG, SCHEMA, TABLE, VIEW, TOPIC, FILESET, MODEL,"+ + " MODEL_VERSION)))",+ replaced);+ }+@Testpublic void testReplaceAnyPrivilegeForAnyViewTag() {String replaced = AuthorizationExpressionConverter.replaceAnyPrivilege("ANY_VIEW_TAG");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.javaindex 7bfc921f11..196e1619a0 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@@ -108,12 +108,6 @@ public class MetadataObjectCredentialOperations {NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);- if (!MetadataAuthzHelper.checkAccess(- identifier,- entityType,- AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)) {- return Utils.ok(new CredentialResponse(new CredentialDTO[0]));- }Map<String, String> filteredFilesetHeaders =Utils.filterFilesetCredentialHeaders(httpRequest);diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSecretOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSecretOperations.javaindex 08b0774ee3..58c778623c 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSecretOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSecretOperations.java@@ -42,6 +42,7 @@ import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.dto.responses.SecretsResponse;import org.apache.gravitino.metrics.MetricNames;import org.apache.gravitino.secret.SecretPropertyOperationDispatcher;+import org.apache.gravitino.secret.SecretPropertyUtils;import org.apache.gravitino.server.authorization.MetadataAuthzHelper;import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;import org.apache.gravitino.server.authorization.annotations.AuthorizationFullName;@@ -111,14 +112,25 @@ public class MetadataObjectSecretOperations {NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, object);Entity.EntityType entityType = MetadataObjectUtil.toEntityType(object);- if (!MetadataAuthzHelper.checkAccess(- identifier,- entityType,- AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)) {+ boolean canUseSecrets =+ MetadataAuthzHelper.checkAccess(+ identifier,+ entityType,+ AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION);+ if (!canUseSecrets) {return Utils.ok(new SecretsResponse(ImmutableMap.of()));}+ boolean canIncludeCredentialSecrets =+ MetadataAuthzHelper.checkAccess(+ identifier,+ entityType,+ AuthorizationExpressionConstants+ .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION);Map<String, String> secrets =secretPropertyOperationDispatcher.getSecrets(identifier, entityType);+ if (!canIncludeCredentialSecrets) {+ secrets = SecretPropertyUtils.omitCloudAccessKeyPairSecrets(secrets);+ }return Utils.ok(new SecretsResponse(secrets));});} catch (Exception e) {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.javaindex 1e83e42925..c1e814f0d3 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,11 +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.never;-import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.io.IOException;@@ -32,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 +36,12 @@ import org.apache.gravitino.credential.S3SecretKeyCredential;import org.apache.gravitino.dto.responses.CredentialResponse;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 {@@ -103,43 +94,6 @@ public class TestMetadataObjectCredentialOperations extends JerseyTest {MetadataObjects.parse("catalog.schema.fileset", MetadataObject.Type.FILESET));}- @Test- public void testGetCredentialsReturnsEmptyWithoutUseSecret() throws Exception {- MetadataObject metadataObject =- MetadataObjects.parse("catalog.schema.fileset", MetadataObject.Type.FILESET);- S3SecretKeyCredential credential = new S3SecretKeyCredential("access-id", "secret-key");- when(credentialOperationDispatcher.getCredentials(any(), any()))- .thenReturn(Arrays.asList(credential));-- MetadataObjectCredentialOperations operations =- new MetadataObjectCredentialOperations(credentialOperationDispatcher);- FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);-- try (MockedStatic<MetadataAuthzHelper> metadataAuthzHelper =- mockStatic(MetadataAuthzHelper.class)) {- metadataAuthzHelper- .when(- () ->- MetadataAuthzHelper.checkAccess(- any(),- any(Entity.EntityType.class),- eq(- AuthorizationExpressionConstants- .FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)))- .thenReturn(false);-- Response response =- operations.getCredentials(- metalake, metadataObject.type().name(), metadataObject.fullName());-- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- CredentialResponse credentialResponse = (CredentialResponse) response.getEntity();- Assertions.assertEquals(0, credentialResponse.getCode());- Assertions.assertEquals(0, credentialResponse.getCredentials().length);- verify(credentialOperationDispatcher, never()).getCredentials(any(), any());- }- }-private void testGetCredentialsForObject(MetadataObject metadataObject) {S3SecretKeyCredential credential = new S3SecretKeyCredential("access-id", "secret-key");diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSecretOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSecretOperations.javaindex 7e9f24738b..2efe6e0d3b 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSecretOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSecretOperations.java@@ -136,7 +136,7 @@ public class TestMetadataObjectSecretOperations extends JerseyTest {}@Test- public void testGetSecretsReturnsEmptyWithoutUseSecret() throws Exception {+ public void testGetSecretsReturnsEmptyWithoutUseSecretss() throws Exception {MetadataObject metadataObject =MetadataObjects.parse("catalog.schema.fileset", MetadataObject.Type.FILESET);when(secretPropertyOperationDispatcher.getSecrets(any(), any(Entity.EntityType.class)))@@ -158,6 +158,17 @@ public class TestMetadataObjectSecretOperations extends JerseyTest {AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION))).thenReturn(false);+ // INCLUDE alone must not authorize getSecrets.+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.checkAccess(+ any(),+ any(Entity.EntityType.class),+ eq(+ AuthorizationExpressionConstants+ .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION)))+ .thenReturn(true);Response response =operations.getSecrets(metalake, metadataObject.type().name(), metadataObject.fullName());@@ -171,6 +182,116 @@ public class TestMetadataObjectSecretOperations extends JerseyTest {}}+ @Test+ public void testGetSecretsFiltersCloudKeysWithUseSecretsOnly() throws Exception {+ MetadataObject metadataObject =+ MetadataObjects.parse("catalog.schema.fileset", MetadataObject.Type.FILESET);+ when(secretPropertyOperationDispatcher.getSecrets(any(), any(Entity.EntityType.class)))+ .thenReturn(+ Map.of(+ "s3-access-key-id",+ "AKIA",+ "s3-secret-access-key",+ "secret",+ "jdbc-password",+ "db-pass",+ "custom-secret",+ "plaintext"));++ MetadataObjectSecretOperations operations =+ new MetadataObjectSecretOperations(secretPropertyOperationDispatcher);+ FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);++ try (MockedStatic<MetadataAuthzHelper> metadataAuthzHelper =+ mockStatic(MetadataAuthzHelper.class)) {+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.checkAccess(+ any(),+ any(Entity.EntityType.class),+ eq(+ AuthorizationExpressionConstants+ .FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)))+ .thenReturn(true);+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.checkAccess(+ any(),+ any(Entity.EntityType.class),+ eq(+ AuthorizationExpressionConstants+ .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION)))+ .thenReturn(false);++ Response response =+ operations.getSecrets(metalake, metadataObject.type().name(), metadataObject.fullName());++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());+ SecretsResponse secretResponse = (SecretsResponse) response.getEntity();+ Assertions.assertEquals(0, secretResponse.getCode());+ Assertions.assertEquals("db-pass", secretResponse.getSecrets().get("jdbc-password"));+ Assertions.assertEquals("plaintext", secretResponse.getSecrets().get("custom-secret"));+ Assertions.assertFalse(secretResponse.getSecrets().containsKey("s3-access-key-id"));+ Assertions.assertFalse(secretResponse.getSecrets().containsKey("s3-secret-access-key"));+ }+ }++ @Test+ public void testGetSecretsIncludesCloudKeysWithUseSecretsAndIncludeCredentialSecretss()+ throws Exception {+ MetadataObject metadataObject =+ MetadataObjects.parse("catalog.schema.fileset", MetadataObject.Type.FILESET);+ when(secretPropertyOperationDispatcher.getSecrets(any(), any(Entity.EntityType.class)))+ .thenReturn(+ Map.of(+ "s3-access-key-id",+ "AKIA",+ "s3-secret-access-key",+ "secret",+ "jdbc-password",+ "db-pass"));++ MetadataObjectSecretOperations operations =+ new MetadataObjectSecretOperations(secretPropertyOperationDispatcher);+ FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);++ try (MockedStatic<MetadataAuthzHelper> metadataAuthzHelper =+ mockStatic(MetadataAuthzHelper.class)) {+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.checkAccess(+ any(),+ any(Entity.EntityType.class),+ eq(+ AuthorizationExpressionConstants+ .FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)))+ .thenReturn(true);+ metadataAuthzHelper+ .when(+ () ->+ MetadataAuthzHelper.checkAccess(+ any(),+ any(Entity.EntityType.class),+ eq(+ AuthorizationExpressionConstants+ .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION)))+ .thenReturn(true);++ Response response =+ operations.getSecrets(metalake, metadataObject.type().name(), metadataObject.fullName());++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());+ SecretsResponse secretResponse = (SecretsResponse) response.getEntity();+ Assertions.assertEquals(0, secretResponse.getCode());+ Assertions.assertEquals("AKIA", secretResponse.getSecrets().get("s3-access-key-id"));+ Assertions.assertEquals("secret", secretResponse.getSecrets().get("s3-secret-access-key"));+ Assertions.assertEquals("db-pass", secretResponse.getSecrets().get("jdbc-password"));+ }+ }+private void testGetSecretsForObject(MetadataObject metadataObject) {when(secretPropertyOperationDispatcher.getSecrets(any(), any(Entity.EntityType.class))).thenReturn(Map.of("custom-secret", "plaintext"));diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.javaindex a9a9ffa186..b262244a61 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/catalog/BaseCatalog.java@@ -34,10 +34,14 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.Schema;import org.apache.gravitino.SchemaChange;import org.apache.gravitino.authorization.Privilege;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.CredentialInfos;import org.apache.gravitino.exceptions.ForbiddenException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.exceptions.NonEmptySchemaException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.function.Function;import org.apache.gravitino.function.FunctionDefinition;@@ -71,6 +75,8 @@ import org.apache.spark.sql.connector.expressions.Transform;import org.apache.spark.sql.types.StructField;import org.apache.spark.sql.types.StructType;import org.apache.spark.sql.util.CaseInsensitiveStringMap;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** BaseCatalog acts as the foundational class for Apache Spark CatalogManager registration, enabling@@ -86,6 +92,8 @@ import org.apache.spark.sql.util.CaseInsensitiveStringMap;*/public abstract class BaseCatalog implements TableCatalog, SupportsNamespaces, FunctionCatalog {+ private static final Logger LOG = LoggerFactory.getLogger(BaseCatalog.class);+// The specific Spark catalog to do IO operations, different catalogs have different spark catalog// implementations, like HiveTableCatalog for Hive, JDBCTableCatalog for JDBC, SparkCatalog for// Iceberg.@@ -725,7 +733,28 @@ public abstract class BaseCatalog implements TableCatalog, SupportsNamespaces, Fprivate static Map<String, String> propsWithSecrets(Catalog catalog) {Map<String, String> props =new HashMap<>(catalog.properties() == null ? Collections.emptyMap() : catalog.properties());- props.putAll(catalog.supportsSecrets().getSecrets());+ try {+ Map<String, String> secrets = catalog.supportsSecrets().getSecrets();+ if (secrets != null) {+ props.putAll(secrets);+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Stubs may not implement SupportsSecrets; older servers lack /secrets.+ LOG.debug("Skipping getSecrets while resolving Spark catalog properties: {}", e.toString());+ }+ try {+ Credential[] credentials = catalog.supportsCredentials().getCredentials();+ props.putAll(CredentialInfos.nonExpiringCredentialInfo(credentials));+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Stubs may not implement SupportsCredentials; older servers lack /credentials.+ LOG.debug(+ "Skipping getCredentials while resolving Spark catalog properties: {}", e.toString());+ } catch (RESTException e) {+ LOG.warn(+ "Failed to resolve getCredentials while building Spark catalog properties; continuing"+ + " without static credential info: {}",+ e.toString());+ }return props;}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.javaindex 593ba6c529..69a33ebb74 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java@@ -19,6 +19,8 @@package org.apache.gravitino.spark.connector.catalog;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -27,9 +29,17 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Properties;+import java.util.stream.Stream;import org.apache.gravitino.Catalog;import org.apache.gravitino.Config;import org.apache.gravitino.client.GravitinoClient;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.JdbcCredential;+import org.apache.gravitino.credential.S3SecretKeyCredential;+import org.apache.gravitino.credential.S3TokenCredential;+import org.apache.gravitino.credential.SupportsCredentials;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretManager;import org.apache.gravitino.secret.SecretMaterial;@@ -49,6 +59,8 @@ import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.MethodSource;@TestInstance(TestInstance.Lifecycle.PER_CLASS)public class TestBaseCatalogSecrets {@@ -91,35 +103,117 @@ public class TestBaseCatalogSecrets {void testMergeMemorySecrets() {try (SecretManager sm = memorySecretManager()) {Map<String, String> entityProps = new HashMap<>();- entityProps.put("jdbc-user", "root");+ entityProps.put("custom-token", "placeholder");List<SecretMaterial> writes =sm.assembleSecretMaterials(- Map.of("jdbc-user", "root"),+ Map.of(),entityProps,"catalog",1L,- Map.of("jdbc-password", new SecretBinding("memory", "from-memory")),+ Map.of("custom-token", new SecretBinding("memory", "from-memory")),Map.of());sm.writeSecrets(writes);Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm, entityProps);- setUpCatalog(Map.of("jdbc-url", "jdbc:mysql://localhost/db"), secrets);+ setUpCatalog(+ Map.of("jdbc-url", "jdbc:mysql://localhost/db"),+ secrets,+ new Credential[] {new JdbcCredential("root", "jdbc-pwd")});catalog.initialize("jdbc", new CaseInsensitiveStringMap(Map.of()));assertEquals("jdbc:mysql://localhost/db", catalog.lastProperties.get("jdbc-url"));- assertEquals("from-memory", catalog.lastProperties.get("jdbc-password"));+ assertEquals("from-memory", catalog.lastProperties.get("custom-token"));+ assertEquals("jdbc-pwd", catalog.lastProperties.get("jdbc-password"));}}+ static Stream<RuntimeException> getCredentialsFailures() {+ return Stream.of(+ new RESTException("transient failure"),+ new NotFoundException("credentials endpoint missing"));+ }++ @Test+ void testGetSecretsRestExceptionAbortsInitialize() {+ Catalog gravitinoCatalog = mock(Catalog.class);+ SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ TableCatalog sparkCatalog = mock(TableCatalog.class);+ when(gravitinoCatalog.type()).thenReturn(Catalog.Type.RELATIONAL);+ when(gravitinoCatalog.provider()).thenReturn("hive");+ when(gravitinoCatalog.properties())+ .thenReturn(Map.of("metastore.uris", "thrift://localhost:9083"));+ when(gravitinoCatalog.supportsSecrets()).thenReturn(supportsSecrets);+ when(supportsSecrets.getSecrets()).thenThrow(new RESTException("transient /secrets failure"));+ when(gravitinoClient.loadCatalog(any())).thenReturn(gravitinoCatalog);+ GravitinoCatalogManager.get().close();+ GravitinoCatalogManager.create(new SparkConf(false), "user", identity -> gravitinoClient);+ catalog = new CapturingCatalog(sparkCatalog);++ assertThrows(+ RESTException.class,+ () -> catalog.initialize("hive", new CaseInsensitiveStringMap(Map.of())));+ }++ @ParameterizedTest+ @MethodSource("getCredentialsFailures")+ void testGetCredentialsFailureDoesNotAbortInitialize(RuntimeException failure) {+ Catalog gravitinoCatalog = mock(Catalog.class);+ SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);+ TableCatalog sparkCatalog = mock(TableCatalog.class);+ when(gravitinoCatalog.type()).thenReturn(Catalog.Type.RELATIONAL);+ when(gravitinoCatalog.provider()).thenReturn("hive");+ when(gravitinoCatalog.properties())+ .thenReturn(Map.of("metastore.uris", "thrift://localhost:9083"));+ when(gravitinoCatalog.supportsSecrets()).thenReturn(supportsSecrets);+ when(supportsSecrets.getSecrets()).thenReturn(Map.of());+ when(gravitinoCatalog.supportsCredentials()).thenReturn(supportsCredentials);+ when(supportsCredentials.getCredentials()).thenThrow(failure);+ when(gravitinoClient.loadCatalog(any())).thenReturn(gravitinoCatalog);+ GravitinoCatalogManager.get().close();+ GravitinoCatalogManager.create(new SparkConf(false), "user", identity -> gravitinoClient);+ catalog = new CapturingCatalog(sparkCatalog);++ catalog.initialize("hive", new CaseInsensitiveStringMap(Map.of()));++ assertEquals("thrift://localhost:9083", catalog.lastProperties.get("metastore.uris"));+ }++ @Test+ void testSkipsExpiringCredentialsFromGetCredentials() {+ setUpCatalog(+ Map.of("s3-endpoint", "http://s3.example.com"),+ Map.of(),+ new Credential[] {+ new S3TokenCredential("SESSION", "session-secret", "tok", 1_700_000_000_000L),+ new S3SecretKeyCredential("AKIATEST", "static-secret")+ });++ catalog.initialize("hive", new CaseInsensitiveStringMap(Map.of()));++ assertEquals("AKIATEST", catalog.lastProperties.get("s3-access-key-id"));+ assertEquals("static-secret", catalog.lastProperties.get("s3-secret-access-key"));+ assertFalse(catalog.lastProperties.containsKey("s3-session-token"));+ assertEquals("http://s3.example.com", catalog.lastProperties.get("s3-endpoint"));+ }+private void setUpCatalog(Map<String, String> properties, Map<String, String> secrets) {+ setUpCatalog(properties, secrets, new Credential[0]);+ }++ private void setUpCatalog(+ Map<String, String> properties, Map<String, String> secrets, Credential[] credentials) {Catalog gravitinoCatalog = mock(Catalog.class);SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);TableCatalog sparkCatalog = mock(TableCatalog.class);when(gravitinoCatalog.type()).thenReturn(Catalog.Type.RELATIONAL);when(gravitinoCatalog.provider()).thenReturn("hive");when(gravitinoCatalog.properties()).thenReturn(properties);when(gravitinoCatalog.supportsSecrets()).thenReturn(supportsSecrets);when(supportsSecrets.getSecrets()).thenReturn(secrets);+ when(gravitinoCatalog.supportsCredentials()).thenReturn(supportsCredentials);+ when(supportsCredentials.getCredentials()).thenReturn(credentials);when(gravitinoClient.loadCatalog(any())).thenReturn(gravitinoCatalog);// Catalog info is cached; recreate the manager so each test loads the new mock.GravitinoCatalogManager.get().close();diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.javaindex 5c5bd5f85b..8e7e0b6d0a 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java@@ -157,8 +157,8 @@ public abstract class SparkAuthorizationIT extends BaseIT {Privileges.UseSchema.allow(),Privileges.SelectTable.allow(),Privileges.CreateTable.allow(),- // Spark JDBC catalog needs vended jdbc-password via getCredentials / getSecrets.- Privileges.UseSecret.allow()));+ // Spark JDBC catalog needs USE_SECRETS to receive vended jdbc credentials.+ Privileges.UseSecrets.allow()));gravitinoMetalake.createRole(ROLE, new HashMap<>(), ImmutableList.of(securableObject));gravitinoMetalake.grantRolesToUser(ImmutableList.of(ROLE), NORMAL_USER);}@@ -286,7 +286,7 @@ public abstract class SparkAuthorizationIT extends BaseIT {SecurableObject catalogObject =SecurableObjects.ofCatalog(JDBC_CATALOG,- ImmutableList.of(Privileges.UseCatalog.allow(), Privileges.UseSecret.allow()));+ ImmutableList.of(Privileges.UseCatalog.allow(), Privileges.UseSecrets.allow()));SecurableObject schemaObject =SecurableObjects.ofSchema(catalogObject,@@ -336,7 +336,7 @@ public abstract class SparkAuthorizationIT extends BaseIT {Privileges.UseSchema.allow(),Privileges.SelectTable.allow(),Privileges.CreateTable.allow(),- Privileges.UseSecret.allow()));+ Privileges.UseSecrets.allow()));gravitinoMetalake.createRole(testRole, new HashMap<>(), ImmutableList.of(catalogObject));gravitinoMetalake.grantRolesToUser(ImmutableList.of(testRole), NORMAL_USER);diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.javaindex 838b9d9a8d..2b2aecaae6 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java@@ -197,8 +197,8 @@ public abstract class SparkJwksAuthorizationIT extends BaseIT {Privileges.UseSchema.allow(),Privileges.CreateTable.allow(),Privileges.SelectTable.allow(),- // Spark JDBC needs USE_SECRET to receive vended jdbc credentials.- Privileges.UseSecret.allow()));+ // Spark JDBC needs USE_SECRETS to receive vended jdbc credentials.+ Privileges.UseSecrets.allow()));metalake.createRole(ALICE_ROLE, new HashMap<>(), ImmutableList.of(catalogAccess));metalake.grantRolesToUser(ImmutableList.of(ALICE_ROLE), ALICE);}@@ -246,7 +246,7 @@ public abstract class SparkJwksAuthorizationIT extends BaseIT {Privileges.UseCatalog.allow(),Privileges.UseSchema.allow(),Privileges.SelectTable.allow(),- Privileges.UseSecret.allow()));+ Privileges.UseSecrets.allow()));adminMetalake.createRole(BOB_ROLE, new HashMap<>(), ImmutableList.of(bobCatalogAccess));adminMetalake.grantRolesToUser(ImmutableList.of(BOB_ROLE), BOB);diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.javaindex fb393a78eb..a7280cf53f 100644--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java@@ -44,7 +44,10 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Catalog;import org.apache.gravitino.client.GravitinoAdminClient;import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.credential.CredentialInfos;import org.apache.gravitino.exceptions.NoSuchMetalakeException;+import org.apache.gravitino.exceptions.NotFoundException;+import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.trino.connector.GravitinoConfig;import org.apache.gravitino.trino.connector.GravitinoErrorCode;import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergConnectorAdapter;@@ -1058,21 +1061,21 @@ public class CatalogConnectorManager {}/**- * Overlays the secrets the Gravitino server vends for this catalog onto its properties.+ * Overlays secrets and non-expiring credential info onto catalog properties.** <p>Resolved here, on the node that is about to build the connector, rather than once at* registration time: the registered definition travels through a CREATE CATALOG statement that* Trino persists as a catalog properties file, and a secret placed in it would be readable there- * for as long as the catalog exists.+ * for as long as the catalog exists. {@code getSecrets()} failures other than missing-endpoint /+ * unsupported are fatal (this connector is cached). Missing {@code /credentials} is tolerated for+ * older servers.*/private GravitinoCatalog withResolvedSecrets(GravitinoCatalog catalog, GravitinoMetalake metalake) {- Map<String, String> secrets;+ Catalog loaded;try {- secrets = metalake.loadCatalog(catalog.getName()).supportsSecrets().getSecrets();+ loaded = metalake.loadCatalog(catalog.getName());} catch (Exception e) {- // Named explicitly: the caller's message only says the connector could not be created, and- // this step is the one that needs the Gravitino server reachable from this node.throw new TrinoException(GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,String.format(@@ -1080,11 +1083,52 @@ public class CatalogConnectorManager {catalog.getName(), catalog.getMetalake(), toErrorMessage(e)),e);}- if (secrets.isEmpty()) {+ Map<String, String> properties = new HashMap<>(catalog.getProperties());+ try {+ Map<String, String> secrets = loaded.supportsSecrets().getSecrets();+ if (secrets != null && !secrets.isEmpty()) {+ properties.putAll(secrets);+ }+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Catalog may not support secrets, or older servers lack /secrets.+ LOG.debug(+ "Skipping getSecrets for catalog %s in metalake %s: %s",+ catalog.getName(), catalog.getMetalake(), e.toString());+ } catch (Exception e) {+ // Fail-fast on RESTException and unexpected errors: this connector is cached, so continuing+ // with masked ****** properties would leave a permanently broken catalog after a transient+ // /secrets failure.+ throw new TrinoException(+ GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,+ String.format(+ "Failed to resolve the secrets of catalog %s in metalake %s: %s",+ catalog.getName(), catalog.getMetalake(), toErrorMessage(e)),+ e);+ }+ try {+ properties.putAll(+ CredentialInfos.nonExpiringCredentialInfo(loaded.supportsCredentials().getCredentials()));+ } catch (UnsupportedOperationException | NotFoundException e) {+ // Catalog may not support credential vending, or older servers lack /credentials.+ LOG.debug(+ "Skipping getCredentials for catalog %s in metalake %s: %s",+ catalog.getName(), catalog.getMetalake(), e.toString());+ } catch (RESTException e) {+ LOG.warn(+ "Failed to resolve getCredentials for catalog %s in metalake %s; continuing without"+ + " static credential info: %s",+ catalog.getName(), catalog.getMetalake(), e.toString());+ } catch (Exception e) {+ throw new TrinoException(+ GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,+ String.format(+ "Failed to resolve the credentials of catalog %s in metalake %s: %s",+ catalog.getName(), catalog.getMetalake(), toErrorMessage(e)),+ e);+ }+ if (properties.equals(catalog.getProperties())) {return catalog;}- Map<String, String> properties = new HashMap<>(catalog.getProperties());- properties.putAll(secrets);return new GravitinoCatalog(catalog.getMetalake(),catalog.getProvider(),diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/GravitinoMockServer.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/GravitinoMockServer.javaindex 648de60c07..42fdd60193 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/GravitinoMockServer.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/GravitinoMockServer.java@@ -53,6 +53,8 @@ import org.apache.gravitino.Schema;import org.apache.gravitino.SupportsSchemas;import org.apache.gravitino.client.GravitinoAdminClient;import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchMetalakeException;import org.apache.gravitino.rel.Column;@@ -248,6 +250,9 @@ public class GravitinoMockServer implements AutoCloseable {SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);when(supportsSecrets.getSecrets()).thenReturn(Map.of());when(catalog.supportsSecrets()).thenReturn(supportsSecrets);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);+ when(supportsCredentials.getCredentials()).thenReturn(new Credential[0]);+ when(catalog.supportsCredentials()).thenReturn(supportsCredentials);Audit mockAudit = mock(Audit.class);when(mockAudit.creator()).thenReturn("gravitino");diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.javaindex c4d08237d9..2586d526dd 100644--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java@@ -47,6 +47,9 @@ import org.apache.gravitino.Audit;import org.apache.gravitino.Catalog;import org.apache.gravitino.client.GravitinoAdminClient;import org.apache.gravitino.client.GravitinoMetalake;+import org.apache.gravitino.credential.Credential;+import org.apache.gravitino.credential.JdbcCredential;+import org.apache.gravitino.credential.SupportsCredentials;import org.apache.gravitino.exceptions.RESTException;import org.apache.gravitino.secret.SupportsSecrets;import org.apache.gravitino.trino.connector.GravitinoConfig;@@ -1456,7 +1459,7 @@ public class TestCatalogConnectorManager {Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);when(catalog.properties()).thenReturn(Map.of("visible", "v1", "shared", "from-props"));when(catalog.supportsSecrets().getSecrets())- .thenReturn(Map.of("jdbc-password", "hunter2", "shared", "from-secret"));+ .thenReturn(Map.of("custom-token", "hunter2", "shared", "from-secret"));fixture.withCatalogs(catalog);CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());@@ -1469,7 +1472,7 @@ public class TestCatalogConnectorManager {Map<String, String> properties = registered.getValue().getProperties();assertEquals("v1", properties.get("visible"));assertEquals("from-props", properties.get("shared"));- assertFalse(properties.containsKey("jdbc-password"));+ assertFalse(properties.containsKey("custom-token"));assertFalse(properties.toString().contains("hunter2"));}@@ -1479,7 +1482,9 @@ public class TestCatalogConnectorManager {Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);when(catalog.properties()).thenReturn(Map.of("visible", "v1", "shared", "from-props"));when(catalog.supportsSecrets().getSecrets())- .thenReturn(Map.of("jdbc-password", "hunter2", "shared", "from-secret"));+ .thenReturn(Map.of("custom-token", "hunter2", "shared", "from-secret"));+ when(catalog.supportsCredentials().getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("u", "jdbc-secret")});fixture.withCatalogs(catalog);CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());@@ -1503,8 +1508,60 @@ public class TestCatalogConnectorManager {verify(fixture.catalogFactory).createCatalogConnectorContextBuilder(built.capture());Map<String, String> properties = built.getValue().getProperties();assertEquals("v1", properties.get("visible"));- assertEquals("hunter2", properties.get("jdbc-password"));+ assertEquals("hunter2", properties.get("custom-token"));assertEquals("from-secret", properties.get("shared"));+ assertEquals("jdbc-secret", properties.get("jdbc-password"));+ assertEquals("u", properties.get("jdbc-user"));+ }++ @Test+ public void testConnectorContextFailsFastOnSecretsRestException() throws Exception {+ LoadFixture fixture = new LoadFixture();+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);+ when(catalog.properties()).thenReturn(Map.of("visible", "v1"));+ when(catalog.supportsSecrets().getSecrets())+ .thenThrow(new RESTException("simulated: /secrets unavailable"));+ fixture.withCatalogs(catalog);+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());++ TrinoException error =+ assertThrows(+ TrinoException.class,+ () ->+ manager.createCatalogConnectorContext(+ "memory",+ createConnectorConfig(+ GravitinoCatalog.toJson(+ new GravitinoCatalog(+ "test", "memory", "memory", Map.of("visible", "v1"), 0L))),+ mockContext()));+ assertTrue(error.getMessage().contains("Failed to resolve the secrets"));+ }++ @Test+ public void testConnectorContextToleratesMissingCredentialsEndpoint() throws Exception {+ LoadFixture fixture = new LoadFixture();+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);+ when(catalog.properties()).thenReturn(Map.of("visible", "v1"));+ when(catalog.supportsSecrets().getSecrets()).thenReturn(Map.of());+ when(catalog.supportsCredentials().getCredentials())+ .thenThrow(new RESTException("simulated: older server lacks /credentials"));+ fixture.withCatalogs(catalog);+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());++ assertDoesNotThrow(+ () ->+ manager.createCatalogConnectorContext(+ "memory",+ createConnectorConfig(+ GravitinoCatalog.toJson(+ new GravitinoCatalog(+ "test", "memory", "memory", Map.of("visible", "v1"), 0L))),+ mockContext()));++ ArgumentCaptor<GravitinoCatalog> built = ArgumentCaptor.forClass(GravitinoCatalog.class);+ verify(fixture.catalogFactory).createCatalogConnectorContextBuilder(built.capture());+ assertEquals("v1", built.getValue().getProperties().get("visible"));}@Test@@ -1592,6 +1649,9 @@ public class TestCatalogConnectorManager {SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);when(supportsSecrets.getSecrets()).thenReturn(Map.of());when(catalog.supportsSecrets()).thenReturn(supportsSecrets);+ SupportsCredentials supportsCredentials = mock(SupportsCredentials.class);+ when(supportsCredentials.getCredentials()).thenReturn(new Credential[0]);+ when(catalog.supportsCredentials()).thenReturn(supportsCredentials);Audit audit = mock(Audit.class);when(audit.createTime()).thenReturn(Instant.now());when(audit.lastModifiedTime()).thenReturn(null);