World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12297] feat(secret): Support fileset create-time secretBindings/secretReferences (#12366)
MaSaid5d90f45e8d2
diff --git a/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java b/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.javaindex 448b1990a7..68bddf96ed 100644--- a/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java+++ b/api/src/main/java/org/apache/gravitino/file/FilesetCatalog.java@@ -21,6 +21,7 @@ package org.apache.gravitino.file;import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;import com.google.common.collect.ImmutableMap;+import java.util.Collections;import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -30,6 +31,8 @@ import org.apache.gravitino.exceptions.NoSuchFilesetException;import org.apache.gravitino.exceptions.NoSuchLocationNameException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.file.FilesetChange.RenameFileset;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** The FilesetCatalog interface defines the public API for managing fileset objects in a schema. If@@ -105,6 +108,43 @@ public interface FilesetCatalog {properties);}+ /**+ * Create a fileset metadata with a default location and optional create-time secrets.+ *+ * @param ident A fileset identifier.+ * @param comment The comment of the fileset.+ * @param type The type of the fileset.+ * @param storageLocation The storage location of the fileset.+ * @param properties The properties of the fileset.+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).+ * @return The created fileset metadata+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws FilesetAlreadyExistsException If the fileset already exists.+ */+ default Fileset createFileset(+ NameIdentifier ident,+ String comment,+ Fileset.Type type,+ String storageLocation,+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)+ throws NoSuchSchemaException, FilesetAlreadyExistsException {+ return createMultipleLocationFileset(+ ident,+ comment,+ type,+ storageLocation == null+ ? ImmutableMap.of()+ : ImmutableMap.of(LOCATION_NAME_UNKNOWN, storageLocation),+ properties,+ secretBindings,+ secretReferences);+ }+/*** Create a fileset metadata with multiple storage locations in the catalog.*@@ -113,6 +153,10 @@ public interface FilesetCatalog {* @param type The type of the fileset.* @param storageLocations The location names and storage locations of the fileset.* @param properties The properties of the fileset.+ * @param secretBindings optional property key → binding ({@code provider} + {@code plaintext})+ * for write-through+ * @param secretReferences optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).* @return The created fileset metadata* @throws NoSuchSchemaException If the schema does not exist.* @throws FilesetAlreadyExistsException If the fileset already exists.@@ -122,11 +166,42 @@ public interface FilesetCatalog {String comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {throw new UnsupportedOperationException("Not implemented");}+ /**+ * Create a fileset metadata with multiple storage locations in the catalog.+ *+ * @param ident A fileset identifier.+ * @param comment The comment of the fileset.+ * @param type The type of the fileset.+ * @param storageLocations The location names and storage locations of the fileset.+ * @param properties The properties of the fileset.+ * @return The created fileset metadata+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws FilesetAlreadyExistsException If the fileset already exists.+ */+ default Fileset createMultipleLocationFileset(+ NameIdentifier ident,+ String comment,+ Fileset.Type type,+ Map<String, String> storageLocations,+ Map<String, String> properties)+ throws NoSuchSchemaException, FilesetAlreadyExistsException {+ return createMultipleLocationFileset(+ ident,+ comment,+ type,+ storageLocations,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }+/*** Apply the {@link FilesetChange change} to a fileset in the catalog.*diff --git a/api/src/main/java/org/apache/gravitino/secret/SecretUrn.java b/api/src/main/java/org/apache/gravitino/secret/SecretUrn.javaindex d9bf7dc6c1..e9b59a0034 100644--- a/api/src/main/java/org/apache/gravitino/secret/SecretUrn.java+++ b/api/src/main/java/org/apache/gravitino/secret/SecretUrn.java@@ -69,6 +69,18 @@ public final class SecretUrn {return identifierSegments;}+ /**+ * Returns the property key encoded as the last identifier segment.+ *+ * <p>Gravitino secret URNs end with the entity property key that stores the URN (see {@link+ * #buildWriteThrough}). Identifier segments are validated when the URN is parsed or built.+ *+ * @return the property key+ */+ public String propertyKey() {+ return identifierSegments.get(identifierSegments.size() - 1);+ }+/*** Builds a write-through secret URN for an entity property secret.*diff --git a/api/src/test/java/org/apache/gravitino/secret/TestSecretUrn.java b/api/src/test/java/org/apache/gravitino/secret/TestSecretUrn.javaindex be0c42f3e6..49a4073ebd 100644--- a/api/src/test/java/org/apache/gravitino/secret/TestSecretUrn.java+++ b/api/src/test/java/org/apache/gravitino/secret/TestSecretUrn.java@@ -44,6 +44,7 @@ public class TestSecretUrn {Assertions.assertEquals("urn:gravitino-secret:memory:catalog:42:jdbc-password", urn.toString());Assertions.assertEquals("memory", urn.providerName());Assertions.assertEquals(List.of("catalog", "42", "jdbc-password"), urn.identifierSegments());+ Assertions.assertEquals("jdbc-password", urn.propertyKey());SecretUrn parsed = SecretUrn.parse(urn.toString());Assertions.assertEquals(urn, parsed);@@ -58,6 +59,7 @@ public class TestSecretUrn {Assertions.assertEquals("local", urn.providerName());Assertions.assertEquals(List.of("catalog", "1", "authentication.password"), urn.identifierSegments());+ Assertions.assertEquals("authentication.password", urn.propertyKey());}@Testdiff --git a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.javaindex 6f2e7b3b86..42fe482feb 100644--- a/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java@@ -104,6 +104,7 @@ import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.metrics.MetricsSystem;import org.apache.gravitino.metrics.source.FilesetCatalogMetricsSource;+import org.apache.gravitino.secret.SecretManager;import org.apache.gravitino.utils.FilesetUtil;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;@@ -127,6 +128,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsprivate final EntityStore store;+ private final SecretManager secretManager;+private HasPropertyMetadata propertiesMetadata;@VisibleForTesting Configuration hadoopConf;@@ -168,8 +171,9 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations}};- FilesetCatalogOperations(EntityStore store) {+ FilesetCatalogOperations(EntityStore store, SecretManager secretManager) {this.store = store;+ this.secretManager = secretManager;}static class FileSystemCacheKey {@@ -215,7 +219,7 @@ public class FilesetCatalogOperations extends ManagedSchemaOperations}public FilesetCatalogOperations() {- this(GravitinoEnv.getInstance().entityStore());+ this(GravitinoEnv.getInstance().entityStore(), GravitinoEnv.getInstance().secretManager());}@Override@@ -1510,10 +1514,14 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsNameIdentifier ident, Map<String, String> entityProperties, Path path) {// Merge configurations from catalog, schema, and entity (fileset) levels, and also include// user-defined configurations for the specified location.+ //+ // Catalog conf is already plaintext (CatalogManager.createBaseCatalog). Schema/fileset entity+ // properties keep secret URNs in storage; resolve them here so FileSystem ops see plaintext,+ // matching the catalog "storage=URN / connector=plaintext" split.Map<String, String> mergedProperties = new HashMap<>(conf);if (ident.namespace().levels().length == 2) {// schema level- mergedProperties.putAll(entityProperties);+ mergedProperties.putAll(secretManager.toPlaintextProperties(entityProperties));// Add user-defined configs for location if providedmergedProperties.putAll(FilesetUtil.getUserDefinedFileSystemConfigs(@@ -1527,8 +1535,8 @@ public class FilesetCatalogOperations extends ManagedSchemaOperationsNameIdentifierUtil.checkFileset(ident);NameIdentifier schemaIdent = NameIdentifierUtil.getSchemaIdentifier(ident);Schema schema = loadSchema(schemaIdent);- mergedProperties.putAll(schema.properties());- mergedProperties.putAll(entityProperties);+ mergedProperties.putAll(secretManager.toPlaintextProperties(schema.properties()));+ mergedProperties.putAll(secretManager.toPlaintextProperties(entityProperties));// Add user-defined configs for location if providedmergedProperties.putAll(FilesetUtil.getUserDefinedFileSystemConfigs(diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.javaindex 1a55d19792..d8a4f77c13 100644--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java@@ -62,7 +62,9 @@ import java.nio.file.Paths;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;+import java.util.List;import java.util.Map;+import java.util.Properties;import java.util.Set;import java.util.UUID;import java.util.concurrent.ScheduledThreadPoolExecutor;@@ -102,6 +104,12 @@ import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;import org.apache.gravitino.file.FileInfo;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;+import org.apache.gravitino.secret.SecretConstants;+import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretMaterial;+import org.apache.gravitino.secret.SecretProviderRegistry;+import org.apache.gravitino.secret.SecretUrn;+import org.apache.gravitino.secret.memory.InMemorySecretsProvider;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.RelationalEntityStore;@@ -180,6 +188,8 @@ public class TestFilesetCatalogOperations {private static EntityStore store;+ private static SecretManager secretManager;+private static IdGenerator idGenerator;private static SchemaMetaService spySchemaMetaService;@@ -348,11 +358,27 @@ public class TestFilesetCatalogOperations {.thenReturn(spySchemaMetaService);FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);++ Config secretConfig = new Config(false) {};+ Properties secretProps = new Properties();+ secretProps.setProperty(SecretProviderRegistry.GRAVITINO_SECRET_PROVIDERS, "memory");+ secretProps.setProperty(+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX+ + "memory."+ + SecretProviderRegistry.CLASS_NAME,+ InMemorySecretsProvider.class.getName());+ secretConfig.loadFromProperties(secretProps);+ secretManager = new SecretManager(secretConfig);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "secretManager", secretManager, true);}@AfterAll- public static void tearDown() throws IOException {+ public static void tearDown() throws IOException, IllegalAccessException {store.close();+ if (secretManager != null) {+ secretManager.close();+ FieldUtils.writeField(GravitinoEnv.getInstance(), "secretManager", null, true);+ }new Path(TEST_ROOT_PATH).getFileSystem(new Configuration()).delete(new Path(TEST_ROOT_PATH), true);@@ -364,7 +390,7 @@ public class TestFilesetCatalogOperations {@Testpublic void testFilesetCatalogConfiguration() {Map<String, String> emptyProps = Maps.newHashMap();- FilesetCatalogOperations ops = new FilesetCatalogOperations(store);+ FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager);CatalogInfo catalogInfo = randomCatalogInfo();ops.initialize(emptyProps, catalogInfo, FILESET_PROPERTIES_METADATA);@@ -570,7 +596,7 @@ public class TestFilesetCatalogOperations {Assertions.assertEquals(name, schema.name());- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Schema schema1 = ops.loadSchema(NameIdentifierUtil.ofSchema("m1", "c1", name));Assertions.assertEquals(name, schema1.name());@@ -596,7 +622,7 @@ public class TestFilesetCatalogOperations {createSchema(testId1, name1, comment1, null, null);createSchema(testId2, name2, comment2, null, null);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Set<NameIdentifier> idents =Arrays.stream(ops.listSchemas(Namespace.of("m1", "c1"))).collect(Collectors.toSet());@@ -615,7 +641,7 @@ public class TestFilesetCatalogOperations {Schema schema = createSchema(testId, name, comment, catalogPath, null);Assertions.assertEquals(name, schema.name());- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Schema schema1 = ops.loadSchema(NameIdentifierUtil.ofSchema("m1", "c1", name));Assertions.assertEquals(name, schema1.name());@@ -664,7 +690,7 @@ public class TestFilesetCatalogOperations {Assertions.assertEquals(schemaName, schema.name());NameIdentifier id = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(ImmutableMap.of(LOCATION, catalogPath),randomCatalogInfo("m1", "c1"),@@ -736,7 +762,7 @@ public class TestFilesetCatalogOperations {Assertions.assertEquals(schemaName, schema.name());NameIdentifier id = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(ImmutableMap.of(LOCATION, catalogPath, DISABLE_FILESYSTEM_OPS, "true"),randomCatalogInfo("m1", "c1"),@@ -778,7 +804,7 @@ public class TestFilesetCatalogOperations {}NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);if (!ops.schemaExists(schemaIdent)) {createSchema(generateTestId(), schemaName, comment, catalogPath, schemaPath);@@ -835,7 +861,7 @@ public class TestFilesetCatalogOperations {}NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);if (!ops.schemaExists(schemaIdent)) {createSchema(generateTestId(), schemaName, comment, catalogPath, schemaPath, true);@@ -911,7 +937,7 @@ public class TestFilesetCatalogOperations {+ " when it's catalog and schema "+ "location are not set",exception.getMessage());- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Throwable e =Assertions.assertThrows(@@ -930,7 +956,7 @@ public class TestFilesetCatalogOperations {Assertions.assertEquals("Storage location must be set for external fileset " + filesetIdent,exception1.getMessage());- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Throwable e =Assertions.assertThrows(@@ -955,7 +981,7 @@ public class TestFilesetCatalogOperations {createFileset(fileset, schemaName, comment, Fileset.Type.MANAGED, null, null);}- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Set<NameIdentifier> idents =Arrays.stream(ops.listFilesets(Namespace.of("m1", "c1", schemaName)))@@ -979,7 +1005,7 @@ public class TestFilesetCatalogOperations {createSchema(testId, schemaName, comment, null, schemaPath);createFileset(filesetName, schemaName, comment, Fileset.Type.MANAGED, null, null);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);Path testDir = new Path(schemaPath + "/" + filesetName);@@ -1031,7 +1057,7 @@ public class TestFilesetCatalogOperations {Map<String, String> catalogProps = Collections.singletonMap(DISABLE_FILESYSTEM_OPS, "true");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo(), FILESET_PROPERTIES_METADATA);UnsupportedOperationException ex =Assertions.assertThrows(@@ -1059,7 +1085,7 @@ public class TestFilesetCatalogOperations {final NameIdentifier filesetIdent =NameIdentifier.of("m1", "c1", schema.name(), fileset.name());- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);IllegalArgumentException ex =Assertions.assertThrows(@@ -1092,7 +1118,7 @@ public class TestFilesetCatalogOperations {}NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);if (!ops.schemaExists(schemaIdent)) {createSchema(generateTestId(), schemaName, comment, catalogPath, schemaPath);@@ -1140,7 +1166,7 @@ public class TestFilesetCatalogOperations {FilesetChange change1 = FilesetChange.setProperty("k1", "v1");FilesetChange change2 = FilesetChange.removeProperty("k1");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, filesetName);@@ -1252,7 +1278,7 @@ public class TestFilesetCatalogOperations {Fileset fileset = createFileset(name, schemaName, comment, Fileset.Type.MANAGED, null, null);FilesetChange change1 = FilesetChange.updateComment(comment + "_new");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, name);@@ -1277,7 +1303,7 @@ public class TestFilesetCatalogOperations {createFileset(filesetName, schemaName, comment, Fileset.Type.MANAGED, null, null);FilesetChange change1 = FilesetChange.updateComment(null);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, filesetName);@@ -1291,7 +1317,7 @@ public class TestFilesetCatalogOperations {@Testpublic void testTestConnection() {- FilesetCatalogOperations catalogOperations = new FilesetCatalogOperations(store);+ FilesetCatalogOperations catalogOperations = new FilesetCatalogOperations(store, secretManager);Assertions.assertDoesNotThrow(() ->catalogOperations.testConnection(@@ -1304,7 +1330,7 @@ public class TestFilesetCatalogOperations {@Testvoid testTrailSlash() throws IOException {- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {String location = "hdfs://localhost:9000";Map<String, String> catalogProperties = Maps.newHashMap();@@ -1351,7 +1377,7 @@ public class TestFilesetCatalogOperations {createFileset(filesetName, schemaName, comment, Fileset.Type.MANAGED, null, storageLocation);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, filesetName);// test sub path starts with "/"@@ -1383,7 +1409,7 @@ public class TestFilesetCatalogOperations {TEST_ROOT_PATH + "/" + catalogName + "/" + schemaName + "/" + filesetName2;Path filesetLocationPath2 = new Path(filesetLocation2);createFileset(filesetName2, schemaName, comment, Fileset.Type.MANAGED, null, filesetLocation2);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store);+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager);FileSystem localFileSystem = filesetLocationPath2.getFileSystem(new Configuration())) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, filesetName2);@@ -1415,7 +1441,7 @@ public class TestFilesetCatalogOperations {TEST_ROOT_PATH + "/" + catalogName + "/" + schemaName + "/" + filesetName3;Path filesetLocationPath3 = new Path(filesetLocation3);createFileset(filesetName3, schemaName, comment, Fileset.Type.MANAGED, null, filesetLocation3);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store);+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager);FileSystem localFileSystem = filesetLocationPath3.getFileSystem(new Configuration())) {ops.initialize(Maps.newHashMap(), randomCatalogInfo(), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, filesetName3);@@ -1609,7 +1635,7 @@ public class TestFilesetCatalogOperations {}NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);if (!ops.schemaExists(schemaIdent)) {createSchema(generateTestId(), schemaName, comment, catalogPath, schemaPath);@@ -1664,7 +1690,7 @@ public class TestFilesetCatalogOperations {String comment = "comment_s1";NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogPaths, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);if (!ops.schemaExists(schemaIdent)) {createMultiLocationSchema(schemaName, comment, catalogPaths, schemaPaths);@@ -1732,7 +1758,7 @@ public class TestFilesetCatalogOperations {// empty location name in catalog locationMap<String, String> illegalLocations =ImmutableMap.of(PROPERTY_MULTIPLE_LOCATIONS_PREFIX + "", TEST_ROOT_PATH + "/catalog31_1");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {Exception exception =Assertions.assertThrows(IllegalArgumentException.class,@@ -1843,7 +1869,7 @@ public class TestFilesetCatalogOperations {@Testpublic void testGetTargetLocation() throws IOException {- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(Collections.emptyMap(), randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);@@ -2953,7 +2979,7 @@ public class TestFilesetCatalogOperations {props.put(LOCATION, catalogPath);}- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(props, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", name);@@ -2975,7 +3001,7 @@ public class TestFilesetCatalogOperations {Map<String, String> catalogPaths,Map<String, String> schemaPaths)throws IOException {- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogPaths, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", name);@@ -2997,7 +3023,7 @@ public class TestFilesetCatalogOperations {Map<String, String> storageLocations,Map<String, String> filesetProps)throws IOException {- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogPaths, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, name);@@ -3036,7 +3062,7 @@ public class TestFilesetCatalogOperations {props.put(LOCATION, catalogPath);}- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(props, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, name);@@ -3062,7 +3088,7 @@ public class TestFilesetCatalogOperations {props.put(LOCATION, catalogPath);}- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(props, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName, name);@@ -3090,7 +3116,7 @@ public class TestFilesetCatalogOperations {catalogProps.put("catalog-prop", "catalog-value");catalogProps.put("common-prop", "catalog-common-value");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);// Create schema@@ -3186,7 +3212,7 @@ public class TestFilesetCatalogOperations {FilesetCatalogPropertiesMetadata.FS_GRAVITINO_PATH_CONFIG_PREFIX + "cluster2.endpoint","s3://endpoint2");- try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store)) {+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {ops.initialize(catalogProps, randomCatalogInfo("m1", "c1"), FILESET_PROPERTIES_METADATA);// Create schema@@ -3225,4 +3251,40 @@ public class TestFilesetCatalogOperations {Assertions.assertNull(result3.get("endpoint"));}}++ @Test+ public void testMergeResolvesSecrets() throws Exception {+ long entityId = idGenerator.nextId();+ SecretUrn urn =+ SecretUrn.buildWriteThrough(+ "memory",+ Map.of(+ SecretConstants.ATTR_ENTITY_TYPE, "schema",+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entityId),+ SecretConstants.ATTR_PROPERTY_KEY, "aws-sk"));+ secretManager.writeSecrets(List.of(new SecretMaterial(urn, "super-secret")));++ String schemaName = "schema_secret_" + generateTestId();+ String schemaPath = TEST_ROOT_PATH + "/" + schemaName;+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store, secretManager)) {+ ops.initialize(+ Maps.newHashMap(Map.of(LOCATION, TEST_ROOT_PATH)),+ randomCatalogInfo("m1", "c1"),+ FILESET_PROPERTIES_METADATA);++ NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema("m1", "c1", schemaName);+ Map<String, String> schemaProps =+ Maps.newHashMap(+ StringIdentifier.newPropertiesWithId(+ StringIdentifier.fromId(entityId),+ Map.of(LOCATION, schemaPath, "aws-sk", urn.toString())));+ Schema schema = ops.createSchema(schemaIdent, "comment", schemaProps);+ Assertions.assertEquals(urn.toString(), schema.properties().get("aws-sk"));++ Map<String, String> merged =+ ops.mergeUpLevelConfigurations(schemaIdent, schema.properties(), new Path(schemaPath));+ Assertions.assertEquals("super-secret", merged.get("aws-sk"));+ Assertions.assertEquals(urn.toString(), schema.properties().get("aws-sk"));+ }+ }}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.javaindex 33c9b8d131..40dc2d7286 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/FilesetCatalog.java@@ -42,6 +42,8 @@ import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.FileLocationResponse;import org.apache.gravitino.dto.responses.FilesetResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.exceptions.FilesetAlreadyExistsException;import org.apache.gravitino.exceptions.NoSuchFilesetException;import org.apache.gravitino.exceptions.NoSuchLocationNameException;@@ -49,6 +51,8 @@ import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** Fileset catalog is a catalog implementation that supports fileset like metadata operations, for@@ -133,6 +137,10 @@ class FilesetCatalog extends BaseSchemaCatalog* @param type The type of the fileset.* @param storageLocations The location names and storage locations of the fileset.* @param properties The properties of the fileset.+ * @param secretBindings Optional property key → binding ({ provider} + { plaintext}) for+ * write-through.+ * @param secretReferences Optional property key → secret locator ({@code provider} plus+ * provider-specific attributes).* @return The created fileset metadata* @throws NoSuchSchemaException If the schema does not exist.* @throws FilesetAlreadyExistsException If the fileset already exists.@@ -143,7 +151,9 @@ class FilesetCatalog extends BaseSchemaCatalogString comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {checkFilesetNameIdentifier(ident);@@ -155,6 +165,8 @@ class FilesetCatalog extends BaseSchemaCatalog.type(type).storageLocations(storageLocations).properties(properties)+ .secretBindings(SecretBindingDTO.fromSecretBindings(secretBindings))+ .secretReferences(SecretReferenceDTO.fromSecretReferences(secretReferences)).build();req.validate();diff --git a/clients/client-python/gravitino/api/secret.py b/clients/client-python/gravitino/api/secret.pynew file mode 100644index 0000000000..fb1526afae--- /dev/null+++ b/clients/client-python/gravitino/api/secret.py@@ -0,0 +1,45 @@+# 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.++from dataclasses import dataclass+from typing import Dict+++@dataclass+class SecretBinding:+ """Write-through secret binding: provider instance name plus plaintext."""++ provider: str+ plaintext: str++ def __repr__(self) -> str:+ return f"SecretBinding(provider={self.provider!r}, plaintext=***)"+++@dataclass+class SecretReference:+ """External secret locator: provider instance name plus provider-specific attributes."""++ provider: str+ attributes: Dict[str, str]++ def __post_init__(self):+ if self.attributes is None or len(self.attributes) == 0:+ raise ValueError("attributes must not be null or empty")++ def __repr__(self) -> str:+ return f"SecretReference(provider={self.provider!r}, attributes={self.attributes!r})"diff --git a/clients/client-python/gravitino/client/fileset_catalog.py b/clients/client-python/gravitino/client/fileset_catalog.pyindex 40ee47ae6b..50b458b379 100644--- a/clients/client-python/gravitino/client/fileset_catalog.py+++ b/clients/client-python/gravitino/client/fileset_catalog.py@@ -16,7 +16,8 @@# under the License.import logging-from typing import List, Dict+from types import MappingProxyType+from typing import Dict, List, Mappingfrom gravitino.dto.requests.fileset_create_request import FilesetCreateRequest@@ -25,6 +26,7 @@ from gravitino.api.credential.credential import Credentialfrom gravitino.api.credential.supports_credentials import SupportsCredentialsfrom gravitino.api.file.fileset import Filesetfrom gravitino.api.file.fileset_change import FilesetChange+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.audit.caller_context import CallerContextHolder, CallerContextfrom gravitino.client.base_schema_catalog import BaseSchemaCatalogfrom gravitino.client.generic_fileset import GenericFileset@@ -43,6 +45,9 @@ from gravitino.utils import HTTPClientlogger = logging.getLogger(__name__)+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+class FilesetCatalog(BaseSchemaCatalog, SupportsCredentials@@ -138,6 +143,8 @@ class FilesetCatalog(fileset_type: Fileset.Type,storage_location: str,properties: Dict[str, str],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,) -> Fileset:"""Create a fileset metadata in the catalog.@@ -152,6 +159,8 @@ class FilesetCatalog(fileset_type: The type of the fileset.storage_location: The storage location of the fileset.properties: The properties of the fileset.+ secret_bindings: Optional property key → binding (provider + plaintext) for write-through.+ secret_references: Optional property key → locator attributes.Raises:NoSuchSchemaException If the schema does not exist.@@ -166,7 +175,13 @@ class FilesetCatalog(else {})return self.create_multiple_location_fileset(- ident, comment, fileset_type, locations, properties+ ident,+ comment,+ fileset_type,+ locations,+ properties,+ secret_bindings,+ secret_references,)def create_multiple_location_fileset(@@ -176,6 +191,8 @@ class FilesetCatalog(fileset_type: Fileset.Type,storage_locations: Dict[str, str],properties: Dict[str, str],+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,):"""Create a fileset metadata in the catalog with multiple storage locations.@@ -185,6 +202,8 @@ class FilesetCatalog(fileset_type: The type of the fileset.storage_locations: The location names and storage locations of the fileset.properties: The properties of the fileset.+ secret_bindings: Optional property key → binding (provider + plaintext) for write-through.+ secret_references: Optional property key → locator attributes.Raises:NoSuchSchemaException If the schema does not exist.@@ -203,6 +222,8 @@ class FilesetCatalog(fileset_type=fileset_type,storage_locations=storage_locations,properties=properties,+ secret_bindings=dict(secret_bindings),+ secret_references=dict(secret_references),)req.validate()diff --git a/clients/client-python/gravitino/dto/requests/fileset_create_request.py b/clients/client-python/gravitino/dto/requests/fileset_create_request.pyindex 74b692f215..8b7735319f 100644--- a/clients/client-python/gravitino/dto/requests/fileset_create_request.py+++ b/clients/client-python/gravitino/dto/requests/fileset_create_request.py@@ -16,13 +16,18 @@# under the License.from dataclasses import dataclass, field-from typing import Optional, Dict+from types import MappingProxyType+from typing import Dict, Mapping, Optionalfrom dataclasses_json import configfrom gravitino.api.file.fileset import Fileset+from gravitino.api.secret import SecretBinding, SecretReferencefrom gravitino.rest.rest_message import RESTRequest+_EMPTY_SECRET_BINDINGS: Mapping[str, SecretBinding] = MappingProxyType({})+_EMPTY_SECRET_REFERENCES: Mapping[str, SecretReference] = MappingProxyType({})+@dataclassclass FilesetCreateRequest(RESTRequest):@@ -37,6 +42,12 @@ class FilesetCreateRequest(RESTRequest):_properties: Optional[Dict[str, str]] = field(metadata=config(field_name="properties"))+ _secret_bindings: Dict[str, SecretBinding] = field(+ default_factory=dict, metadata=config(field_name="secretBindings")+ )+ _secret_references: Dict[str, SecretReference] = field(+ default_factory=dict, metadata=config(field_name="secretReferences")+ )def __init__(self,@@ -45,12 +56,16 @@ class FilesetCreateRequest(RESTRequest):fileset_type: Fileset.Type = None,storage_locations: Optional[Dict[str, str]] = None,properties: Optional[Dict[str, str]] = None,+ secret_bindings: Mapping[str, SecretBinding] = _EMPTY_SECRET_BINDINGS,+ secret_references: Mapping[str, SecretReference] = _EMPTY_SECRET_REFERENCES,):self._name = nameself._comment = commentself._type = fileset_typeself._storage_locations = storage_locationsself._properties = properties+ self._secret_bindings = dict(secret_bindings)+ self._secret_references = dict(secret_references)def validate(self):"""Validates the request.diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/FilesetCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/FilesetCreateRequest.javaindex f4c79bca34..55940ef3c5 100644--- a/common/src/main/java/org/apache/gravitino/dto/requests/FilesetCreateRequest.java+++ b/common/src/main/java/org/apache/gravitino/dto/requests/FilesetCreateRequest.java@@ -18,8 +18,10 @@*/package org.apache.gravitino.dto.requests;+import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.annotation.JsonProperty;import com.google.common.base.Preconditions;+import java.util.Collections;import java.util.Map;import javax.annotation.Nullable;import lombok.AllArgsConstructor;@@ -29,6 +31,8 @@ import lombok.Getter;import lombok.NoArgsConstructor;import lombok.ToString;import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.rest.RESTRequest;@@ -64,6 +68,44 @@ public class FilesetCreateRequest implements RESTRequest {@JsonProperty("properties")private Map<String, String> properties;+ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretBindings")+ @Builder.Default+ private Map<String, SecretBindingDTO> secretBindings = Collections.emptyMap();++ @JsonInclude(JsonInclude.Include.NON_EMPTY)+ @JsonProperty("secretReferences")+ @Builder.Default+ private Map<String, SecretReferenceDTO> secretReferences = Collections.emptyMap();++ /**+ * Constructor for FilesetCreateRequest without secret maps.+ *+ * @param name The name of the fileset.+ * @param comment The comment of the fileset.+ * @param type The type of the fileset.+ * @param storageLocation The storage location of the fileset.+ * @param storageLocations The storage locations of the fileset.+ * @param properties The properties of the fileset.+ */+ public FilesetCreateRequest(+ String name,+ String comment,+ Fileset.Type type,+ String storageLocation,+ Map<String, String> storageLocations,+ Map<String, String> properties) {+ this(+ name,+ comment,+ type,+ storageLocation,+ storageLocations,+ properties,+ Collections.emptyMap(),+ Collections.emptyMap());+ }+/*** Validates the request.*diff --git a/common/src/main/java/org/apache/gravitino/dto/secret/SecretBindingDTO.java b/common/src/main/java/org/apache/gravitino/dto/secret/SecretBindingDTO.javanew file mode 100644index 0000000000..fd029fdb39--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/secret/SecretBindingDTO.java@@ -0,0 +1,108 @@+/*+ * 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.dto.secret;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.collect.ImmutableMap;+import java.util.Map;+import javax.annotation.Nullable;+import lombok.AccessLevel;+import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.ToString;+import org.apache.gravitino.secret.SecretBinding;++/** Data transfer object for a write-through {@link SecretBinding}. */+@Getter+@EqualsAndHashCode+@NoArgsConstructor(access = AccessLevel.PRIVATE)+@AllArgsConstructor+@Builder(setterPrefix = "with")+@ToString(exclude = "plaintext")+public class SecretBindingDTO {++ @JsonProperty("provider")+ private String provider;++ @JsonProperty("plaintext")+ private String plaintext;++ /**+ * Converts this DTO to a {@link SecretBinding}.+ *+ * @return the secret binding+ */+ public SecretBinding toSecretBinding() {+ return new SecretBinding(provider, plaintext);+ }++ /**+ * Creates a DTO from a {@link SecretBinding}.+ *+ * @param binding the secret binding+ * @return the secret binding DTO+ */+ public static SecretBindingDTO fromSecretBinding(SecretBinding binding) {+ return new SecretBindingDTO(binding.provider(), binding.plaintext());+ }++ /**+ * Converts a property-key map of DTOs to {@link SecretBinding}s.+ *+ * @param dtos property key → binding DTO; {@code null} or empty returns an empty map+ * @return property key → binding (never {@code null})+ */+ public static Map<String, SecretBinding> toSecretBindings(+ @Nullable Map<String, SecretBindingDTO> dtos) {+ if (dtos == null || dtos.isEmpty()) {+ return ImmutableMap.of();+ }+ ImmutableMap.Builder<String, SecretBinding> bindings = ImmutableMap.builder();+ for (Map.Entry<String, SecretBindingDTO> entry : dtos.entrySet()) {+ String key = entry.getKey();+ SecretBindingDTO dto = entry.getValue();+ if (dto == null) {+ throw new IllegalArgumentException("secretBindings[\"" + key + "\"] must not be null");+ }+ bindings.put(key, dto.toSecretBinding());+ }+ return bindings.build();+ }++ /**+ * Converts a property-key map of {@link SecretBinding}s to DTOs.+ *+ * @param bindings property key → binding; {@code null} or empty returns an empty map+ * @return property key → binding DTO (never {@code null})+ */+ public static Map<String, SecretBindingDTO> fromSecretBindings(+ @Nullable Map<String, SecretBinding> bindings) {+ if (bindings == null || bindings.isEmpty()) {+ return ImmutableMap.of();+ }+ ImmutableMap.Builder<String, SecretBindingDTO> dtos = ImmutableMap.builder();+ for (Map.Entry<String, SecretBinding> entry : bindings.entrySet()) {+ dtos.put(entry.getKey(), fromSecretBinding(entry.getValue()));+ }+ return dtos.build();+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/secret/SecretReferenceDTO.java b/common/src/main/java/org/apache/gravitino/dto/secret/SecretReferenceDTO.javanew file mode 100644index 0000000000..e050e37bc7--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/secret/SecretReferenceDTO.java@@ -0,0 +1,110 @@+/*+ * 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.dto.secret;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.collect.ImmutableMap;+import java.util.Map;+import javax.annotation.Nullable;+import lombok.AccessLevel;+import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.ToString;+import org.apache.gravitino.secret.SecretReference;++/** Data transfer object for an external {@link SecretReference}. */+@Getter+@EqualsAndHashCode+@NoArgsConstructor(access = AccessLevel.PRIVATE)+@AllArgsConstructor+@Builder(setterPrefix = "with")+@ToString+public class SecretReferenceDTO {++ @JsonProperty("provider")+ private String provider;++ @Builder.Default+ @JsonProperty("attributes")+ private Map<String, String> attributes = ImmutableMap.of();++ /**+ * Converts this DTO to a {@link SecretReference}.+ *+ * @return the secret reference+ */+ public SecretReference toSecretReference() {+ Map<String, String> attrs = attributes == null ? ImmutableMap.of() : attributes;+ return new SecretReference(provider, attrs);+ }++ /**+ * Creates a DTO from a {@link SecretReference}.+ *+ * @param reference the secret reference+ * @return the secret reference DTO+ */+ public static SecretReferenceDTO fromSecretReference(SecretReference reference) {+ return new SecretReferenceDTO(reference.provider(), reference.attributes());+ }++ /**+ * Converts a property-key map of DTOs to {@link SecretReference}s.+ *+ * @param dtos property key → reference DTO; {@code null} or empty returns an empty map+ * @return property key → reference (never {@code null})+ */+ public static Map<String, SecretReference> toSecretReferences(+ @Nullable Map<String, SecretReferenceDTO> dtos) {+ if (dtos == null || dtos.isEmpty()) {+ return ImmutableMap.of();+ }+ ImmutableMap.Builder<String, SecretReference> references = ImmutableMap.builder();+ for (Map.Entry<String, SecretReferenceDTO> entry : dtos.entrySet()) {+ String key = entry.getKey();+ SecretReferenceDTO dto = entry.getValue();+ if (dto == null) {+ throw new IllegalArgumentException("secretReferences[\"" + key + "\"] must not be null");+ }+ references.put(key, dto.toSecretReference());+ }+ return references.build();+ }++ /**+ * Converts a property-key map of {@link SecretReference}s to DTOs.+ *+ * @param references property key → reference; {@code null} or empty returns an empty map+ * @return property key → reference DTO (never {@code null})+ */+ public static Map<String, SecretReferenceDTO> fromSecretReferences(+ @Nullable Map<String, SecretReference> references) {+ if (references == null || references.isEmpty()) {+ return ImmutableMap.of();+ }+ ImmutableMap.Builder<String, SecretReferenceDTO> dtos = ImmutableMap.builder();+ for (Map.Entry<String, SecretReference> entry : references.entrySet()) {+ dtos.put(entry.getKey(), fromSecretReference(entry.getValue()));+ }+ return dtos.build();+ }+}diff --git a/common/src/test/java/org/apache/gravitino/dto/secret/TestSecretReferenceDTO.java b/common/src/test/java/org/apache/gravitino/dto/secret/TestSecretReferenceDTO.javanew file mode 100644index 0000000000..0fc812412c--- /dev/null+++ b/common/src/test/java/org/apache/gravitino/dto/secret/TestSecretReferenceDTO.java@@ -0,0 +1,80 @@+/*+ * 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.dto.secret;++import com.google.common.collect.ImmutableMap;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestSecretReferenceDTO {++ @Test+ void testAttributesRequired() {+ SecretReferenceDTO dto = SecretReferenceDTO.builder().withProvider("vault").build();+ Assertions.assertNotNull(dto.getAttributes());+ Assertions.assertTrue(dto.getAttributes().isEmpty());+ Assertions.assertThrows(IllegalArgumentException.class, dto::toSecretReference);++ SecretReference reference =+ SecretReferenceDTO.builder()+ .withProvider("vault")+ .withAttributes(Map.of("path", "secret/data/x"))+ .build()+ .toSecretReference();+ Assertions.assertEquals("vault", reference.provider());+ Assertions.assertEquals("secret/data/x", reference.attributes().get("path"));+ }++ @Test+ void testMapConverters() {+ Assertions.assertEquals(ImmutableMap.of(), SecretReferenceDTO.toSecretReferences(null));+ Assertions.assertEquals(ImmutableMap.of(), SecretReferenceDTO.fromSecretReferences(null));+ Assertions.assertEquals(ImmutableMap.of(), SecretBindingDTO.toSecretBindings(null));+ Assertions.assertEquals(ImmutableMap.of(), SecretBindingDTO.fromSecretBindings(null));++ Map<String, SecretReference> references =+ Map.of("jdbc-password", new SecretReference("vault", Map.of("path", "secret/data/x")));+ Map<String, SecretReferenceDTO> dtos = SecretReferenceDTO.fromSecretReferences(references);+ Assertions.assertEquals(1, dtos.size());+ Assertions.assertEquals(references, SecretReferenceDTO.toSecretReferences(dtos));++ Map<String, SecretBinding> bindings =+ Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));+ Map<String, SecretBindingDTO> bindingDtos = SecretBindingDTO.fromSecretBindings(bindings);+ Assertions.assertEquals(1, bindingDtos.size());+ Assertions.assertEquals(bindings, SecretBindingDTO.toSecretBindings(bindingDtos));+ }++ @Test+ void testNullMapValues() {+ Map<String, SecretReferenceDTO> nullRef = new HashMap<>();+ nullRef.put("jdbc-password", null);+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> SecretReferenceDTO.toSecretReferences(nullRef));++ Map<String, SecretBindingDTO> nullBinding = new HashMap<>();+ nullBinding.put("jdbc-password", null);+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> SecretBindingDTO.toSecretBindings(nullBinding));+ }+}diff --git a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.javaindex 3bafc882b8..72c0139cf4 100644--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java@@ -1303,7 +1303,11 @@ public class CatalogManager implements CatalogDispatcher, Closeable {private BaseCatalog<?> createBaseCatalog(IsolatedClassLoader classLoader, CatalogEntity entity) {// Load Catalog class instanceBaseCatalog<?> catalog = createCatalogInstance(classLoader, entity.getProvider());- catalog.withCatalogConf(entity.getProperties()).withCatalogEntity(entity);+ // Resolve secret URNs to plaintext for connector init only; entity storage keeps URNs.+ // Fileset FS merge assumes catalog conf is already plaintext at this boundary.+ catalog+ .withCatalogConf(secretManager.toPlaintextProperties(entity.getProperties()))+ .withCatalogEntity(entity);catalog.initAuthorizationPluginInstance(classLoader);return catalog;}diff --git a/core/src/main/java/org/apache/gravitino/catalog/FilesetNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/FilesetNormalizeDispatcher.javaindex 292edd8d27..df280664ca 100644--- a/core/src/main/java/org/apache/gravitino/catalog/FilesetNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/FilesetNormalizeDispatcher.java@@ -34,6 +34,8 @@ import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.file.FileInfo;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;/*** Note on list operations: names returned by list methods (e.g. {@link #listFilesets(Namespace)})@@ -82,10 +84,18 @@ public class FilesetNormalizeDispatcher implements FilesetDispatcher {String comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {return dispatcher.createMultipleLocationFileset(- normalizeNameIdentifier(ident), comment, type, storageLocations, properties);+ normalizeNameIdentifier(ident),+ comment,+ type,+ storageLocations,+ properties,+ secretBindings,+ secretReferences);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.javaindex b7f887de7c..b8fe860afe 100644--- a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java@@ -22,6 +22,7 @@ import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validateProimport static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;import java.util.Arrays;+import java.util.List;import java.util.Map;import org.apache.gravitino.EntityStore;import org.apache.gravitino.NameIdentifier;@@ -38,7 +39,11 @@ import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;+import org.apache.gravitino.secret.SecretBinding;import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretMaterial;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.storage.IdGenerator;public class FilesetOperationDispatcher extends OperationDispatcher implements FilesetDispatcher {@@ -143,45 +148,61 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements FString comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {NameIdentifier catalogIdent = getCatalogIdentifier(ident);+ long uid = idGenerator.nextId();+ Map<String, String> entityProperties = SecretPropertyUtils.copyEntityProperties(properties);+ List<SecretMaterial> secretMaterials =+ secretManager.assembleSecretMaterials(+ properties, entityProperties, "fileset", uid, secretBindings, secretReferences);doWithCatalog(catalogIdent,c ->c.doWithPropertiesMeta(p -> {- validatePropertyForCreate(p.filesetPropertiesMetadata(), properties);+ validatePropertyForCreate(p.filesetPropertiesMetadata(), entityProperties);return null;}),IllegalArgumentException.class);- long uid = idGenerator.nextId();+ secretManager.writeSecrets(secretMaterials);StringIdentifier stringId = StringIdentifier.fromId(uid);+ // Same split as CatalogManager: create/storage properties keep secret URNs. Connectors that+ // need plaintext for runtime (e.g. Fileset FS) resolve at the conf boundary — see+ // FilesetCatalogOperations.mergeUpLevelConfigurations / CatalogManager.createBaseCatalog.Map<String, String> updatedProperties =- StringIdentifier.newPropertiesWithId(stringId, properties);+ StringIdentifier.newPropertiesWithId(stringId, entityProperties);- Fileset createdFileset =- TreeLockUtils.doWithTreeLock(- // Lock at fileset level (not schema level) to allow concurrent fileset creation.- // Trade-off: listFilesets() may temporarily miss in-progress creations until complete.- ident,- LockType.WRITE,- () ->- doWithCatalog(- catalogIdent,- c ->- c.doWithFilesetOps(- f ->- f.createMultipleLocationFileset(- ident, comment, type, storageLocations, updatedProperties)),- NoSuchSchemaException.class,- FilesetAlreadyExistsException.class));- return EntityCombinedFileset.of(createdFileset)- .withHiddenProperties(- getHiddenPropertyNames(- catalogIdent,- HasPropertyMetadata::filesetPropertiesMetadata,- createdFileset.properties()));+ try {+ Fileset createdFileset =+ TreeLockUtils.doWithTreeLock(+ // Lock at fileset level (not schema level) to allow concurrent fileset creation.+ // Trade-off: listFilesets() may temporarily miss in-progress creations until+ // complete.+ ident,+ LockType.WRITE,+ () ->+ doWithCatalog(+ catalogIdent,+ c ->+ c.doWithFilesetOps(+ f ->+ f.createMultipleLocationFileset(+ ident, comment, type, storageLocations, updatedProperties)),+ NoSuchSchemaException.class,+ FilesetAlreadyExistsException.class));+ return EntityCombinedFileset.of(createdFileset)+ .withHiddenProperties(+ getHiddenPropertyNames(+ catalogIdent,+ HasPropertyMetadata::filesetPropertiesMetadata,+ createdFileset.properties()));+ } catch (RuntimeException e) {+ secretManager.rollbackSecrets(secretMaterials);+ throw e;+ }}/**@@ -243,11 +264,31 @@ public class FilesetOperationDispatcher extends OperationDispatcher implements Freturn TreeLockUtils.doWithTreeLock(NameIdentifier.of(ident.namespace().levels()),LockType.WRITE,- () ->- doWithCatalog(- getCatalogIdentifier(ident),- c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),- NonEmptyEntityException.class));+ () -> {+ NameIdentifier catalogIdent = getCatalogIdentifier(ident);+ // Capture properties (including write-through secret URNs) before drop.+ Map<String, String> filesetProperties;+ try {+ Fileset fileset =+ doWithCatalog(+ catalogIdent,+ c -> c.doWithFilesetOps(f -> f.loadFileset(ident)),+ NoSuchFilesetException.class);+ filesetProperties = fileset.properties();+ } catch (NoSuchFilesetException e) {+ return false;+ }++ boolean dropped =+ doWithCatalog(+ catalogIdent,+ c -> c.doWithFilesetOps(f -> f.dropFileset(ident)),+ NonEmptyEntityException.class);+ if (dropped) {+ secretManager.deleteSecretsFromProperties(filesetProperties);+ }+ return dropped;+ });}/**diff --git a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.javaindex 0c66ea2242..029a0a7f32 100644--- a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java+++ b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java@@ -48,6 +48,7 @@ import org.apache.gravitino.credential.S3SecretKeyCredential;import org.apache.gravitino.exceptions.CatalogNotInUseException;import org.apache.gravitino.exceptions.MetalakeNotInUseException;import org.apache.gravitino.meta.CatalogEntity;+import org.apache.gravitino.secret.SecretPropertyUtils;import org.apache.gravitino.storage.AzureProperties;import org.apache.gravitino.storage.GCSProperties;import org.apache.gravitino.storage.OSSProperties;@@ -458,7 +459,11 @@ public abstract class BaseCatalog<T extends BaseCatalog>Map<String, String> tempProperties = Maps.newHashMap(entity.getProperties());tempProperties.entrySet()- .removeIf(entry -> catalogPropertiesMetadata().isHiddenProperty(entry.getKey()));+ .removeIf(+ entry ->+ catalogPropertiesMetadata().isHiddenProperty(entry.getKey())+ || SecretPropertyUtils.isSecretProperty(+ entry.getKey(), entry.getValue()));tempProperties.putIfAbsent(PROPERTY_IN_USE,catalogPropertiesMetadata().getDefaultValue(PROPERTY_IN_USE).toString());diff --git a/core/src/main/java/org/apache/gravitino/hook/FilesetHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/FilesetHookDispatcher.javaindex 22103b6253..037fdec8f7 100644--- a/core/src/main/java/org/apache/gravitino/hook/FilesetHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/FilesetHookDispatcher.java@@ -38,6 +38,8 @@ import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.file.FileInfo;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;@@ -75,11 +77,13 @@ public class FilesetHookDispatcher implements FilesetDispatcher {String comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {Fileset fileset =dispatcher.createMultipleLocationFileset(- ident, comment, type, storageLocations, properties);+ ident, comment, type, storageLocations, properties, secretBindings, secretReferences);// Set the creator as the owner of the fileset.OwnerDispatcher ownerManager = GravitinoEnv.getInstance().ownerDispatcher();diff --git a/core/src/main/java/org/apache/gravitino/listener/FilesetEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/FilesetEventDispatcher.javaindex c0f5fb5d80..c57cf69180 100644--- a/core/src/main/java/org/apache/gravitino/listener/FilesetEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/FilesetEventDispatcher.java@@ -55,6 +55,8 @@ import org.apache.gravitino.listener.api.event.LoadFilesetEvent;import org.apache.gravitino.listener.api.event.LoadFilesetFailureEvent;import org.apache.gravitino.listener.api.event.LoadFilesetPreEvent;import org.apache.gravitino.listener.api.info.FilesetInfo;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretReference;import org.apache.gravitino.utils.PrincipalUtils;/**@@ -135,7 +137,9 @@ public class FilesetEventDispatcher implements FilesetDispatcher {String comment,Fileset.Type type,Map<String, String> storageLocations,- Map<String, String> properties)+ Map<String, String> properties,+ Map<String, SecretBinding> secretBindings,+ Map<String, SecretReference> secretReferences)throws NoSuchSchemaException, FilesetAlreadyExistsException {FilesetInfo createFileRequest =new FilesetInfo(ident.name(), comment, type, storageLocations, properties, null);@@ -144,7 +148,7 @@ public class FilesetEventDispatcher implements FilesetDispatcher {try {Fileset fileset =dispatcher.createMultipleLocationFileset(- ident, comment, type, storageLocations, properties);+ ident, comment, type, storageLocations, properties, secretBindings, secretReferences);eventBus.dispatchEvent(new CreateFilesetEvent(PrincipalUtils.getCurrentUserName(), ident, new FilesetInfo(fileset)));diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretManager.java b/core/src/main/java/org/apache/gravitino/secret/SecretManager.javaindex a404cc8e94..3a989209df 100644--- a/core/src/main/java/org/apache/gravitino/secret/SecretManager.java+++ b/core/src/main/java/org/apache/gravitino/secret/SecretManager.java@@ -28,8 +28,11 @@ import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import java.io.Closeable;import java.util.ArrayList;+import java.util.HashMap;+import java.util.HashSet;import java.util.List;import java.util.Map;+import java.util.Set;import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.Config;@@ -63,20 +66,108 @@ public class SecretManager implements Closeable {return registry;}+ /**+ * Ensures each property key appears at most once across {@code properties}, {@code+ * secretBindings}, and {@code secretReferences}, and that {@code properties} do not contain raw+ * secret URN values.+ *+ * <p>{@code null} maps are treated as empty. Callers must bind/reference secrets via the typed+ * maps rather than embedding {@code urn:gravitino-secret:} values in properties.+ *+ * @param properties entity properties from the create request (may be null)+ * @param secretBindings property key → write-through binding (may be null)+ * @param secretReferences property key → secret locator (may be null)+ */+ public void checkSecretKeys(+ @Nullable Map<String, String> properties,+ @Nullable Map<String, SecretBinding> secretBindings,+ @Nullable Map<String, SecretReference> secretReferences) {+ // Reject raw URNs in request properties: they bypass typed secretBindings/secretReferences+ // and can be used to resolve another entity's secret.+ if (properties != null && !properties.isEmpty()) {+ for (Map.Entry<String, String> entry : properties.entrySet()) {+ String key = entry.getKey();+ String value = entry.getValue();+ if (SecretPropertyUtils.isSecretProperty(key, value)) {+ throw new IllegalArgumentException(+ "Property \""+ + key+ + "\" must not contain a raw gravitino secret URN; use secretBindings or"+ + " secretReferences instead");+ }+ }+ }+ Set<String> keys = new HashSet<>();+ int count = 0;+ if (properties != null) {+ keys.addAll(properties.keySet());+ count += properties.size();+ }+ if (secretBindings != null) {+ keys.addAll(secretBindings.keySet());+ count += secretBindings.size();+ }+ if (secretReferences != null) {+ keys.addAll(secretReferences.keySet());+ count += secretReferences.size();+ }+ if (keys.size() != count) {+ throw new IllegalArgumentException(+ "Duplicate property key across properties, secretBindings and secretReferences");+ }+ }++ /**+ * Checks secret keys and puts reference / write-through URN strings into {@code+ * targetProperties}.+ *+ * <p>Callers typically validate {@code targetProperties}, then call {@link #writeSecrets} with+ * the returned secret materials, and {@link #rollbackSecrets} on failure. {@code properties} is+ * used only for key uniqueness checks (e.g. the original request map); {@code targetProperties}+ * is the mutable map that will be stored (may already contain merged catalog conf).+ *+ * @param properties properties used for key uniqueness checks (may be null)+ * @param targetProperties mutable properties that receive URN values+ * @param entityType {@code catalog}, {@code schema}, or {@code fileset}+ * @param entityId stable numeric entity id+ * @param secretBindings property key → write-through binding (may be null)+ * @param secretReferences property key → secret locator (may be null)+ * @return write-through secret materials for {@link #writeSecrets} / {@link #rollbackSecrets}+ * (empty when there are no bindings)+ */+ public List<SecretMaterial> assembleSecretMaterials(+ @Nullable Map<String, String> properties,+ Map<String, String> targetProperties,+ String entityType,+ long entityId,+ @Nullable Map<String, SecretBinding> secretBindings,+ @Nullable Map<String, SecretReference> secretReferences) {+ checkSecretKeys(properties, secretBindings, secretReferences);+ Map<String, SecretBinding> bindings = secretBindings == null ? Map.of() : secretBindings;+ Map<String, SecretReference> references =+ secretReferences == null ? Map.of() : secretReferences;+ SecretPropertyUtils.putSecretUrns(targetProperties, buildSecretReferenceUrns(references));+ List<SecretUrn> bindingUrns = buildSecretBindingUrns(entityType, entityId, bindings);+ SecretPropertyUtils.putSecretUrns(targetProperties, bindingUrns);+ return toSecretMaterials(bindingUrns, bindings);+ }+/*** Builds external-reference URNs from {@code secretReferences} without writing secret material.** <p>Callers must put the returned URN strings into properties themselves (e.g. via {@link- * SecretPropertyUtils#applySecretUrns}). External-ref URNs are owned outside Gravitino and must- * not be passed to {@link #rollbackWritten}.+ * SecretPropertyUtils#putSecretUrns}). External-ref URNs are owned outside Gravitino and must not+ * be passed to {@link #rollbackSecrets}.*- * @param secretReferences property key → secret locator+ * @param secretReferences property key → secret locator (empty returns an empty list; must not be+ * null)* @return external-reference URNs (insertion order)*/- public List<SecretUrn> getSecretReferenceUrns(Map<String, SecretReference> secretReferences) {- Preconditions.checkArgument(- secretReferences != null && !secretReferences.isEmpty(),- "secretReferences must not be null or empty");+ public List<SecretUrn> buildSecretReferenceUrns(Map<String, SecretReference> secretReferences) {+ Preconditions.checkArgument(secretReferences != null, "secretReferences must not be null");+ if (secretReferences.isEmpty()) {+ return List.of();+ }validateSecretReferences(secretReferences);List<SecretUrn> urns = new ArrayList<>(secretReferences.size());@@ -105,21 +196,23 @@ public class SecretManager implements Closeable {/*** Builds write-through URNs from {@code secretBindings} without writing secret material.*- * <p>Callers should pass the returned URNs to {@link #writeSecrets} to persist plaintext from- * each binding's value, then put URNs into properties (e.g. via {@link- * SecretPropertyUtils#applySecretUrns}).+ * <p>Callers typically pass the returned URNs to {@link #writeSecrets} via {@link+ * #assembleSecretMaterials}, or put URN strings into properties themselves (e.g. via {@link+ * SecretPropertyUtils#putSecretUrns}).** @param entityType {@code catalog}, {@code schema}, or {@code fileset}* @param entityId stable numeric entity id- * @param secretBindings property key → write-through binding+ * @param secretBindings property key → write-through binding (empty returns an empty list; must+ * not be null)* @return write-through URNs (insertion order)*/- public List<SecretUrn> getSecretBindingUrns(+ public List<SecretUrn> buildSecretBindingUrns(String entityType, long entityId, Map<String, SecretBinding> secretBindings) {Preconditions.checkArgument(StringUtils.isNotBlank(entityType), "entityType must not be blank");- Preconditions.checkArgument(- secretBindings != null && !secretBindings.isEmpty(),- "secretBindings must not be null or empty");+ Preconditions.checkArgument(secretBindings != null, "secretBindings must not be null");+ if (secretBindings.isEmpty()) {+ return List.of();+ }validateSecretBindings(secretBindings);List<SecretUrn> urns = new ArrayList<>(secretBindings.size());@@ -141,27 +234,26 @@ public class SecretManager implements Closeable {}/**- * Writes plaintext secrets from {@code secretBindings} values into the write-through providers- * for {@code secretUrns} (e.g. Vault).+ * Writes plaintext secrets into the write-through providers for each {@link SecretMaterial} (e.g.+ * Vault).*- * <p>{@code secretUrns} must come from {@link #getSecretBindingUrns}. On failure, already-written- * URNs are rolled back. Callers must put URN strings into properties themselves (e.g. via {@link- * SecretPropertyUtils#applySecretUrns}).+ * <p>{@code secretMaterials} must come from {@link #assembleSecretMaterials}. On failure,+ * already-written URNs are rolled back. When using {@link #assembleSecretMaterials}, URN strings+ * are already in properties; otherwise callers must put them themselves (e.g. via {@link+ * SecretPropertyUtils#putSecretUrns}).*- * @param secretBindings property key → write-through binding- * @param secretUrns write-through URNs from {@link #getSecretBindingUrns}+ * @param secretMaterials write-through secret materials (empty is a no-op; must not be null)*/- public void writeSecrets(Map<String, SecretBinding> secretBindings, List<SecretUrn> secretUrns) {- Preconditions.checkArgument(- secretBindings != null && !secretBindings.isEmpty(),- "secretBindings must not be null or empty");- Preconditions.checkArgument(- secretUrns != null && !secretUrns.isEmpty(), "secretUrns must not be null or empty");- validateSecretBindings(secretBindings);+ public void writeSecrets(List<SecretMaterial> secretMaterials) {+ Preconditions.checkArgument(secretMaterials != null, "secretMaterials must not be null");+ if (secretMaterials.isEmpty()) {+ return;+ }- List<SecretUrn> written = new ArrayList<>(secretUrns.size());+ List<SecretUrn> written = new ArrayList<>(secretMaterials.size());try {- for (SecretUrn urn : secretUrns) {+ for (SecretMaterial material : secretMaterials) {+ SecretUrn urn = material.urn();List<String> segments = urn.identifierSegments();Preconditions.checkArgument(segments.size() == 3,@@ -169,57 +261,146 @@ public class SecretManager implements Closeable {urn);String entityType = segments.get(0);String entityId = segments.get(1);- String propertyKey = segments.get(2);- SecretBinding binding = secretBindings.get(propertyKey);- Preconditions.checkArgument(- binding != null, "No secretBindings entry for property key \"%s\"", propertyKey);- String plaintext = binding.plaintext();+ String propertyKey = urn.propertyKey();Map<String, String> attributes =ImmutableMap.of(ATTR_ENTITY_TYPE, entityType,ATTR_ENTITY_ID, entityId,ATTR_PROPERTY_KEY, propertyKey);SecretUrn writtenUrn =- registry.getProvider(urn.providerName()).writeSecret(plaintext, attributes);- Preconditions.checkArgument(- urn.equals(writtenUrn),- "Provider returned unexpected URN: expected %s, got %s",- urn,- writtenUrn);+ registry.getProvider(urn.providerName()).writeSecret(material.plaintext(), attributes);+ if (!urn.equals(writtenUrn)) {+ throw new IllegalArgumentException(+ "Provider returned unexpected URN: expected " + urn + ", got " + writtenUrn);+ }written.add(writtenUrn);}} catch (RuntimeException e) {- rollbackWritten(written);+ deleteSecrets(written);throw e;}}/**- * Best-effort delete of write-through secrets after a failed create.+ * Best-effort delete of write-through secret materials after a failed create.*- * <p>Only write-through URNs that were persisted by {@link #writeSecrets} may be passed. Do not- * roll back external reference URNs from {@link #getSecretReferenceUrns}.+ * <p>Only secrets that were persisted by {@link #writeSecrets} may be passed. Do not roll back+ * external reference URNs from {@link #buildSecretReferenceUrns}.*- * @param secretUrns write-through URNs from {@link #getSecretBindingUrns}+ * @param secretMaterials write-through secret materials (must not be null)*/- public void rollbackWritten(@Nullable List<SecretUrn> secretUrns) {- if (secretUrns == null || secretUrns.isEmpty()) {+ public void rollbackSecrets(List<SecretMaterial> secretMaterials) {+ Preconditions.checkArgument(secretMaterials != null, "secretMaterials must not be null");+ if (secretMaterials.isEmpty()) {+ return;+ }+ List<SecretUrn> urns = new ArrayList<>(secretMaterials.size());+ for (SecretMaterial material : secretMaterials) {+ urns.add(material.urn());+ }+ deleteSecrets(urns);+ }++ private void deleteSecrets(List<SecretUrn> secretUrns) {+ if (secretUrns.isEmpty()) {return;}for (SecretUrn urn : secretUrns) {try {registry.getProvider(urn.providerName()).deleteSecret(urn);} catch (Exception e) {- LOG.warn("Failed to roll back written secret {}", urn, e);+ LOG.warn("Failed to delete secret {}", urn, e);}}}+ /**+ * Best-effort delete of write-through secrets whose URN values appear in entity properties.+ *+ * <p>Used when dropping an entity so create-time write-through secrets are not left orphaned+ * (including CatalogHookDispatcher post-hook rollback via {@code dropCatalog}). External+ * reference URNs from {@code secretReferences} are left untouched.+ *+ * @param properties persisted entity properties (may be null)+ */+ public void deleteSecretsFromProperties(@Nullable Map<String, String> properties) {+ if (properties == null || properties.isEmpty()) {+ return;+ }+ List<SecretUrn> writeThrough = new ArrayList<>();+ for (Map.Entry<String, String> entry : properties.entrySet()) {+ if (!SecretPropertyUtils.isSecretProperty(entry.getKey(), entry.getValue())) {+ continue;+ }+ try {+ SecretUrn urn = SecretUrn.parse(entry.getValue());+ // Write-through URNs are entityType:entityId:propertyKey (3 segments).+ if (urn.identifierSegments().size() == 3) {+ writeThrough.add(urn);+ }+ } catch (IllegalArgumentException e) {+ LOG.warn("Skipping invalid secret URN in properties for key {}", entry.getKey(), e);+ }+ }+ deleteSecrets(writeThrough);+ }++ /**+ * Reads plaintext for a secret URN via the provider named in the URN.+ *+ * @param urn the secret URN+ * @return the secret plaintext+ */+ public String readSecret(SecretUrn urn) {+ Preconditions.checkArgument(urn != null, "urn must not be null");+ return registry.getProvider(urn.providerName()).readSecret(urn);+ }++ /**+ * Returns a copy of {@code properties} with secret URN values replaced by plaintext.+ *+ * <p>Used so connectors receive plaintext conf while entity storage keeps URN strings. Non-secret+ * entries are copied unchanged.+ *+ * @param properties entity or request properties (may be null)+ * @return a new map with secret URNs replaced by plaintext; empty map when {@code properties} is+ * null+ */+ public Map<String, String> toPlaintextProperties(@Nullable Map<String, String> properties) {+ if (properties == null || properties.isEmpty()) {+ return properties == null ? Map.of() : Map.copyOf(properties);+ }+ Map<String, String> plaintext = new HashMap<>(properties.size());+ for (Map.Entry<String, String> entry : properties.entrySet()) {+ String key = entry.getKey();+ String value = entry.getValue();+ if (SecretPropertyUtils.isSecretProperty(key, value)) {+ plaintext.put(key, readSecret(SecretUrn.parse(value)));+ } else {+ plaintext.put(key, value);+ }+ }+ return plaintext;+ }+@Overridepublic void close() {registry.close();}+ private static List<SecretMaterial> toSecretMaterials(+ List<SecretUrn> bindingUrns, Map<String, SecretBinding> bindings) {+ List<SecretMaterial> secretMaterials = new ArrayList<>(bindingUrns.size());+ for (SecretUrn urn : bindingUrns) {+ String propertyKey = urn.propertyKey();+ SecretBinding binding = bindings.get(propertyKey);+ Preconditions.checkArgument(+ binding != null, "No secretBindings entry for property key \"%s\"", propertyKey);+ secretMaterials.add(new SecretMaterial(urn, binding.plaintext()));+ }+ return List.copyOf(secretMaterials);+ }+private static void validateUrnEndsWithPropertyKey(SecretUrn urn, String propertyKey) {Preconditions.checkArgument(urn.toString().endsWith(propertyKey),diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.java b/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.javanew file mode 100644index 0000000000..6bfc04499a--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.java@@ -0,0 +1,91 @@+/*+ * 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.secret;++import com.google.common.base.Preconditions;+import java.util.Objects;+import org.apache.gravitino.annotation.Evolving;++/**+ * Write-through secret material: the target {@link SecretUrn} paired with the plaintext to store.+ *+ * <p>Internal to the secrets write path in {@code core}. Produced by {@link+ * SecretManager#assembleSecretMaterials} and consumed by {@link SecretManager#writeSecrets} /+ * {@link SecretManager#rollbackSecrets}.+ */+@Evolving+public final class SecretMaterial {++ private final SecretUrn urn;+ private final String plaintext;++ /**+ * Creates secret material for a write-through secret.+ *+ * @param urn write-through URN (provider + entity locator)+ * @param plaintext plaintext secret to write+ */+ public SecretMaterial(SecretUrn urn, String plaintext) {+ Preconditions.checkArgument(urn != null, "urn must not be null");+ Preconditions.checkArgument(plaintext != null, "plaintext must not be null");+ this.urn = urn;+ this.plaintext = plaintext;+ }++ /**+ * Returns the write-through URN.+ *+ * @return the URN+ */+ public SecretUrn urn() {+ return urn;+ }++ /**+ * Returns the plaintext secret to write.+ *+ * @return the plaintext+ */+ public String plaintext() {+ return plaintext;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof SecretMaterial)) {+ return false;+ }+ SecretMaterial that = (SecretMaterial) o;+ return Objects.equals(urn, that.urn) && Objects.equals(plaintext, that.plaintext);+ }++ @Override+ public int hashCode() {+ return Objects.hash(urn, plaintext);+ }++ @Override+ public String toString() {+ return "SecretMaterial{urn=" + urn + ", plaintext=***}";+ }+}diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.javaindex 334773efb3..b7988cd6dc 100644--- a/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java+++ b/core/src/main/java/org/apache/gravitino/secret/SecretPropertyUtils.java@@ -21,10 +21,9 @@ package org.apache.gravitino.secret;import static org.apache.gravitino.secret.SecretConstants.URN_PREFIX;import com.google.common.base.Preconditions;-import java.util.HashSet;+import java.util.HashMap;import java.util.List;import java.util.Map;-import java.util.Set;import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;@@ -32,7 +31,7 @@ import org.apache.commons.lang3.StringUtils;* Helpers for secret-related entity property handling and request validation.** <p>This is intentionally separate from {@link SecretManager}, which owns secret lifecycle- * (build/write/rollback) rather than property assembly and request-shape checks.+ * (build/write/rollback) and secret-key uniqueness checks rather than property assembly.*/public final class SecretPropertyUtils {@@ -50,39 +49,31 @@ public final class SecretPropertyUtils {}/**- * Rejects property keys that appear in both {@code secretBindings} and {@code secretReferences}.+ * Returns a mutable copy of a property map for create-time assembly.*- * @param secretBindings property key → write-through binding (may be null)- * @param secretReferences property key → secret locator (may be null)+ * <p>{@code null} becomes an empty {@link HashMap}; otherwise returns a new {@link HashMap} copy.+ * Used for request properties and for merged catalog conf (which may be unmodifiable).+ *+ * @param properties property map to copy (may be null)+ * @return a mutable property map, never null*/- public static void checkNoOverlap(- @Nullable Map<String, SecretBinding> secretBindings,- @Nullable Map<String, SecretReference> secretReferences) {- Set<String> bindingKeys = secretBindings == null ? Set.of() : secretBindings.keySet();- Set<String> referenceKeys = secretReferences == null ? Set.of() : secretReferences.keySet();- Set<String> overlap = new HashSet<>(bindingKeys);- overlap.retainAll(referenceKeys);- Preconditions.checkArgument(- overlap.isEmpty(),- "Property keys cannot appear in both secretBindings and secretReferences: %s",- overlap);+ public static Map<String, String> copyEntityProperties(@Nullable Map<String, String> properties) {+ return properties == null ? new HashMap<>() : new HashMap<>(properties);}/**- * Applies each URN string into {@code properties} under the property key encoded in the URN (last- * identifier segment).+ * Puts each URN string into {@code entityProperties} under the property key encoded in the URN+ * (last identifier segment).*- * @param properties mutable entity properties+ * @param entityProperties mutable entity properties* @param secretUrns secret URNs whose last identifier segment is the property key*/- public static void applySecretUrns(Map<String, String> properties, List<SecretUrn> secretUrns) {- Preconditions.checkArgument(properties != null, "properties must not be null");+ public static void putSecretUrns(+ Map<String, String> entityProperties, List<SecretUrn> secretUrns) {+ Preconditions.checkArgument(entityProperties != null, "entityProperties must not be null");Preconditions.checkArgument(secretUrns != null, "secretUrns must not be null");for (SecretUrn urn : secretUrns) {- List<String> segments = urn.identifierSegments();- Preconditions.checkArgument(- !segments.isEmpty(), "Secret URN must contain at least one identifier segment: %s", urn);- properties.put(segments.get(segments.size() - 1), urn.toString());+ entityProperties.put(urn.propertyKey(), urn.toString());}}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.javaindex 3e26888264..b0a17ccd48 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java@@ -25,15 +25,27 @@ import com.google.common.collect.Maps;import java.io.File;import java.io.IOException;import java.util.Map;+import java.util.Properties;import java.util.UUID;+import java.util.concurrent.atomic.AtomicLong;+import org.apache.gravitino.Config;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.audit.CallerContext;import org.apache.gravitino.audit.FilesetAuditConstants;import org.apache.gravitino.audit.FilesetDataOperation;+import org.apache.gravitino.exceptions.FilesetAlreadyExistsException;import org.apache.gravitino.exceptions.GravitinoRuntimeException;import org.apache.gravitino.file.Fileset;import org.apache.gravitino.file.FilesetChange;+import org.apache.gravitino.secret.SecretBinding;+import org.apache.gravitino.secret.SecretConstants;+import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.secret.SecretPropertyUtils;+import org.apache.gravitino.secret.SecretProviderRegistry;+import org.apache.gravitino.secret.SecretUrn;+import org.apache.gravitino.secret.memory.InMemorySecretsProvider;+import org.apache.gravitino.storage.IdGenerator;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;@@ -312,4 +324,66 @@ public class TestFilesetOperationDispatcher extends TestOperationDispatcher {}}}++ @Test+ public void testCreateWithSecrets() throws Exception {+ try (SecretManager secrets = memorySecretManager()) {+ AtomicLong nextId = new AtomicLong(9000L);+ IdGenerator ids = nextId::getAndIncrement;+ FilesetOperationDispatcher filesets =+ new FilesetOperationDispatcher(catalogManager, entityStore, ids, secrets);+ new SchemaOperationDispatcher(catalogManager, entityStore, ids, secrets)+ .createSchema(+ NameIdentifier.of(metalake, catalog, "schema_secret_fileset"),+ "comment",+ ImmutableMap.of("k1", "v1"));++ NameIdentifier ident =+ NameIdentifier.of(metalake, catalog, "schema_secret_fileset", "fileset_secret_1");+ Map<String, SecretBinding> bindings = Map.of("k2", new SecretBinding("memory", "s3cr3t"));+ Map<String, String> locations = Map.of(Fileset.LOCATION_NAME_UNKNOWN, "loc");+ Map<String, String> props = ImmutableMap.of("k1", "v1");+ long entityId = nextId.get();+ Fileset fileset =+ filesets.createMultipleLocationFileset(+ ident, "comment", Fileset.Type.MANAGED, locations, props, bindings, Map.of());+ Assertions.assertFalse(fileset.properties().containsKey("k2"));++ Fileset stored =+ catalogManager+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))+ .doWithFilesetOps(ops -> ops.loadFileset(ident));+ Assertions.assertTrue(+ SecretPropertyUtils.isSecretProperty("k2", stored.properties().get("k2")));++ SecretUrn urn =+ SecretUrn.buildWriteThrough(+ "memory",+ Map.of(+ SecretConstants.ATTR_ENTITY_TYPE, "fileset",+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entityId),+ SecretConstants.ATTR_PROPERTY_KEY, "k2"));+ Assertions.assertEquals("s3cr3t", secrets.readSecret(urn));+ Assertions.assertThrows(+ FilesetAlreadyExistsException.class,+ () ->+ filesets.createMultipleLocationFileset(+ ident, "comment", Fileset.Type.MANAGED, locations, props, bindings, Map.of()));+ Assertions.assertTrue(filesets.dropFileset(ident));+ Assertions.assertThrows(IllegalArgumentException.class, () -> secrets.readSecret(urn));+ }+ }++ private static SecretManager memorySecretManager() {+ Config c = new Config(false) {};+ Properties p = new Properties();+ p.setProperty(SecretProviderRegistry.GRAVITINO_SECRET_PROVIDERS, "memory");+ p.setProperty(+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX+ + "memory."+ + SecretProviderRegistry.CLASS_NAME,+ InMemorySecretsProvider.class.getName());+ c.loadFromProperties(p);+ return new SecretManager(c);+ }}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.javaindex da5675094e..06a43a0e8e 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestModelOperationDispatcher.java@@ -74,7 +74,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testRegisterAndGetModel() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -105,7 +105,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testRegisterAndListModels() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName1 = randomModelName();@@ -129,7 +129,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testRegisterAndDeleteModel() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -151,7 +151,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndGetModelVersion() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -202,7 +202,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndListModelVersion() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -230,7 +230,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndListModelVersionInfos() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -257,7 +257,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndDeleteModelVersion() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -294,7 +294,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndGetModelVersionUriWithoutDefaultUriName() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -363,7 +363,7 @@ public class TestModelOperationDispatcher extends TestOperationDispatcher {public void testLinkAndGetModelVersionUriWithDefaultUriName() {String schemaName = randomSchemaName();NameIdentifier schemaIdent = NameIdentifier.of(metalake, catalog, schemaName);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));// set default uri name to "n1" at model levelMap<String, String> modelProps =diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.javaindex bf3d116240..25a9ea6ebb 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestPartitionOperationDispatcher.java@@ -24,6 +24,7 @@ import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.mock;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.Maps;import java.util.Arrays;import org.apache.commons.lang3.reflect.FieldUtils;@@ -93,7 +94,7 @@ public class TestPartitionOperationDispatcher extends TestOperationDispatcher {GravitinoEnv.getInstance(), "schemaDispatcher", schemaOperationDispatcher, true);NameIdentifier schemaIdent = NameIdentifierUtil.ofSchema(metalake, catalog, SCHEMA);- schemaOperationDispatcher.createSchema(schemaIdent, "comment", null);+ schemaOperationDispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1"));Column[] columns =new Column[] {Column.of("col1", Types.StringType.get()), Column.of("col2", Types.StringType.get())diff --git a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.javaindex 943444019e..fe0447fa75 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java@@ -119,7 +119,8 @@ public class TestFilesetHookDispatcher extends TestOperationDispatcher {OwnerDispatcher mockOwnerDispatcher = Mockito.mock(OwnerDispatcher.class);FilesetDispatcher mockFilesetDispatcher = Mockito.mock(FilesetDispatcher.class);Mockito.when(- mockFilesetDispatcher.createMultipleLocationFileset(any(), any(), any(), any(), any()))+ mockFilesetDispatcher.createMultipleLocationFileset(+ any(), any(), any(), any(), any(), any(), any())).thenReturn(Mockito.mock(Fileset.class));FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogManager", mockCatalogManager, true);diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestFilesetEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestFilesetEvent.javaindex db200d91f9..ebc368b275 100644--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestFilesetEvent.java+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestFilesetEvent.java@@ -21,6 +21,7 @@ package org.apache.gravitino.listener.api.event;import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.ArgumentMatchers.nullable;import static org.mockito.Mockito.any;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -391,8 +392,10 @@ public class TestFilesetEvent {any(NameIdentifier.class),any(String.class),any(Fileset.Type.class),- any(Map.class),- any(Map.class)))+ nullable(Map.class),+ nullable(Map.class),+ nullable(Map.class),+ nullable(Map.class))).thenReturn(fileset);when(dispatcher.loadFileset(any(NameIdentifier.class))).thenReturn(fileset);when(dispatcher.dropFileset(any(NameIdentifier.class))).thenReturn(true);diff --git a/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java b/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.javaindex ef6c2b08a6..ccc1f54d0d 100644--- a/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java@@ -29,72 +29,108 @@ import org.junit.jupiter.api.Test;public class TestSecretManager {+ private static final Map<String, SecretBinding> BINDINGS =+ Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));+ private static final Map<String, SecretReference> REFERENCES =+ Map.of("jdbc-password", new SecretReference("memory", Map.of("path", "secret/data/x")));+@Testvoid testWriteSecrets() {- try (SecretManager secretManager = memorySecretManager()) {- Map<String, String> properties = new HashMap<>(Map.of("jdbc-user", "root"));- Map<String, SecretBinding> secretBindings =- Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));- List<SecretUrn> secretUrns =- secretManager.getSecretBindingUrns("catalog", 42L, secretBindings);- secretManager.writeSecrets(secretBindings, secretUrns);- SecretPropertyUtils.applySecretUrns(properties, secretUrns);-- String urn = properties.get("jdbc-password");+ try (SecretManager sm = memorySecretManager()) {+ Map<String, String> props = new HashMap<>(Map.of("jdbc-user", "root"));+ List<SecretUrn> urns = sm.buildSecretBindingUrns("catalog", 42L, BINDINGS);+ sm.writeSecrets(List.of(new SecretMaterial(urns.get(0), "s3cr3t")));+ SecretPropertyUtils.putSecretUrns(props, urns);++ String urn = props.get("jdbc-password");Assertions.assertTrue(SecretPropertyUtils.isSecretProperty("jdbc-password", urn));- Assertions.assertEquals("root", properties.get("jdbc-user"));- Assertions.assertEquals(1, secretUrns.size());+ Assertions.assertEquals("root", props.get("jdbc-user"));+ Assertions.assertEquals(1, urns.size());Assertions.assertEquals(- "s3cr3t",- secretManager.getRegistry().getProvider("memory").readSecret(secretUrns.get(0)));+ "s3cr3t", sm.getRegistry().getProvider("memory").readSecret(urns.get(0)));+ Assertions.assertEquals("s3cr3t", sm.readSecret(urns.get(0)));}}@Test- void testGetSecretReferenceUrnsRejectedByMemoryProvider() {- try (SecretManager secretManager = memorySecretManager()) {- Assertions.assertThrows(- IllegalArgumentException.class,- () ->- secretManager.getSecretReferenceUrns(- Map.of(- "jdbc-password",- new SecretReference("memory", Map.of("path", "secret/data/x")))));+ void testToPlaintextProperties() {+ try (SecretManager sm = memorySecretManager()) {+ Assertions.assertTrue(sm.toPlaintextProperties(null).isEmpty());+ Assertions.assertTrue(sm.toPlaintextProperties(Map.of()).isEmpty());++ Map<String, String> props = new HashMap<>(Map.of("jdbc-user", "root"));+ List<SecretUrn> urns = sm.buildSecretBindingUrns("catalog", 42L, BINDINGS);+ SecretPropertyUtils.putSecretUrns(props, urns);+ sm.writeSecrets(List.of(new SecretMaterial(urns.get(0), "s3cr3t")));++ String urn = props.get("jdbc-password");+ Map<String, String> plaintext = sm.toPlaintextProperties(props);+ Assertions.assertEquals("root", plaintext.get("jdbc-user"));+ Assertions.assertEquals("s3cr3t", plaintext.get("jdbc-password"));+ Assertions.assertEquals(urn, props.get("jdbc-password"));}}@Test- void testRejectOverlapAndInvalidBinding() {- try (SecretManager secretManager = memorySecretManager()) {+ void testRejectReferenceUrns() {+ try (SecretManager sm = memorySecretManager()) {Assertions.assertThrows(- IllegalArgumentException.class,- () ->- SecretPropertyUtils.checkNoOverlap(- Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t")),- Map.of(- "jdbc-password",- new SecretReference("memory", Map.of("path", "secret/data/x")))));+ IllegalArgumentException.class, () -> sm.buildSecretReferenceUrns(REFERENCES));+ }+ }+ @Test+ void testCheckSecretKeys() {+ try (SecretManager sm = memorySecretManager()) {Assertions.assertThrows(- IllegalArgumentException.class, () -> new SecretBinding(" ", "s3cr3t"));+ IllegalArgumentException.class, () -> sm.checkSecretKeys(Map.of(), BINDINGS, REFERENCES));+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> sm.checkSecretKeys(Map.of("jdbc-password", "plain"), BINDINGS, Map.of()));+ List<SecretUrn> urns = sm.buildSecretBindingUrns("catalog", 42L, BINDINGS);Assertions.assertThrows(IllegalArgumentException.class,() ->- secretManager.getSecretReferenceUrns(- Map.of(- "jdbc-password",- new SecretReference("memory", Map.of("path", "secret/data/x")))));+ sm.checkSecretKeys(+ Map.of("jdbc-password", urns.get(0).toString()), Map.of(), Map.of()));++ Assertions.assertThrows(+ IllegalArgumentException.class, () -> new SecretBinding(" ", "s3cr3t"));}}@Test- void testSecretBindingToStringRedactsPlaintext() {+ void testBindingRedacts() {SecretBinding binding = new SecretBinding("memory", "s3cr3t");Assertions.assertFalse(binding.toString().contains("s3cr3t"));Assertions.assertTrue(binding.toString().contains("***"));}+ @Test+ void testSecretMaterialRedacts() {+ try (SecretManager sm = memorySecretManager()) {+ List<SecretUrn> urns = sm.buildSecretBindingUrns("catalog", 42L, BINDINGS);+ SecretMaterial material = new SecretMaterial(urns.get(0), "s3cr3t");+ Assertions.assertEquals(urns.get(0), material.urn());+ Assertions.assertEquals("s3cr3t", material.plaintext());+ Assertions.assertFalse(material.toString().contains("s3cr3t"));+ Assertions.assertTrue(material.toString().contains("***"));+ }+ }++ @Test+ void testDeleteBindingsFromProperties() {+ try (SecretManager sm = memorySecretManager()) {+ List<SecretUrn> urns = sm.buildSecretBindingUrns("catalog", 99L, BINDINGS);+ sm.writeSecrets(List.of(new SecretMaterial(urns.get(0), "s3cr3t")));+ Map<String, String> props = new HashMap<>();+ SecretPropertyUtils.putSecretUrns(props, urns);+ sm.deleteSecretsFromProperties(props);+ Assertions.assertThrows(IllegalArgumentException.class, () -> sm.readSecret(urns.get(0)));+ }+ }+private static SecretManager memorySecretManager() {Config config = new Config(false) {};Properties properties = new Properties();diff --git a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.javanew file mode 100644index 0000000000..89fd5d065b--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java@@ -0,0 +1,85 @@+/*+ * 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.secret;++import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Properties;+import org.apache.gravitino.Config;+import org.apache.gravitino.secret.memory.InMemorySecretsProvider;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestSecretPropertyUtils {++ @Test+ void testAssembleAndWrite() {+ try (SecretManager sm = memorySecretManager()) {+ Map<String, String> properties = Map.of("jdbc-user", "root");+ Map<String, SecretBinding> bindings =+ Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));+ Map<String, String> entityProps = SecretPropertyUtils.copyEntityProperties(properties);+ List<SecretMaterial> writes =+ sm.assembleSecretMaterials(properties, entityProps, "catalog", 42L, bindings, Map.of());+ sm.writeSecrets(writes);++ Assertions.assertEquals("root", entityProps.get("jdbc-user"));+ Assertions.assertTrue(+ SecretPropertyUtils.isSecretProperty("jdbc-password", entityProps.get("jdbc-password")));+ Assertions.assertEquals(1, writes.size());+ Assertions.assertEquals("s3cr3t", sm.readSecret(writes.get(0).urn()));+ }+ }++ @Test+ void testCopyEntityProperties() {+ Assertions.assertTrue(SecretPropertyUtils.copyEntityProperties(null).isEmpty());+ Map<String, String> original = Map.of("a", "b");+ Map<String, String> copy = SecretPropertyUtils.copyEntityProperties(original);+ Assertions.assertEquals(original, copy);+ copy.put("c", "d");+ Assertions.assertFalse(original.containsKey("c"));+ }++ @Test+ void testEmptySecretsNoOp() {+ try (SecretManager sm = memorySecretManager()) {+ Map<String, String> entityProps = new HashMap<>(Map.of("jdbc-user", "root"));+ List<SecretMaterial> writes =+ sm.assembleSecretMaterials(entityProps, entityProps, "schema", 1L, Map.of(), Map.of());+ sm.writeSecrets(writes);+ Assertions.assertTrue(writes.isEmpty());+ Assertions.assertEquals("root", entityProps.get("jdbc-user"));+ }+ }++ private static SecretManager memorySecretManager() {+ Config config = new Config(false) {};+ Properties properties = new Properties();+ properties.setProperty(SecretProviderRegistry.GRAVITINO_SECRET_PROVIDERS, "memory");+ properties.setProperty(+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX+ + "memory."+ + SecretProviderRegistry.CLASS_NAME,+ InMemorySecretsProvider.class.getName());+ config.loadFromProperties(properties);+ return new SecretManager(config);+ }+}diff --git a/design-docs/gravitino-entity-secrets.md b/design-docs/gravitino-entity-secrets.mdindex e9003122dd..f854ce8085 100644--- a/design-docs/gravitino-entity-secrets.md+++ b/design-docs/gravitino-entity-secrets.md@@ -64,13 +64,13 @@ instead of plaintext for marked keys, expose a clear **REST create/alter contrac3. **REST + persistence split**: HTTP **`properties`** stays **`map<string, string>`**; optional**`secretReferences`** (key → locator object; server **builds** the URN) and/or- **`secretBindings`** (key → provider name for write-through) mark secrets on **create**; **alter**- adds `@type`s **`setSecretBinding`** / **`setSecretReference`** (§5.9.4) for **catalog, schema, and- fileset** (see §5.9). **Persistence** stays an all-string JSON map on each entity's properties- column. Secret property values are stored as **URN strings**. A property is treated as a secret- when its value matches the **URN recognition rule** (§5.1): starts with `urn:gravitino-secret`- and ends with that property's key. Whether to `deleteSecret` on entity drop or alter- `removeProperty` is decided from the **URN shape** (write-through embeds+ **`secretBindings`** (key → `{ provider, plaintext }` for write-through) mark secrets on+ **create**; **alter** adds `@type`s **`setSecretBinding`** / **`setSecretReference`** (§5.9.4)+ for **catalog, schema, and fileset** (see §5.9). **Persistence** stays an all-string JSON map on+ each entity's properties column. Secret property values are stored as **URN strings**. A property+ is treated as a secret when its value matches the **URN recognition rule** (§5.1): starts with+ `urn:gravitino-secret` and ends with that property's key. Whether to `deleteSecret` on entity drop+ or alter `removeProperty` is decided from the **URN shape** (write-through embeds`entityType`/`entityId`/`propertyKey` — §5.5.2 C).4. **Backward compatible reads**: existing all-string entity properties continue to@@ -152,11 +152,11 @@ Both peers share one idea we keep: **secret material lives outside catalog metad| Layer | Shape | Role || ----------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------- |-| **REST** `properties` | `map<string, string>` | Unchanged from today — create HTTP values are strings |-| **REST** `secretReferences` | `map<string, object>` | Optional on **create** — **property key → locator** (external ref; server builds URN — §5.9.2) |-| **REST** alter secret `@type`s | in `updates` | **`setSecretBinding`** / **`setSecretReference`** (§5.9.4) — same `{ "updates": [...] }` body; `setProperty` unchanged |-| **REST** `secretBindings` | `map<string, string>` | Optional on **create** — **property key → provider name** (write-through; plaintext in `properties`) |-| **Persistence** entity `properties` | JSON **string map** | `catalog_meta` / `schema_meta` / `fileset_version_info` — secret keys store URN strings (§5.1 recognition rule) |+| **REST** `properties` | `map<string, string>` | Unchanged from today — non-secret create HTTP values are strings |+| **REST** `secretReferences` | `map<string, object>` | Optional on **create** — **property key → locator** (external ref; server builds URN — §5.9.2) |+| **REST** alter secret `@type`s | in `updates` | **`setSecretBinding`** / **`setSecretReference`** (§5.9.4) — same `{ "updates": [...] }` body; `setProperty` unchanged |+| **REST** `secretBindings` | `map<string, object>` | Optional on **create** — **property key → `{ provider, plaintext }`** (write-through; plaintext **not** in `properties`) |+| **Persistence** entity `properties` | JSON **string map** | `catalog_meta` / `schema_meta` / `fileset_version_info` — secret keys store URN strings (§5.1 recognition rule) |**Secret recognition rule** (server-side; no reserved metadata key):@@ -410,8 +410,8 @@ Create request shapes: §5.9.2 / §5.9.5. Below is the provider / URN outcome on**A. Write-through (in-memory)**-Client create uses `secretBindings` (`jdbc-password` → `memory`) plus plaintext in-`properties`. Core calls `writeSecret(plaintext, SecretWriteContext("catalog", entityId,+Client create uses typed `secretBindings` (`jdbc-password` → `{ "provider": "memory",+"plaintext": "…" }`). Core calls `writeSecret(plaintext, SecretWriteContext("catalog", entityId,"jdbc-password"))`, persists e.g.:```text@@ -511,9 +511,9 @@ do not diverge.| Layer | Today | v1 || -------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------ |-| REST `properties` | `map<string, string>` | **Unchanged** (create) |-| REST `secretReferences` | — | **New optional** on **create** (property key → **locator object**; server builds URN) |-| REST `secretBindings` | — | **New optional** on **create** (property key → provider name) |+| REST `properties` | `map<string, string>` | **Unchanged** (create; non-secret keys only when using secret maps) |+| REST `secretReferences` | — | **New optional** on **create** (property key → **locator object**; server builds URN) |+| REST `secretBindings` | — | **New optional** on **create** (property key → **`{ provider, plaintext }`**) || REST alter `updates` | existing `@type`s | **Add** `setSecretBinding` / `setSecretReference` (§5.9.4); `setProperty` stays plaintext string || REST list providers | — | **New** `GET /configs/secrets/providers` — static config discovery (§5.9.6) || Persistence | string map per entity | Same; secret values = **URN strings** (recognized by URN shape; drop delete via URN shape) |@@ -557,8 +557,16 @@ rules as catalog list.#### 5.9.2 Create (request)-**`properties`** and **`secretBindings`** are `map<string, string>`.-**`secretReferences`** is `map<string, object>` (same for catalog, schema, and fileset create bodies).+**`properties`** is `map<string, string>`.+**`secretBindings`** and **`secretReferences`** are `map<string, object>` (same for catalog,+schema, and fileset create bodies).++**Binding object** (each `secretBindings` value — shared shape with alter `setSecretBinding`):++| Field | Required | Meaning |+| ----------- | -------- | ---------------------------------------------------------- |+| `provider` | Yes | Registered `provider_name` |+| `plaintext` | Yes | Plaintext secret to write through (must not be `******`) |**Locator object** (each `secretReferences` value — shared by create and by alter`setSecretReference`):@@ -566,7 +574,7 @@ rules as catalog list.| Field | Required | Meaning || ------------ | -------- | ------------------------------------------------------------------------------------------------------------ || `provider` | Yes | Registered `provider_name` |-| `attributes` | No | Provider-specific locator keys (`map<string, string>`). Empty / omitted ⇒ empty map. Never a raw URN string. |+| `attributes` | Yes | Provider-specific locator keys (`map<string, string>`); must be non-null and non-empty. Never a raw URN string. |**`attributes`** are provider-specific. The REST schema stays the same for every provider; each`GravitinoSecretProvider` documents required keys. **`InMemorySecretsProvider` does not use@@ -585,16 +593,15 @@ urn:gravitino-secret:<provider>:<type-specific-identifier>| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- || Key **not** in either secret map | Persist `properties` value as plain **string** (legacy / non-secret). || Key in **`secretReferences`** | Validate locator; **build URN** (must end with the property key); persist **URN string**; key **must not** be in `properties`; **do not** `readSecret` on write. |-| Key in **`secretBindings`** | `properties[key]` required; plaintext (not `******`) → `writeSecret` via named provider; persist **returned URN string**. |+| Key in **`secretBindings`** | Validate binding; `plaintext` (not `******`) → `writeSecret` via named provider; persist **returned URN string**; key **must not** be in `properties`. || Key in **both** `secretReferences` and `secretBindings` | **Reject**. |-| Key in `secretReferences` **and** also present in `properties` | **Reject**. |-| Key in `secretBindings`, value in `properties` is `******` | **Reject** (no existing value to preserve). |-| Key in `secretBindings` but missing from `properties` | **Reject**. |+| Key in `secretReferences` **or** `secretBindings` **and** also present in `properties` | **Reject** (no overlap with `properties`). |+| `secretBindings` missing `provider` / `plaintext`, or `plaintext` is `******` | **Reject**. || `secretBindings` / locator `provider` not in `gravitino.secret.providers` | **Reject**. || Locator `attributes` value is a raw `urn:gravitino-secret:...` string | **Reject** — use locator attributes, not a client-built URN. || Client sends a raw `urn:gravitino-secret:...` string as `secretReferences` value | **Reject** in v1 — use the locator object (server builds the URN). |-**Write-through example** (`secretBindings` + plaintext in `properties`):+**Write-through example** (typed `secretBindings`; plaintext **not** in `properties`):```json{@@ -602,13 +609,15 @@ urn:gravitino-secret:<provider>:<type-specific-identifier>"type": "relational","provider": "jdbc-mysql","secretBindings": {- "jdbc-password": "memory"+ "jdbc-password": {+ "provider": "memory",+ "plaintext": "S3cret!Passw0rd"+ }},"properties": {"jdbc-url": "jdbc:mysql://staging.example.com:3306/app","jdbc-driver": "com.mysql.cj.jdbc.Driver",- "jdbc-user": "app",- "jdbc-password": "S3cret!Passw0rd"+ "jdbc-user": "app"}}```@@ -650,12 +659,12 @@ sibling maps). Existing **`setProperty`** stays a **string** `value` (plaintext| `@type` | Fields (flat; not nested under `value`) | Behavior || -------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- || `setProperty` | `value` (**string** plaintext) | Today’s plaintext set. If the **current** value matches the URN recognition rule, in-place `writeSecret` via provider in the current URN; persist new URN |-| `setSecretBinding` | `provider` (instance name) + `value` (plaintext string) | Write-through bind/re-bind (`writeSecret`); persist returned URN |+| `setSecretBinding` | `provider` (instance name) + `plaintext` (plaintext string) | Write-through bind/re-bind (`writeSecret`); persist returned URN || `setSecretReference` | `provider` (instance name) + `attributes` (`map<string,string>`; same locator as §5.9.2) | External ref; server builds URN from locator (must end with the property key). Required `attributes` keys are provider-defined. || Rule | Behavior || ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `setSecretBinding` missing `provider` / string `value`, or `value` is `******` | **Reject** |+| `setSecretBinding` missing `provider` / string `plaintext`, or `plaintext` is `******` | **Reject** || `setSecretReference` missing `provider` | **Reject** || `setSecretReference` `attributes` value is a raw `urn:gravitino-secret:...` string | **Reject** — use locator attributes, not a client-built URN || `setSecretReference` missing attributes required by the selected provider | **Reject** |@@ -691,13 +700,15 @@ Request:"provider": "jdbc-mysql","comment": "Staging MySQL catalog","secretBindings": {- "jdbc-password": "memory"+ "jdbc-password": {+ "provider": "memory",+ "plaintext": "S3cret!Passw0rd"+ }},"properties": {"jdbc-url": "jdbc:mysql://staging.example.com:3306/app","jdbc-driver": "com.mysql.cj.jdbc.Driver",- "jdbc-user": "app",- "jdbc-password": "S3cret!Passw0rd"+ "jdbc-user": "app"}}```@@ -749,7 +760,7 @@ DB `properties` (plaintext):**TC-3 — Alter: write-through via `setSecretBinding` (200)**-Request (flat `provider` + plaintext `value`):+Request (flat `provider` + `plaintext`):```json{@@ -758,7 +769,7 @@ Request (flat `provider` + plaintext `value`):"@type": "setSecretBinding","property": "jdbc-password","provider": "memory",- "value": "S3cret!Passw0rd"+ "plaintext": "S3cret!Passw0rd"}]}diff --git a/docs/open-api/filesets.yaml b/docs/open-api/filesets.yamlindex 956b9bad63..6ef16f304a 100644--- a/docs/open-api/filesets.yaml+++ b/docs/open-api/filesets.yaml@@ -346,6 +346,22 @@ components:default: {}additionalProperties:type: string+ secretBindings:+ type: object+ description: >+ Optional map of property key to write-through binding. Persisted value+ becomes a URN.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretBinding"+ secretReferences:+ type: object+ description: >+ Optional map of property key to secret locator. Server builds and+ persists the URN. Must not overlap with secretBindings.+ nullable: true+ additionalProperties:+ $ref: "./secrets.yaml#/components/schemas/SecretReference"FilesetUpdatesRequest:type: objectdiff --git a/docs/open-api/secrets.yaml b/docs/open-api/secrets.yamlnew file mode 100644index 0000000000..cfcf9db149--- /dev/null+++ b/docs/open-api/secrets.yaml@@ -0,0 +1,57 @@+# 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.++---+components:+ schemas:+ SecretBinding:+ type: object+ description: >+ Write-through secret binding. Provider is a registered secrets-provider+ instance name; plaintext is the secret to store. The persisted property+ value becomes a URN.+ required:+ - provider+ - plaintext+ properties:+ provider:+ type: string+ description: Registered secrets-provider instance name+ plaintext:+ type: string+ description: Plaintext secret to write through+ format: password++ SecretReference:+ type: object+ description: >+ External secret locator. Provider is a registered secrets-provider+ instance name; attributes are provider-specific. The server builds and+ persists the URN. Clients must not send a raw gravitino secret URN.+ required:+ - provider+ - attributes+ properties:+ provider:+ type: string+ description: Registered secrets-provider instance name+ attributes:+ type: object+ description: Provider-specific locator keys (must be non-empty)+ additionalProperties:+ type: string+ minProperties: 1diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.javaindex eda03954fd..0802f852a5 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/FilesetOperations.java@@ -55,6 +55,8 @@ import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.FileInfoListResponse;import org.apache.gravitino.dto.responses.FileLocationResponse;import org.apache.gravitino.dto.responses.FilesetResponse;+import org.apache.gravitino.dto.secret.SecretBindingDTO;+import org.apache.gravitino.dto.secret.SecretReferenceDTO;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.file.FileInfo;import org.apache.gravitino.file.Fileset;@@ -173,7 +175,9 @@ public class FilesetOperations {request.getComment(),Optional.ofNullable(request.getType()).orElse(Fileset.Type.MANAGED),storageLocations,- request.getProperties());+ request.getProperties(),+ SecretBindingDTO.toSecretBindings(request.getSecretBindings()),+ SecretReferenceDTO.toSecretReferences(request.getSecretReferences()));Response response = Utils.ok(new FilesetResponse(DTOConverters.toDTO(fileset)));LOG.info("Fileset created: {}.{}.{}.{}", metalake, catalog, schema, request.getName());return response;diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestFilesetOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestFilesetOperations.javaindex 8bfb5bd6a5..ca77641129 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestFilesetOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestFilesetOperations.java@@ -252,7 +252,7 @@ public class TestFilesetOperations extends BaseOperationsTest {"mock comment","mock location",ImmutableMap.of("k1", "v1"));- when(dispatcher.createMultipleLocationFileset(any(), any(), any(), any(), any()))+ when(dispatcher.createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any())).thenReturn(fileset);FilesetCreateRequest req =@@ -299,7 +299,7 @@ public class TestFilesetOperations extends BaseOperationsTest {"mock comment",locations,ImmutableMap.of("k1", "v1"));- when(dispatcher.createMultipleLocationFileset(any(), any(), any(), any(), any()))+ when(dispatcher.createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any())).thenReturn(fileset);req =@@ -331,7 +331,7 @@ public class TestFilesetOperations extends BaseOperationsTest {// Test throw NoSuchSchemaExceptiondoThrow(new NoSuchSchemaException("mock error")).when(dispatcher)- .createMultipleLocationFileset(any(), any(), any(), any(), any());+ .createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any());Response resp1 =target(filesetPath(metalake, catalog, schema))@@ -348,7 +348,7 @@ public class TestFilesetOperations extends BaseOperationsTest {// Test throw FilesetAlreadyExistsExceptiondoThrow(new FilesetAlreadyExistsException("mock error")).when(dispatcher)- .createMultipleLocationFileset(any(), any(), any(), any(), any());+ .createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any());Response resp2 =target(filesetPath(metalake, catalog, schema))@@ -366,7 +366,7 @@ public class TestFilesetOperations extends BaseOperationsTest {// Test throw RuntimeExceptiondoThrow(new RuntimeException("mock error")).when(dispatcher)- .createMultipleLocationFileset(any(), any(), any(), any(), any());+ .createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any());Response resp3 =target(filesetPath(metalake, catalog, schema))@@ -384,7 +384,7 @@ public class TestFilesetOperations extends BaseOperationsTest {// Test throw ErrordoThrow(new Error("mock error")).when(dispatcher)- .createMultipleLocationFileset(any(), any(), any(), any(), any());+ .createMultipleLocationFileset(any(), any(), any(), any(), any(), any(), any());Response resp4 =target(filesetPath(metalake, catalog, schema)).request(MediaType.APPLICATION_JSON_TYPE)