This is an automated email from the ASF dual-hosted git repository.
roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new 5a6af76639 [#14970] improvement(secret): Use stageSecrets for entity
create (#14983)
5a6af76639 is described below
commit 5a6af766390d2c0a41a8832ef53f4a71fad97246
Author: YangJie <[email protected]>
AuthorDate: Wed Nov 18 01:23:50 2026 -0500
[#14970] improvement(secret): Use stageSecrets for entity create (#14983)
### What changes were proposed in this pull request?
Catalog, schema and fileset create now use the secret lifecycle of
alter, as #14970 proposes.
- `assembleSecretMaterials` is renamed to `assembleSecretPlaintexts` and
returns property key → plaintext.
- Create passes those plaintexts to `stageSecrets`, now public, with no
start properties. The new URNs have no current version, so each first
version is current once written and `commitSecrets` switches nothing.
- `commitSecrets` runs only after the create succeeds, as in alter. A
failed create calls `rollbackSecrets(SecretVersionChanges)`, which
deletes the written versions, unless the catalog already created the
schema or fileset, or a stored catalog cannot be removed.
- `writeSecrets(List)`, `rollbackSecrets(List)` and `SecretMaterial` are
removed, and `SecretMaterialsHolder` is renamed to
`SecretVersionChangesHolder`.
- `SecretProvider` signatures and `deleteSecretsFromProperties` are
unchanged; the `writeSecretVersion` Javadoc now says create uses the
version methods.
- Design doc §5.5.3 covers create; the `setProperty` and
`setSecretBinding` alter rows, stale since #14954, now describe
versions.
### Why are the changes needed?
`SecretManager` had one lifecycle for create and another for alter, and
`SecretMaterial` existed only for create. Callers now follow one: stage,
commit once the create succeeds, and roll back on failure unless
something that may reference the secrets is left behind.
Fix: #14970
### Does this PR introduce _any_ user-facing change?
- A write-through provider that does not implement the version methods
now fails at create with `UnsupportedOperationException`, instead of at
the first alter of that secret. The SPI is not released yet.
- If a catalog create fails after the catalog was stored and the catalog
cannot be removed, the error now says so and asks to drop it with force.
### How was this patch tested?
- `TestSecretManager`: staging and committing a create, rolling back a
failed create, and a later binding on a provider without versions
failing the stage, which deletes the version written before it.
- `TestSchemaOperationDispatcher.testSecrets`,
`TestFilesetOperationDispatcher.testCreateWithSecrets`: a create that
fails before the entity exists deletes its version.
-
`TestFilesetOperationDispatcher.testCreateKeepsSecretsOnceFilesetIsCreated`:
a failure after the catalog created the fileset, inside or after the
catalog call, keeps its secret.
-
`TestCatalogManager.testFailureAfterCatalogIsStoredKeepsSecretsUntilEntityIsRemoved`:
a failure after `store.put` deletes the secret only if the catalog
entity is removed, and otherwise reports the leftover catalog.
---------
Co-authored-by: roryqi <[email protected]>
---
.../catalog/fileset/FilesetCatalogOperations.java | 10 +-
.../fileset/TestFilesetCatalogOperations.java | 23 ++-
.../apache/gravitino/secret/SecretProvider.java | 4 +-
.../apache/gravitino/catalog/CatalogManager.java | 66 +++---
.../catalog/FilesetOperationDispatcher.java | 55 ++---
.../catalog/SchemaOperationDispatcher.java | 222 +++++++++++----------
.../org/apache/gravitino/secret/SecretManager.java | 141 ++++---------
.../apache/gravitino/secret/SecretMaterial.java | 91 ---------
.../gravitino/secret/SecretVersionChanges.java | 13 +-
...Holder.java => SecretVersionChangesHolder.java} | 9 +-
.../gravitino/catalog/TestCatalogManager.java | 73 ++++++-
.../catalog/TestFilesetOperationDispatcher.java | 87 ++++++++
.../catalog/TestSchemaOperationDispatcher.java | 16 +-
.../TestBaseCatalogCredentialSecrets.java | 6 +-
.../apache/gravitino/secret/TestSecretManager.java | 92 ++++++---
.../gravitino/secret/TestSecretPropertyUtils.java | 36 ++--
design-docs/gravitino-entity-secrets.md | 50 +++--
.../connector/store/TestGravitinoCatalogStore.java | 7 +-
.../provider/TestDynamicIcebergConfigProvider.java | 13 +-
.../connector/catalog/TestBaseCatalogSecrets.java | 8 +-
20 files changed, 560 insertions(+), 462 deletions(-)
diff --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.java
index 843d980a49..b6739ca450 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
@@ -121,8 +121,8 @@ import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.FilesetCatalogMetricsSource;
import org.apache.gravitino.secret.SecretAlterChanges;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterialsHolder;
import org.apache.gravitino.secret.SecretVersionChanges;
+import org.apache.gravitino.secret.SecretVersionChangesHolder;
import org.apache.gravitino.utils.ExceptionMessages;
import org.apache.gravitino.utils.FilesetUtil;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -746,7 +746,7 @@ public class FilesetCatalogOperations extends
ManagedSchemaOperations
throw ExceptionMessages.wrap("Failed to load fileset " + ident, ioe);
}
- SecretMaterialsHolder writtenSecretMaterials = new SecretMaterialsHolder();
+ SecretVersionChangesHolder stagedSecrets = new
SecretVersionChangesHolder();
boolean alterCommitted = false;
try {
FilesetEntity updatedFilesetEntity =
@@ -762,11 +762,11 @@ public class FilesetCatalogOperations extends
ManagedSchemaOperations
Pair<FilesetChange[], SecretVersionChanges> secretResult =
SecretAlterChanges.prepareFilesetChanges(
secretManager, currentProperties, existing.id(),
changes);
- writtenSecretMaterials.set(secretResult.getRight());
+ stagedSecrets.set(secretResult.getRight());
return updateFilesetEntity(ident, existing,
secretResult.getLeft());
});
alterCommitted = true;
- secretManager.commitSecrets(writtenSecretMaterials.get());
+ secretManager.commitSecrets(stagedSecrets.get());
return FilesetImpl.builder()
.withName(updatedFilesetEntity.name())
.withComment(updatedFilesetEntity.comment())
@@ -790,7 +790,7 @@ public class FilesetCatalogOperations extends
ManagedSchemaOperations
e, "Fileset %s already exists", NameIdentifier.of(ident.namespace(),
newName));
} finally {
if (!alterCommitted) {
- secretManager.rollbackSecrets(writtenSecretMaterials.get());
+ secretManager.rollbackSecrets(stagedSecrets.get());
}
}
}
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.java
index 160e8df732..7a3c904d04 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
@@ -151,7 +151,6 @@ import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.secret.SecretBinding;
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;
@@ -899,7 +898,7 @@ public class TestFilesetCatalogOperations {
Path schemaPath = new Path(catalogPath, schemaName);
long schemaId = generateTestId();
SecretUrn urn = writeThroughUrn("schema", schemaId, "schema-sk");
- secretManager.writeSecrets(List.of(new SecretMaterial(urn,
"schema-secret")));
+ seedSecret(urn, "schema-secret");
FileSystem realFileSystem = schemaPath.getFileSystem(new Configuration());
FileSystem failingFileSystem = Mockito.mock(FileSystem.class);
@@ -1063,7 +1062,7 @@ public class TestFilesetCatalogOperations {
SecretConstants.ATTR_ENTITY_TYPE, "fileset",
SecretConstants.ATTR_ENTITY_ID,
String.valueOf(generateTestId()),
SecretConstants.ATTR_PROPERTY_KEY, "test-secret"));
- secretManager.writeSecrets(List.of(new SecretMaterial(urn,
"test-value")));
+ seedSecret(urn, "test-value");
secrets.add(urn);
createFileset(
name,
@@ -1147,7 +1146,7 @@ public class TestFilesetCatalogOperations {
NameIdentifier schemaIdent = NameIdentifier.of("m1", "c1", schemaName);
NameIdentifier filesetIdent = NameIdentifier.of("m1", "c1", schemaName,
"fileset");
SecretUrn urn = writeThroughUrn("fileset", generateTestId(),
"test-secret");
- secretManager.writeSecrets(List.of(new SecretMaterial(urn, "test-value")));
+ seedSecret(urn, "test-value");
Map<String, String> catalogProperties = ImmutableMap.of(LOCATION,
catalogPath);
Fileset fileset =
createMultiLocationFileset(
@@ -1244,7 +1243,7 @@ public class TestFilesetCatalogOperations {
SecretConstants.ATTR_ENTITY_TYPE, "fileset",
SecretConstants.ATTR_ENTITY_ID, String.valueOf(remainingId),
SecretConstants.ATTR_PROPERTY_KEY, "test-secret"));
- secretManager.writeSecrets(List.of(new SecretMaterial(urn, "test-value")));
+ seedSecret(urn, "test-value");
Map<String, String> remainingProperties =
StringIdentifier.newPropertiesWithId(
StringIdentifier.fromId(remainingId), Map.of("test-secret",
urn.toString()));
@@ -1311,7 +1310,7 @@ public class TestFilesetCatalogOperations {
SecretConstants.ATTR_ENTITY_TYPE, "fileset",
SecretConstants.ATTR_ENTITY_ID,
String.valueOf(generateTestId()),
SecretConstants.ATTR_PROPERTY_KEY, "test-secret"));
- secretManager.writeSecrets(List.of(new SecretMaterial(urn, "test-value")));
+ seedSecret(urn, "test-value");
Fileset fileset =
createFileset(
filesetIdent.name(),
@@ -5548,7 +5547,7 @@ public class TestFilesetCatalogOperations {
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")));
+ seedSecret(urn, "super-secret");
String schemaName = "schema_secret_" + generateTestId();
String schemaPath = TEST_ROOT_PATH + "/" + schemaName;
@@ -5580,10 +5579,8 @@ public class TestFilesetCatalogOperations {
long filesetId = idGenerator.nextId();
SecretUrn schemaUrn = writeThroughUrn("schema", schemaId, "schema-sk");
SecretUrn filesetUrn = writeThroughUrn("fileset", filesetId, "fileset-sk");
- secretManager.writeSecrets(
- List.of(
- new SecretMaterial(schemaUrn, "schema-secret"),
- new SecretMaterial(filesetUrn, "fileset-secret")));
+ seedSecret(schemaUrn, "schema-secret");
+ seedSecret(filesetUrn, "fileset-secret");
String schemaName = "schema_cascade_" + generateTestId();
String catalogPath = TEST_ROOT_PATH + "/catalog_cascade_" +
generateTestId();
@@ -5689,6 +5686,10 @@ public class TestFilesetCatalogOperations {
Arguments.of(new IOException("Cannot initialize filesystem"), "probe
failed"));
}
+ private static void seedSecret(SecretUrn urn, String plaintext) {
+
secretManager.getRegistry().getProvider(urn.providerName()).writeSecretVersion(urn,
plaintext);
+ }
+
private static SecretUrn writeThroughUrn(String entityType, long entityId,
String key) {
return SecretUrn.buildWriteThrough(
"memory",
diff --git
a/common/src/main/java/org/apache/gravitino/secret/SecretProvider.java
b/common/src/main/java/org/apache/gravitino/secret/SecretProvider.java
index c54bb57015..861762db33 100644
--- a/common/src/main/java/org/apache/gravitino/secret/SecretProvider.java
+++ b/common/src/main/java/org/apache/gravitino/secret/SecretProvider.java
@@ -85,8 +85,8 @@ public interface SecretProvider {
* keep the value the entity still references.
*
* <p>Providers that support write-through must implement this method and
the other version
- * methods; altering a write-through secret uses them. Providers that only
build external
- * references can keep the defaults, which throw.
+ * methods; creating or altering a write-through secret uses them. Providers
that only build
+ * external references can keep the defaults, which throw.
*
* <p>Version ids are non-blank and are not reused for the same URN until
{@link #deleteSecret}
* removes it, because Gravitino deletes replaced versions by id. Gravitino
passes to the other
diff --git
a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
index c15569600d..772c0160a7 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/CatalogManager.java
@@ -119,11 +119,10 @@ import org.apache.gravitino.rel.ViewCatalog;
import org.apache.gravitino.secret.SecretAlterChanges;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterial;
-import org.apache.gravitino.secret.SecretMaterialsHolder;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretReference;
import org.apache.gravitino.secret.SecretVersionChanges;
+import org.apache.gravitino.secret.SecretVersionChangesHolder;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.relational.SupportsEntityChangeLog;
import org.apache.gravitino.utils.ClassLoaderKey;
@@ -853,8 +852,8 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
buildCatalogConf(provider, properties), secretBindings,
secretReferences);
long uid = idGenerator.nextId();
- List<SecretMaterial> secretMaterials =
- secretManager.assembleSecretMaterials(
+ Map<String, String> secretPlaintexts =
+ secretManager.assembleSecretPlaintexts(
properties, mergedConfig, "catalog", uid, secretBindings,
secretReferences);
StringIdentifier stringId = StringIdentifier.fromId(uid);
@@ -889,8 +888,10 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
checkOpen();
checkMetalake(metalakeIdent, store);
// Initialization resolves secret URNs, but must not publish the
entity yet.
- secretManager.writeSecrets(secretMaterials);
+ SecretVersionChanges stagedSecrets =
+ secretManager.stageSecrets(null, mergedConfig, "catalog", uid,
secretPlaintexts);
AtomicBoolean entityStored = new AtomicBoolean(false);
+ Catalog info;
try {
// Reject known duplicates before contacting the backend;
store.put still arbitrates
// concurrent creates from other server instances.
@@ -904,7 +905,7 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
wrapper.tryAcquire(), "A new catalog wrapper cannot be
retired");
try (CatalogLease lease = new CatalogLease(wrapper)) {
// Snapshot construction can also fail; finish it before
making the row visible.
- Catalog info = toCatalogInfo(lease.wrapper());
+ info = toCatalogInfo(lease.wrapper());
// Initializing outside compute keeps slow backend
verification out of cache
// locks. Serialize the short store/cache publication with
acquireCatalogLease
// so a listCatalogsInfo reader cannot build a second
wrapper in between them.
@@ -928,7 +929,6 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
return wrapper;
});
published = true;
- return info;
}
} finally {
if (!published) {
@@ -936,13 +936,15 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
}
}
} catch (RuntimeException re) {
- rollbackFailedCatalogCreate(ident, secretMaterials,
entityStored.get());
+ rollbackFailedCatalogCreate(ident, stagedSecrets,
entityStored.get(), re);
throw re;
} catch (Exception ex) {
- rollbackFailedCatalogCreate(ident, secretMaterials,
entityStored.get());
+ rollbackFailedCatalogCreate(ident, stagedSecrets,
entityStored.get(), ex);
LOG.error("Failed to create catalog {}", ident, ex);
throw new RuntimeException(ex);
}
+ secretManager.commitSecrets(stagedSecrets);
+ return info;
} finally {
lifecycleLock.readLock().unlock();
}
@@ -1327,7 +1329,7 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
private CatalogEntity alterCatalogUnderLock(NameIdentifier ident,
CatalogChange... changes)
throws NoSuchCatalogException, IllegalArgumentException, IOException {
- SecretMaterialsHolder writtenSecretMaterials = new SecretMaterialsHolder();
+ SecretVersionChangesHolder stagedSecrets = new
SecretVersionChangesHolder();
boolean alterCommitted = false;
try (CatalogLease lease = acquireCatalogLease(ident)) {
CatalogEntity updatedCatalog =
@@ -1367,7 +1369,7 @@ public class CatalogManager implements CatalogDispatcher,
Closeable {
Pair<CatalogChange[], SecretVersionChanges> secretResult =
SecretAlterChanges.prepareCatalogChanges(
secretManager, currentProperties, existing.id(),
changes);
- writtenSecretMaterials.set(secretResult.getRight());
+ stagedSecrets.set(secretResult.getRight());
return updateEntity(
newCatalogBuilder(ident.namespace(), existing),
new HashMap<>(currentProperties),
@@ -1375,13 +1377,13 @@ public class CatalogManager implements
CatalogDispatcher, Closeable {
.build();
});
alterCommitted = true;
- secretManager.commitSecrets(writtenSecretMaterials.get());
+ secretManager.commitSecrets(stagedSecrets.get());
return updatedCatalog;
} catch (NoSuchEntityException e) {
throw new NoSuchCatalogException(CATALOG_DOES_NOT_EXIST_MSG, ident);
} finally {
if (!alterCommitted) {
- secretManager.rollbackSecrets(writtenSecretMaterials.get());
+ secretManager.rollbackSecrets(stagedSecrets.get());
}
}
}
@@ -2352,20 +2354,34 @@ public class CatalogManager implements
CatalogDispatcher, Closeable {
}
/**
- * Rolls back secrets written for a catalog create attempt and, when {@code
store.put} succeeded,
- * removes the catalog entity left behind by a failed publication.
+ * Cleans up a failed catalog create by rolling back its staged secrets.
When {@code store.put}
+ * succeeded, the stored catalog entity is removed first; if it cannot be
removed, its secrets are
+ * kept because it still references them.
+ *
+ * @throws GravitinoRuntimeException if the stored catalog entity cannot be
removed, with {@code
+ * failure} as the cause and the delete failure suppressed
*/
private void rollbackFailedCatalogCreate(
- NameIdentifier ident, List<SecretMaterial> secretMaterials, boolean
entityStored) {
- secretManager.rollbackSecrets(secretMaterials);
- if (!entityStored) {
- return;
- }
- catalogCache.invalidate(ident);
- try {
- store.delete(ident, EntityType.CATALOG, true);
- } catch (IOException e) {
- LOG.error("Failed to clean up catalog {}", ident, e);
+ NameIdentifier ident,
+ SecretVersionChanges stagedSecrets,
+ boolean entityStored,
+ Exception failure) {
+ if (entityStored) {
+ catalogCache.invalidate(ident);
+ try {
+ store.delete(ident, EntityType.CATALOG, true);
+ } catch (IOException | RuntimeException e) {
+ LOG.error("Failed to clean up catalog {}; keeping the secrets it
references", ident, e);
+ GravitinoRuntimeException leftover =
+ new GravitinoRuntimeException(
+ failure,
+ "Failed to create catalog %s, and failed to remove the catalog
entity it stored;"
+ + " drop the catalog with force before creating it again",
+ ident);
+ leftover.addSuppressed(e);
+ throw leftover;
+ }
}
+ secretManager.rollbackSecrets(stagedSecrets);
}
}
diff --git
a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java
b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java
index 5e46cd4815..25190deb85 100644
---
a/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java
+++
b/core/src/main/java/org/apache/gravitino/catalog/FilesetOperationDispatcher.java
@@ -24,9 +24,9 @@ import static
org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier
import java.util.Arrays;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
@@ -48,11 +48,10 @@ import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.secret.SecretAlterChanges;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterial;
-import org.apache.gravitino.secret.SecretMaterialsHolder;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretReference;
import org.apache.gravitino.secret.SecretVersionChanges;
+import org.apache.gravitino.secret.SecretVersionChangesHolder;
import org.apache.gravitino.storage.IdGenerator;
public class FilesetOperationDispatcher extends OperationDispatcher implements
FilesetDispatcher {
@@ -181,8 +180,8 @@ public class FilesetOperationDispatcher extends
OperationDispatcher implements F
long uid = idGenerator.nextId();
Map<String, String> entityProperties =
SecretPropertyUtils.copyEntityProperties(properties, secretBindings,
secretReferences);
- List<SecretMaterial> secretMaterials =
- secretManager.assembleSecretMaterials(
+ Map<String, String> secretPlaintexts =
+ secretManager.assembleSecretPlaintexts(
properties, entityProperties, "fileset", uid, secretBindings,
secretReferences);
doWithCatalog(
catalogIdent,
@@ -201,11 +200,14 @@ public class FilesetOperationDispatcher extends
OperationDispatcher implements F
StringIdentifier.newPropertiesWithId(stringId, entityProperties);
// Write secrets before create: paths that resolve URNs (e.g.
mergeUpLevelConfigurations for FS
- // mkdir, catalog createBaseCatalog) require secrets to exist first. Roll
back on any create
- // failure (same pattern as CatalogManager / SchemaOperationDispatcher).
- secretManager.writeSecrets(secretMaterials);
+ // mkdir, catalog createBaseCatalog) require secrets to exist first. Roll
back only if the
+ // catalog create fails; once it returns, the fileset references these
secrets.
+ SecretVersionChanges stagedSecrets =
+ secretManager.stageSecrets(null, entityProperties, "fileset", uid,
secretPlaintexts);
+ AtomicBoolean createdInCatalog = new AtomicBoolean();
+ Fileset createdFileset;
try {
- Fileset createdFileset =
+ 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
@@ -217,21 +219,28 @@ public class FilesetOperationDispatcher extends
OperationDispatcher implements F
catalogIdent,
c ->
c.doWithFilesetOps(
- f ->
- f.createMultipleLocationFileset(
- ident, comment, type, storageLocations,
updatedProperties)),
+ f -> {
+ Fileset created =
+ f.createMultipleLocationFileset(
+ ident, comment, type,
storageLocations, updatedProperties);
+ createdInCatalog.set(true);
+ return created;
+ }),
NoSuchSchemaException.class,
FilesetAlreadyExistsException.class));
- return EntityCombinedFileset.of(createdFileset)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent,
- HasPropertyMetadata::filesetPropertiesMetadata,
- createdFileset.properties()));
} catch (RuntimeException e) {
- secretManager.rollbackSecrets(secretMaterials);
+ if (!createdInCatalog.get()) {
+ secretManager.rollbackSecrets(stagedSecrets);
+ }
throw e;
}
+ secretManager.commitSecrets(stagedSecrets);
+ return EntityCombinedFileset.of(createdFileset)
+ .withHiddenProperties(
+ getMaskAndOmitKeys(
+ catalogIdent,
+ HasPropertyMetadata::filesetPropertiesMetadata,
+ createdFileset.properties()));
}
/**
@@ -323,13 +332,13 @@ public class FilesetOperationDispatcher extends
OperationDispatcher implements F
filesetId = null;
}
- SecretMaterialsHolder writtenSecretMaterials = new SecretMaterialsHolder();
+ SecretVersionChangesHolder stagedSecrets = new
SecretVersionChangesHolder();
boolean alterCommitted = false;
try {
Pair<FilesetChange[], SecretVersionChanges> secretResult =
SecretAlterChanges.prepareFilesetChanges(
secretManager, currentProperties, filesetId, changes);
- writtenSecretMaterials.set(secretResult.getRight());
+ stagedSecrets.set(secretResult.getRight());
FilesetChange[] effectiveChanges = secretResult.getLeft();
Fileset altered =
@@ -339,11 +348,11 @@ public class FilesetOperationDispatcher extends
OperationDispatcher implements F
NoSuchFilesetException.class,
IllegalArgumentException.class);
alterCommitted = true;
- secretManager.commitSecrets(writtenSecretMaterials.get());
+ secretManager.commitSecrets(stagedSecrets.get());
return altered;
} finally {
if (!alterCommitted) {
- secretManager.rollbackSecrets(writtenSecretMaterials.get());
+ secretManager.rollbackSecrets(stagedSecrets.get());
}
}
}
diff --git
a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
index dd2dc37d88..5325f6dab9 100644
---
a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
+++
b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
@@ -61,12 +61,11 @@ import org.apache.gravitino.secret.SecretAlterChanges;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretConstants;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterial;
-import org.apache.gravitino.secret.SecretMaterialsHolder;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretReference;
import org.apache.gravitino.secret.SecretUrn;
import org.apache.gravitino.secret.SecretVersionChanges;
+import org.apache.gravitino.secret.SecretVersionChangesHolder;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.gravitino.utils.SchemaEntityCleaner;
@@ -173,8 +172,8 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
long uid = idGenerator.nextId();
Map<String, String> entityProperties =
SecretPropertyUtils.copyEntityProperties(properties, secretBindings,
secretReferences);
- List<SecretMaterial> secretMaterials =
- secretManager.assembleSecretMaterials(
+ Map<String, String> secretPlaintexts =
+ secretManager.assembleSecretPlaintexts(
properties, entityProperties, "schema", uid, secretBindings,
secretReferences);
doWithCatalog(
catalogIdent,
@@ -198,111 +197,120 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
// Write secrets before createSchema: create paths that resolve URNs (e.g.
Fileset FS
// mergeUpLevelConfigurations, catalog createBaseCatalog) require secrets
to exist first.
- // Roll back secrets only if external creation has not succeeded. Once the
source schema
- // exists, it may reference these secrets even if registration fails.
- secretManager.writeSecrets(secretMaterials);
+ // Roll back secrets only if the catalog has not created the schema; once
it has, the schema may
+ // reference them even if a later step fails.
+ SecretVersionChanges stagedSecrets =
+ secretManager.stageSecrets(null, entityProperties, "schema", uid,
secretPlaintexts);
AtomicBoolean createdInCatalog = new AtomicBoolean();
+ Schema createdSchema;
try {
- return TreeLockUtils.doWithTreeLock(
- catalogIdent,
- LockType.WRITE,
- () -> {
- boolean isManagedSchema = isManagedEntity(catalogIdent,
Capability.Scope.SCHEMA);
- if (!isManagedSchema) {
- // Check before source creation so a renamed schema can still be
imported under its
- // new name. Never interpret a store failure as permission to
replace its identity.
- try {
- if (store.exists(ident, SCHEMA)) {
+ createdSchema =
+ TreeLockUtils.doWithTreeLock(
+ catalogIdent,
+ LockType.WRITE,
+ () -> {
+ boolean isManagedSchema = isManagedEntity(catalogIdent,
Capability.Scope.SCHEMA);
+ if (!isManagedSchema) {
+ // Check before source creation so a renamed schema can
still be imported under
+ // its new name. Never interpret a store failure as
permission to replace its
+ // identity.
+ try {
+ if (store.exists(ident, SCHEMA)) {
+ throw new SchemaAlreadyExistsException(
+ "Schema %s is already registered in Gravitino. If it
was renamed externally, "
+ + "loadSchema under its new name before creating
this name. Otherwise, "
+ + "verify the old source identity is gone before
removing its registration.",
+ ident);
+ }
+ } catch (IOException e) {
+ throw new GravitinoRuntimeException(
+ e,
+ "Cannot verify the registration of schema %s. Resolve
the entity-store error "
+ + "before retrying; source creation has not been
attempted.",
+ ident);
+ }
+ }
+ // we do not retrieve the schema again (to obtain some values
generated by
+ // underlying catalog) since some catalogs' API is async and
the schema may not
+ // be created immediately
+ Schema schema =
+ doWithCatalog(
+ catalogIdent,
+ c ->
+ c.doWithSchemaOps(
+ s -> {
+ Schema created =
+ s.createSchema(ident, comment,
updatedProperties);
+ createdInCatalog.set(true);
+ return created;
+ }),
+ NoSuchCatalogException.class,
+ SchemaAlreadyExistsException.class);
+
+ // If the Schema is maintained by the Gravitino's store, we
don't have to store
+ // again.
+ if (isManagedSchema) {
+ return EntityCombinedSchema.of(schema)
+ .withHiddenProperties(
+ getMaskAndOmitKeys(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ }
+
+ // Persist properties (including secret URNs) in the entity
store so cleanup still
+ // works when the underlying catalog does not retain schema
properties.
+ SchemaEntity schemaEntity =
+ SchemaEntity.builder()
+ .withId(uid)
+ .withName(ident.name())
+ .withNamespace(ident.namespace())
+ .withProperties(updatedProperties)
+ .withAuditInfo(
+ AuditInfo.builder()
+
.withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
+
+ try {
+ store.put(schemaEntity, true /* overwrite */);
+ } catch (EntityAlreadyExistsException e) {
throw new SchemaAlreadyExistsException(
- "Schema %s is already registered in Gravitino. If it was
renamed externally, "
- + "loadSchema under its new name before creating
this name. Otherwise, "
- + "verify the old source identity is gone before
removing its registration.",
+ e,
+ "Schema %s was created in the external catalog, but its
registration conflicts "
+ + "with an existing entity. Verify and reconcile the
registered and source "
+ + "identities before continuing; loading the schema
does not resolve this conflict.",
+ ident);
+ } catch (Exception e) {
+ LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put",
ident, e);
+ throw new GravitinoRuntimeException(
+ e,
+ "Schema %s was created in the external catalog, but its
registration in Gravitino "
+ + "failed. Resolve the entity-store error, verify
the source identity, and use "
+ + "loadSchema to import it. Do not repeat
createSchema; it will report already exists.",
ident);
}
- } catch (IOException e) {
- throw new GravitinoRuntimeException(
- e,
- "Cannot verify the registration of schema %s. Resolve the
entity-store error "
- + "before retrying; source creation has not been
attempted.",
- ident);
- }
- }
- // we do not retrieve the schema again (to obtain some values
generated by underlying
- // catalog)
- // since some catalogs' API is async and the schema may not be
created immediately
- Schema schema =
- doWithCatalog(
- catalogIdent,
- c ->
- c.doWithSchemaOps(
- s -> {
- Schema created = s.createSchema(ident, comment,
updatedProperties);
- createdInCatalog.set(true);
- return created;
- }),
- NoSuchCatalogException.class,
- SchemaAlreadyExistsException.class);
-
- // If the Schema is maintained by the Gravitino's store, we don't
have to store again.
- if (isManagedSchema) {
- return EntityCombinedSchema.of(schema)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- }
-
- // Persist properties (including secret URNs) in the entity store
so cleanup still works
- // when the underlying catalog does not retain schema properties.
- SchemaEntity schemaEntity =
- SchemaEntity.builder()
- .withId(uid)
- .withName(ident.name())
- .withNamespace(ident.namespace())
- .withProperties(updatedProperties)
- .withAuditInfo(
- AuditInfo.builder()
-
.withCreator(PrincipalUtils.getCurrentPrincipal().getName())
- .withCreateTime(Instant.now())
- .build())
- .build();
-
- try {
- store.put(schemaEntity, true /* overwrite */);
- } catch (EntityAlreadyExistsException e) {
- throw new SchemaAlreadyExistsException(
- e,
- "Schema %s was created in the external catalog, but its
registration conflicts "
- + "with an existing entity. Verify and reconcile the
registered and source "
- + "identities before continuing; loading the schema does
not resolve this conflict.",
- ident);
- } catch (Exception e) {
- LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident,
e);
- throw new GravitinoRuntimeException(
- e,
- "Schema %s was created in the external catalog, but its
registration in Gravitino "
- + "failed. Resolve the entity-store error, verify the
source identity, and use "
- + "loadSchema to import it. Do not repeat createSchema;
it will report already exists.",
- ident);
- }
- // Merge both the metadata from catalog operation and the metadata
from entity store.
- return EntityCombinedSchema.of(schema, schemaEntity)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
- });
+ // Merge both the metadata from catalog operation and the
metadata from entity
+ // store.
+ return EntityCombinedSchema.of(schema, schemaEntity)
+ .withHiddenProperties(
+ getMaskAndOmitKeys(
+ catalogIdent,
+ HasPropertyMetadata::schemaPropertiesMetadata,
+ schema.properties()));
+ });
} catch (RuntimeException e) {
- // An externally created schema may already reference these URNs. Keep
its credentials
- // available for reconciliation when only the entity-store registration
failed.
+ // Once the catalog created the schema, the schema may reference these
URNs, so keep its
+ // secrets even if a later step, such as the entity-store registration,
fails.
if (!createdInCatalog.get()) {
- secretManager.rollbackSecrets(secretMaterials);
+ secretManager.rollbackSecrets(stagedSecrets);
}
throw e;
}
+ secretManager.commitSecrets(stagedSecrets);
+ return createdSchema;
}
/**
@@ -456,7 +464,7 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
NameIdentifier ident, SchemaChange... changes) throws
NoSuchSchemaException {
validateAlterProperties(ident,
HasPropertyMetadata::schemaPropertiesMetadata, changes);
- SecretMaterialsHolder writtenSecretMaterials = new SecretMaterialsHolder();
+ SecretVersionChangesHolder stagedSecrets = new
SecretVersionChangesHolder();
SchemaChange[][] effectiveChangesHolder = new SchemaChange[1][];
boolean alterCommitted = false;
try {
@@ -473,12 +481,12 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
Pair<SchemaChange[], SecretVersionChanges> secretResult =
SecretAlterChanges.prepareSchemaChanges(
secretManager, currentProperties, existing.id(),
changes);
- writtenSecretMaterials.set(secretResult.getRight());
+ stagedSecrets.set(secretResult.getRight());
effectiveChangesHolder[0] = secretResult.getLeft();
return SchemaEntityChanges.apply(ident, existing,
secretResult.getLeft());
});
alterCommitted = true;
- secretManager.commitSecrets(writtenSecretMaterials.get());
+ secretManager.commitSecrets(stagedSecrets.get());
Schema alteredSchema =
ManagedSchemaOperations.ManagedSchema.builder()
.withName(ident.name())
@@ -493,7 +501,7 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
throw new RuntimeException("Failed to alter schema " + ident, e);
} finally {
if (!alterCommitted) {
- secretManager.rollbackSecrets(writtenSecretMaterials.get());
+ secretManager.rollbackSecrets(stagedSecrets.get());
}
}
}
@@ -545,13 +553,13 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
throw missingSchema;
}
- SecretMaterialsHolder writtenSecretMaterials = new SecretMaterialsHolder();
+ SecretVersionChangesHolder stagedSecrets = new
SecretVersionChangesHolder();
boolean alterCommitted = false;
try {
Pair<SchemaChange[], SecretVersionChanges> secretResult =
SecretAlterChanges.prepareSchemaChanges(
secretManager, currentProperties, entityIdForSecrets, changes);
- writtenSecretMaterials.set(secretResult.getRight());
+ stagedSecrets.set(secretResult.getRight());
SchemaChange[] effectiveChanges = secretResult.getLeft();
Schema alteredSchema =
@@ -562,13 +570,13 @@ public class SchemaOperationDispatcher extends
OperationDispatcher implements Sc
alterCommitted = true;
if (schemaEntityForSecrets == null) {
// No SchemaEntity references the released secrets.
- secretManager.commitSecrets(writtenSecretMaterials.get());
+ secretManager.commitSecrets(stagedSecrets.get());
return Triple.of(alteredSchema, effectiveChanges,
SecretVersionChanges.EMPTY);
}
- return Triple.of(alteredSchema, effectiveChanges,
writtenSecretMaterials.get());
+ return Triple.of(alteredSchema, effectiveChanges, stagedSecrets.get());
} finally {
if (!alterCommitted) {
- secretManager.rollbackSecrets(writtenSecretMaterials.get());
+ secretManager.rollbackSecrets(stagedSecrets.get());
}
}
}
diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretManager.java
b/core/src/main/java/org/apache/gravitino/secret/SecretManager.java
index 22fdfbe69c..15140de45d 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,10 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.io.Closeable;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -43,7 +45,8 @@ import org.slf4j.LoggerFactory;
/**
* SecretManager owns write-through / external-reference secret lifecycle
against configured
- * providers, and rolls back write-through secrets when entity create fails.
+ * providers. For an entity create or alter, it stages the write-through
secret versions for the
+ * caller to commit or roll back.
*/
public class SecretManager implements Closeable {
@@ -123,10 +126,11 @@ public class SecretManager implements Closeable {
* 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).
+ * <p>Callers typically validate {@code targetProperties}, then pass the
returned plaintexts to
+ * {@link #stageSecrets}, and call {@link #commitSecrets} after the entity
is created or {@link
+ * #rollbackSecrets(SecretVersionChanges)} 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 (may
be null only when both
@@ -135,10 +139,10 @@ public class SecretManager implements Closeable {
* @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}
+ * @return property key → plaintext of each write-through binding, for
{@link #stageSecrets}
* (empty when there are no bindings)
*/
- public List<SecretMaterial> assembleSecretMaterials(
+ public Map<String, String> assembleSecretPlaintexts(
@Nullable Map<String, String> properties,
@Nullable Map<String, String> targetProperties,
String entityType,
@@ -147,7 +151,7 @@ public class SecretManager implements Closeable {
@Nullable Map<String, SecretReference> secretReferences) {
checkSecretKeys(properties, secretBindings, secretReferences);
if (!SecretPropertyUtils.hasSecretMaps(secretBindings, secretReferences)) {
- return List.of();
+ return Map.of();
}
Preconditions.checkArgument(
targetProperties != null, "targetProperties must not be null when
secrets are present");
@@ -157,15 +161,14 @@ public class SecretManager implements Closeable {
SecretPropertyUtils.putSecretUrns(targetProperties,
buildSecretReferenceUrns(references));
List<SecretUrn> bindingUrns = buildSecretBindingUrns(entityType, entityId,
bindings);
SecretPropertyUtils.putSecretUrns(targetProperties, bindingUrns);
- return toSecretMaterials(bindingUrns, bindings);
+ return toPlaintexts(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#putSecretUrns}). External-ref URNs are owned outside
Gravitino and must not
- * be passed to {@link #rollbackSecrets}.
+ * SecretPropertyUtils#putSecretUrns}).
*
* @param secretReferences property key → secret locator (empty returns an
empty list; must not be
* null)
@@ -230,8 +233,8 @@ public class SecretManager implements Closeable {
/**
* Builds write-through URNs from {@code secretBindings} without writing
secret material.
*
- * <p>Callers typically pass the returned URNs to {@link #writeSecrets} via
{@link
- * #assembleSecretMaterials}, or put URN strings into properties themselves
(e.g. via {@link
+ * <p>Callers typically use {@link #assembleSecretPlaintexts}, which puts
these URNs into the
+ * properties, or put URN strings into properties themselves (e.g. via {@link
* SecretPropertyUtils#putSecretUrns}).
*
* @param entityType {@code catalog}, {@code schema}, or {@code fileset}
@@ -257,83 +260,16 @@ public class SecretManager implements Closeable {
}
/**
- * Writes plaintext secrets into the write-through providers for each {@link
SecretMaterial} (e.g.
- * Vault).
- *
- * <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 secretMaterials write-through secret materials (empty is a no-op;
must not be null)
- */
- public void writeSecrets(List<SecretMaterial> secretMaterials) {
- Preconditions.checkArgument(secretMaterials != null, "secretMaterials must
not be null");
- if (secretMaterials.isEmpty()) {
- return;
- }
-
- List<SecretUrn> written = new ArrayList<>(secretMaterials.size());
- try {
- for (SecretMaterial material : secretMaterials) {
- SecretUrn urn = material.urn();
- List<String> segments = urn.identifierSegments();
- Preconditions.checkArgument(
- segments.size() == 3,
- "Write-through secret URN must have entityType, entityId,
propertyKey segments: %s",
- urn);
- String entityType = segments.get(0);
- String entityId = segments.get(1);
- 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(material.plaintext(),
attributes);
- if (!urn.equals(writtenUrn)) {
- throw new IllegalArgumentException(
- "Provider returned unexpected URN: expected " + urn + ", got " +
writtenUrn);
- }
- written.add(writtenUrn);
- }
- } catch (RuntimeException e) {
- deleteSecrets(written);
- throw e;
- }
- }
-
- /**
- * Best-effort delete of write-through secret materials after a failed
create.
- *
- * <p>Only secrets that were persisted by {@link #writeSecrets} may be
passed. Do not roll back
- * external reference URNs from {@link #buildSecretReferenceUrns}.
- *
- * @param secretMaterials write-through secret materials (must not be null)
- */
- 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);
- }
-
- /**
- * Makes the versions an alter wrote current and deletes the versions it
replaced.
+ * Makes the staged versions current and deletes the versions they replaced.
*
- * <p>Call only after the entity alter committed. Failures are logged and do
not fail the
- * committed alter. If making a written version current fails and the
provider then reports it as
- * current, the previous version is deleted; otherwise the written version
is deleted. If the
- * current version cannot be looked up, both versions are kept. Running the
same change again
- * writes a new version and makes it current.
+ * <p>Call only after the entity create or alter committed. Failures are
logged and do not fail
+ * the committed create or alter. If making a written version current fails
and the provider then
+ * reports it as current, the previous version is deleted; otherwise the
written version is
+ * deleted. If the current version cannot be looked up, both versions are
kept. Running the same
+ * change again writes a new version and makes it current.
*
- * @param changes changes returned by a {@code
SecretAlterChanges.prepare*Changes} method
+ * @param changes changes returned by {@link #stageSecrets} or a {@code
+ * SecretAlterChanges.prepare*Changes} method
*/
public void commitSecrets(SecretVersionChanges changes) {
Preconditions.checkArgument(changes != null, "changes must not be null");
@@ -405,13 +341,14 @@ public class SecretManager implements Closeable {
}
/**
- * Best-effort delete of the versions an alter wrote, after the entity alter
failed.
+ * Best-effort delete of the staged versions, after the entity create or
alter failed.
*
- * <p>The versions that were current before the alter are kept, so the
entity's own write-through
+ * <p>The versions that were current before an alter are kept, so the
entity's own write-through
* secrets keep the values it still references. A secret that {@link
#alterSetProperty} rewrote
* right away is not restored.
*
- * @param changes changes returned by a {@code
SecretAlterChanges.prepare*Changes} method
+ * @param changes changes returned by {@link #stageSecrets} or a {@code
+ * SecretAlterChanges.prepare*Changes} method
*/
public void rollbackSecrets(SecretVersionChanges changes) {
Preconditions.checkArgument(changes != null, "changes must not be null");
@@ -423,15 +360,15 @@ public class SecretManager implements Closeable {
}
/**
- * Stages an alter batch: writes its plaintexts as new versions and finds
the versions it
- * releases.
+ * Stages an entity create or alter batch: writes its plaintexts as new
versions and finds the
+ * versions it releases.
*
* <p>Works from the properties before and after the whole batch, so a batch
that changes one key
* several times is treated by its net effect. A URN that has a current
version keeps it readable
* until {@link #commitSecrets}. If a write fails, the versions already
written are deleted.
*
- * @param startProperties entity properties before the alter (may be null)
- * @param finalProperties entity properties after the alter
+ * @param startProperties entity properties before the alter, or {@code
null} for a create
+ * @param finalProperties entity properties after the create or alter
* @param entityType {@code catalog}, {@code schema}, or {@code fileset}
* @param entityId stable numeric entity id
* @param plaintexts property key → plaintext to write; each key holds a
write-through URN of this
@@ -440,7 +377,7 @@ public class SecretManager implements Closeable {
* @throws UnsupportedOperationException if a provider of a written or
released secret does not
* support secret versions
*/
- SecretVersionChanges stageSecrets(
+ public SecretVersionChanges stageSecrets(
@Nullable Map<String, String> startProperties,
Map<String, String> finalProperties,
String entityType,
@@ -513,8 +450,8 @@ public class SecretManager implements Closeable {
SecretUrn urn, UnsupportedOperationException cause) {
return new UnsupportedOperationException(
String.format(
- "Secret provider \"%s\" does not support secret versions, which
altering the"
- + " write-through secret of property \"%s\" requires",
+ "Secret provider \"%s\" does not support secret versions, which
the write-through"
+ + " secret of property \"%s\" requires",
urn.providerName(), urn.propertyKey()),
cause);
}
@@ -772,9 +709,9 @@ public class SecretManager implements Closeable {
registry.close();
}
- private static List<SecretMaterial> toSecretMaterials(
+ private static Map<String, String> toPlaintexts(
List<SecretUrn> bindingUrns, Map<String, SecretBinding> bindings) {
- List<SecretMaterial> secretMaterials = new ArrayList<>(bindingUrns.size());
+ Map<String, String> plaintexts = new LinkedHashMap<>();
for (SecretUrn urn : bindingUrns) {
String propertyKey = urn.propertyKey();
SecretBinding binding = bindings.get(propertyKey);
@@ -788,9 +725,9 @@ public class SecretManager implements Closeable {
"Property '%s' cannot be set to the masked placeholder value
'%s'",
propertyKey, HiddenPropertyMaskUtils.MASKED_VALUE));
}
- secretMaterials.add(new SecretMaterial(urn, plaintext));
+ plaintexts.put(propertyKey, plaintext);
}
- return List.copyOf(secretMaterials);
+ return Collections.unmodifiableMap(plaintexts);
}
private static SecretUrn buildWriteThroughUrn(
diff --git a/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.java
b/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.java
deleted file mode 100644
index 6bfc04499a..0000000000
--- a/core/src/main/java/org/apache/gravitino/secret/SecretMaterial.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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/SecretVersionChanges.java
b/core/src/main/java/org/apache/gravitino/secret/SecretVersionChanges.java
index a71bf84c29..30c61fb52d 100644
--- a/core/src/main/java/org/apache/gravitino/secret/SecretVersionChanges.java
+++ b/core/src/main/java/org/apache/gravitino/secret/SecretVersionChanges.java
@@ -22,11 +22,14 @@ import java.util.List;
import javax.annotation.Nullable;
/**
- * Write-through secret versions that an entity alter staged or stopped
referencing.
+ * Write-through secret versions that an entity create or alter staged, or
that an alter stopped
+ * referencing.
*
- * <p>Created by the {@code SecretAlterChanges.prepare*Changes} methods. After
the entity alter
- * commits, {@link SecretManager#commitSecrets} applies them; if the alter
fails, {@link
- * SecretManager#rollbackSecrets(SecretVersionChanges)} deletes the written
versions.
+ * <p>Created by {@link SecretManager#stageSecrets}, which the {@code
+ * SecretAlterChanges.prepare*Changes} methods call. After the entity create
or alter commits,
+ * {@link SecretManager#commitSecrets} applies them. If the create or alter
fails, {@link
+ * SecretManager#rollbackSecrets(SecretVersionChanges)} deletes the written
versions, except after a
+ * failed create that leaves behind a catalog, schema, or fileset that may
still reference them.
*/
public final class SecretVersionChanges {
@@ -53,7 +56,7 @@ public final class SecretVersionChanges {
return new SecretVersionChanges(written, List.of());
}
- /** Versions written by the alter, to make current on commit and delete on
rollback. */
+ /** Versions written by the create or alter, to make current on commit and
delete on rollback. */
List<WrittenVersion> written() {
return written;
}
diff --git
a/core/src/main/java/org/apache/gravitino/secret/SecretMaterialsHolder.java
b/core/src/main/java/org/apache/gravitino/secret/SecretVersionChangesHolder.java
similarity index 83%
rename from
core/src/main/java/org/apache/gravitino/secret/SecretMaterialsHolder.java
rename to
core/src/main/java/org/apache/gravitino/secret/SecretVersionChangesHolder.java
index a1682e0004..236305a8bd 100644
--- a/core/src/main/java/org/apache/gravitino/secret/SecretMaterialsHolder.java
+++
b/core/src/main/java/org/apache/gravitino/secret/SecretVersionChangesHolder.java
@@ -21,12 +21,11 @@ package org.apache.gravitino.secret;
import com.google.common.base.Preconditions;
/**
- * Mutable holder so {@code store.update} lambdas can record secret version
changes.
- *
- * <p>Used by catalog, schema, and fileset alter paths that stage secret
versions inside {@code
- * store.update}, commit them after the update and roll them back on failure.
+ * Mutable holder that records the secret version changes a catalog, schema,
or fileset alter
+ * stages, including from inside a {@code store.update} lambda, so the alter
path can commit them
+ * after the alter succeeds and roll them back if it fails.
*/
-public final class SecretMaterialsHolder {
+public final class SecretVersionChangesHolder {
private SecretVersionChanges changes = SecretVersionChanges.EMPTY;
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
index f87f2da8a3..066e87358d 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestCatalogManager.java
@@ -102,7 +102,6 @@ import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretConstants;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterial;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretProvider;
import org.apache.gravitino.secret.SecretProviderRegistry;
@@ -2643,7 +2642,7 @@ public class TestCatalogManager {
NameIdentifier ident = NameIdentifier.of("metalake",
"legacy_secret_providers");
long id = new RandomIdGenerator().nextId();
SecretUrn urn = writeThroughUrn("catalog", id,
CredentialConstants.CREDENTIAL_PROVIDERS);
- secrets.writeSecrets(List.of(new SecretMaterial(urn, "gcs-token")));
+
secrets.getRegistry().getProvider(urn.providerName()).writeSecretVersion(urn,
"gcs-token");
Map<String, String> props = new HashMap<>(catalogProps());
props.put(CredentialConstants.CREDENTIAL_PROVIDERS, urn.toString());
entityStore.put(
@@ -2801,6 +2800,76 @@ public class TestCatalogManager {
}
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testFailureAfterCatalogIsStoredKeepsSecretsUntilEntityIsRemoved(boolean
deleteFails)
+ throws Exception {
+ InMemoryEntityStore store = Mockito.spy(new InMemoryEntityStore());
+ store.initialize(config);
+ store.put(metalakeEntity, true);
+ IOException deleteFailure = new IOException("catalog delete failed");
+ if (deleteFails) {
+ Mockito.doThrow(deleteFailure).when(store).delete(any(),
eq(EntityType.CATALOG), eq(true));
+ }
+ IllegalStateException failure = new IllegalStateException("injected lease
release failure");
+ try (SecretManager secrets = memorySecretManager();
+ CatalogManager manager =
+ Mockito.spy(
+ new CatalogManager(
+ config, store, new AtomicLong(4545L)::getAndIncrement,
secrets))) {
+ // The lease is released after store.put stored the catalog, and a
failure there still runs
+ // the create rollback.
+ Mockito.doAnswer(
+ invocation -> {
+ CatalogManager.CatalogWrapper wrapper =
+ Mockito.spy((CatalogManager.CatalogWrapper)
invocation.callRealMethod());
+ Mockito.doAnswer(
+ release -> {
+ release.callRealMethod();
+ throw failure;
+ })
+ .when(wrapper)
+ .release();
+ return wrapper;
+ })
+ .when(manager)
+ .createCatalogWrapper(any(CatalogEntity.class), Mockito.anyMap());
+ NameIdentifier ident = NameIdentifier.of(metalake, "failed_after_store");
+ SecretUrn urn = writeThroughUrn("catalog", 4545L, PROPERTY_KEY4);
+
+ RuntimeException error =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ manager.createCatalog(
+ ident,
+ Catalog.Type.RELATIONAL,
+ provider,
+ "comment",
+ catalogProps(),
+ Map.of(PROPERTY_KEY4, new SecretBinding("memory", "x")),
+ Map.of()));
+ if (deleteFails) {
+ // The catalog row is still there, so it keeps the secret it
references, and the error
+ // says the catalog was left behind.
+ Assertions.assertInstanceOf(GravitinoRuntimeException.class, error);
+ Assertions.assertTrue(
+ error.getMessage().contains("failed to remove the catalog
entity"), error.getMessage());
+ Assertions.assertSame(failure, error.getCause());
+ Assertions.assertArrayEquals(new Throwable[] {deleteFailure},
error.getSuppressed());
+ Assertions.assertTrue(store.exists(ident, EntityType.CATALOG));
+ Assertions.assertEquals("x", secrets.readSecret(urn));
+ } else {
+ Assertions.assertSame(failure, error);
+ Assertions.assertEquals(0, error.getSuppressed().length);
+ Assertions.assertFalse(store.exists(ident, EntityType.CATALOG));
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
+ }
+ } finally {
+ store.close();
+ }
+ }
+
@Test
void testSecretNoMetalake() throws Exception {
try (SecretManager secrets = memorySecretManager();
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java
b/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java
index d727523769..205f6d6d83 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestFilesetOperationDispatcher.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.audit.FilesetDataOperation;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.exceptions.FilesetAlreadyExistsException;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.file.Fileset;
import org.apache.gravitino.file.FilesetChange;
import org.apache.gravitino.meta.AuditInfo;
@@ -52,6 +53,9 @@ import org.apache.gravitino.storage.IdGenerator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
public class TestFilesetOperationDispatcher extends TestOperationDispatcher {
static FilesetOperationDispatcher filesetOperationDispatcher;
@@ -397,16 +401,99 @@ public class TestFilesetOperationDispatcher extends
TestOperationDispatcher {
.properties()
.containsKey("k2"));
Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
+ long retryId = nextId.get();
Assertions.assertThrows(
FilesetAlreadyExistsException.class,
() ->
filesets.createMultipleLocationFileset(
ident, "comment", Fileset.Type.MANAGED, locations, props,
bindings, Map.of()));
+ // The failed create deletes the version it staged under its own id.
+ SecretUrn retryUrn =
+ SecretUrn.buildWriteThrough(
+ "memory",
+ Map.of(
+ SecretConstants.ATTR_ENTITY_TYPE, "fileset",
+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(retryId),
+ SecretConstants.ATTR_PROPERTY_KEY, "k2"));
+ Assertions.assertNull(
+
secrets.getRegistry().getProvider("memory").currentSecretVersion(retryUrn));
Assertions.assertTrue(filesets.dropFileset(ident));
Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
}
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void testCreateKeepsSecretsOnceFilesetIsCreated(boolean
failInCatalogCall)
+ throws Exception {
+ try (SecretManager secrets = memorySecretManager()) {
+ AtomicLong nextId = new AtomicLong(failInCatalogCall ? 9200L : 9100L);
+ IdGenerator ids = nextId::getAndIncrement;
+ String schemaName = "schema_secret_created" + (failInCatalogCall ?
"_call" : "_mask");
+ new SchemaOperationDispatcher(catalogManager, entityStore, ids, secrets)
+ .createSchema(
+ NameIdentifier.of(metalake, catalog, schemaName),
+ "comment",
+ ImmutableMap.of("k1", "v1"));
+ FilesetOperationDispatcher filesets =
+ Mockito.spy(new FilesetOperationDispatcher(catalogManager,
entityStore, ids, secrets));
+ if (failInCatalogCall) {
+ // doWithCatalog throws after the catalog created the fileset, as a
failed detach or lease
+ // release would.
+ Mockito.doAnswer(
+ invocation -> {
+ invocation.callRealMethod();
+ throw new IllegalStateException("injected failure after the
catalog create");
+ })
+ .when(filesets)
+ .doWithCatalog(
+ Mockito.any(NameIdentifier.class),
+ Mockito.any(),
+ Mockito.eq(NoSuchSchemaException.class),
+ Mockito.eq(FilesetAlreadyExistsException.class));
+ } else {
+ // Masking reloads the catalog after the create, which fails once the
manager is closed.
+ Mockito.doThrow(new IllegalStateException("CatalogManager is already
closed"))
+ .when(filesets)
+ .getMaskAndOmitKeys(Mockito.any(NameIdentifier.class),
Mockito.any(), Mockito.any());
+ }
+
+ NameIdentifier ident =
+ NameIdentifier.of(metalake, catalog, schemaName,
"fileset_secret_created");
+ long entityId = nextId.get();
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ filesets.createMultipleLocationFileset(
+ ident,
+ "comment",
+ Fileset.Type.MANAGED,
+ Map.of(Fileset.LOCATION_NAME_UNKNOWN, "loc"),
+ ImmutableMap.of("k1", "v1"),
+ Map.of("k2", new SecretBinding("memory", "s3cr3t")),
+ Map.of()));
+
+ SecretUrn urn =
+ SecretUrn.buildWriteThrough(
+ "memory",
+ Map.of(
+ SecretConstants.ATTR_ENTITY_TYPE, "fileset",
+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(entityId),
+ SecretConstants.ATTR_PROPERTY_KEY, "k2"));
+ Fileset stored =
+ catalogManager
+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))
+ .doWithFilesetOps(ops -> ops.loadFileset(ident));
+ Assertions.assertEquals(urn.toString(), stored.properties().get("k2"));
+ Assertions.assertEquals("s3cr3t", secrets.readSecret(urn));
+
+ Assertions.assertTrue(
+ new FilesetOperationDispatcher(catalogManager, entityStore, ids,
secrets)
+ .dropFileset(ident));
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
+ }
+ }
+
@Test
public void testDropDeletesSecretsOnEitherSide() throws Exception {
try (SecretManager secrets = memorySecretManager()) {
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
index e71dfdb955..2eedb0cc15 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
@@ -43,6 +43,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
@@ -1123,8 +1124,10 @@ public class TestSchemaOperationDispatcher extends
TestOperationDispatcher {
@Test
public void testSecrets() throws Exception {
try (SecretManager secrets = memorySecretManager()) {
+ AtomicLong nextId = new AtomicLong(idGenerator.nextId());
SchemaOperationDispatcher d =
- new SchemaOperationDispatcher(catalogManager, entityStore,
idGenerator, secrets);
+ new SchemaOperationDispatcher(
+ catalogManager, entityStore, nextId::getAndIncrement, secrets);
NameIdentifier ident = NameIdentifier.of(metalake, catalog,
"schema_secret");
Map<String, SecretBinding> bindings = Map.of("k2", new
SecretBinding("memory", "s3cr3t"));
Schema schema =
@@ -1150,9 +1153,20 @@ public class TestSchemaOperationDispatcher extends
TestOperationDispatcher {
Assertions.assertFalse(
entityStore.get(ident, SCHEMA,
SchemaEntity.class).properties().containsKey("k2"));
Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
+ long retryId = nextId.get();
Assertions.assertThrows(
SchemaAlreadyExistsException.class,
() -> d.createSchema(ident, "comment", ImmutableMap.of("k1", "v1"),
bindings, Map.of()));
+ // The schema was not created in the catalog, so the failed create
deletes its version.
+ SecretUrn retryUrn =
+ SecretUrn.buildWriteThrough(
+ "memory",
+ Map.of(
+ SecretConstants.ATTR_ENTITY_TYPE, "schema",
+ SecretConstants.ATTR_ENTITY_ID, String.valueOf(retryId),
+ SecretConstants.ATTR_PROPERTY_KEY, "k2"));
+ Assertions.assertNull(
+
secrets.getRegistry().getProvider("memory").currentSecretVersion(retryUrn));
Assertions.assertTrue(d.dropSchema(ident, false));
Assertions.assertThrows(IllegalArgumentException.class, () ->
secrets.readSecret(urn));
}
diff --git
a/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java
b/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java
index 8a36cdd273..818a4cd29b 100644
---
a/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java
+++
b/core/src/test/java/org/apache/gravitino/credential/TestBaseCatalogCredentialSecrets.java
@@ -30,7 +30,6 @@ import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.CatalogEntity;
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;
@@ -124,7 +123,10 @@ public class TestBaseCatalogCredentialSecrets {
"1",
SecretConstants.ATTR_PROPERTY_KEY,
"jdbc-password"));
- secretManager.writeSecrets(java.util.List.of(new SecretMaterial(urn,
"plain-jdbc-pass")));
+ secretManager
+ .getRegistry()
+ .getProvider(urn.providerName())
+ .writeSecretVersion(urn, "plain-jdbc-pass");
Map<String, String> entityProps =
Map.of(
diff --git
a/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java
b/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java
index 10430a3457..7c8beea6fe 100644
--- a/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java
+++ b/core/src/test/java/org/apache/gravitino/secret/TestSecretManager.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.secret;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -35,20 +36,64 @@ public class TestSecretManager {
Map.of("jdbc-password", new SecretReference("memory", Map.of("path",
"secret/data/x")));
@Test
- void testWriteSecrets() {
+ void testStageSecretsForCreate() {
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));
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
+ Map.of("jdbc-user", "root"), props, "catalog", 42L, BINDINGS,
Map.of());
+ Assertions.assertEquals(Map.of("jdbc-password", "s3cr3t"), plaintexts);
Assertions.assertEquals("root", props.get("jdbc-user"));
- Assertions.assertEquals(1, urns.size());
- Assertions.assertEquals(
- "s3cr3t",
sm.getRegistry().getProvider("memory").readSecret(urns.get(0)));
- Assertions.assertEquals("s3cr3t", sm.readSecret(urns.get(0)));
+ SecretUrn urn = SecretUrn.parse(props.get("jdbc-password"));
+ Assertions.assertTrue(
+ SecretPropertyUtils.isWriteThroughForEntity(
+ "jdbc-password", urn.toString(), "catalog", 42L));
+
+ SecretVersionChanges staged = sm.stageSecrets(null, props, "catalog",
42L, plaintexts);
+ // A create releases nothing and its URN has no previous version, so
commit switches nothing.
+ Assertions.assertEquals(1, staged.written().size());
+ Assertions.assertNull(staged.written().get(0).previousId());
+ Assertions.assertTrue(staged.released().isEmpty());
+ Assertions.assertEquals("s3cr3t", sm.readSecret(urn));
+ sm.commitSecrets(staged);
+ Assertions.assertEquals("s3cr3t", sm.readSecret(urn));
+ }
+ }
+
+ @Test
+ void testRollbackSecretsAfterFailedCreate() {
+ try (SecretManager sm = memorySecretManager()) {
+ Map<String, String> props = new HashMap<>();
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(Map.of(), props, "catalog", 42L,
BINDINGS, Map.of());
+ SecretVersionChanges staged = sm.stageSecrets(null, props, "catalog",
42L, plaintexts);
+ SecretUrn urn = SecretUrn.parse(props.get("jdbc-password"));
+ Assertions.assertEquals("s3cr3t", sm.readSecret(urn));
+
+ sm.rollbackSecrets(staged);
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
sm.readSecret(urn));
+
Assertions.assertNull(sm.getRegistry().getProvider("memory").currentSecretVersion(urn));
+ }
+ }
+
+ @Test
+ void testCreateWithUnversionedProviderDeletesVersionsWrittenBefore() {
+ try (SecretManager sm = memorySecretManager()) {
+ Map<String, SecretBinding> bindings = new LinkedHashMap<>();
+ bindings.put("jdbc-password", new SecretBinding("memory", "s3cr3t"));
+ bindings.put("token", new SecretBinding("unversioned", "t0ken"));
+ Map<String, String> props = new HashMap<>();
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(Map.of(), props, "catalog", 42L,
bindings, Map.of());
+
+ UnsupportedOperationException error =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> sm.stageSecrets(null, props, "catalog", 42L, plaintexts));
+ Assertions.assertTrue(error.getMessage().contains("\"unversioned\""),
error.getMessage());
+ Assertions.assertTrue(error.getMessage().contains("\"token\""),
error.getMessage());
+ SecretUrn urn = SecretUrn.parse(props.get("jdbc-password"));
+
Assertions.assertNull(sm.getRegistry().getProvider("memory").currentSecretVersion(urn));
}
}
@@ -61,7 +106,7 @@ public class TestSecretManager {
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")));
+ sm.stageSecrets(null, props, "catalog", 42L, Map.of("jdbc-password",
"s3cr3t"));
String urn = props.get("jdbc-password");
Map<String, String> plaintext = sm.toPlaintextProperties(props);
@@ -99,7 +144,7 @@ public class TestSecretManager {
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
- sm.assembleSecretMaterials(
+ sm.assembleSecretPlaintexts(
Map.of(), entityProps, "catalog", 42L, bindings,
Map.of()));
Assertions.assertTrue(ex.getMessage().contains("masked placeholder"));
Assertions.assertTrue(ex.getMessage().contains("jdbc-password"));
@@ -142,25 +187,13 @@ public class TestSecretManager {
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.stageSecrets(null, props, "catalog", 99L, Map.of("jdbc-password",
"s3cr3t"));
sm.deleteSecretsFromProperties(props);
Assertions.assertThrows(IllegalArgumentException.class, () ->
sm.readSecret(urns.get(0)));
}
@@ -169,12 +202,17 @@ public class TestSecretManager {
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_PROVIDERS,
"memory,unversioned");
properties.setProperty(
SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX
+ "memory."
+ SecretProviderRegistry.CLASS_NAME,
InMemorySecretsProvider.class.getName());
+ properties.setProperty(
+ SecretProviderRegistry.GRAVITINO_SECRET_PROVIDER_PREFIX
+ + "unversioned."
+ + SecretProviderRegistry.CLASS_NAME,
+ TestSecretManagerAlter.UnversionedSecretsProvider.class.getName());
config.loadFromProperties(properties);
return new SecretManager(config);
}
diff --git
a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java
b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java
index 85b7a53f20..14495e3b2b 100644
---
a/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java
+++
b/core/src/test/java/org/apache/gravitino/secret/TestSecretPropertyUtils.java
@@ -49,15 +49,16 @@ public class TestSecretPropertyUtils {
Map.of("jdbc-password", new SecretBinding("memory", "s3cr3t"));
Map<String, String> entityProps =
SecretPropertyUtils.copyEntityProperties(properties, bindings,
Map.of());
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(properties, entityProps, "catalog", 42L,
bindings, Map.of());
- sm.writeSecrets(writes);
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(properties, entityProps, "catalog", 42L,
bindings, Map.of());
+ sm.stageSecrets(null, entityProps, "catalog", 42L, plaintexts);
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()));
+ Assertions.assertEquals(Map.of("jdbc-password", "s3cr3t"), plaintexts);
+ Assertions.assertEquals(
+ "s3cr3t",
sm.readSecret(SecretUrn.parse(entityProps.get("jdbc-password"))));
}
}
@@ -83,10 +84,9 @@ public class TestSecretPropertyUtils {
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());
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(entityProps, entityProps, "schema", 1L,
Map.of(), Map.of());
+ Assertions.assertTrue(plaintexts.isEmpty());
Assertions.assertEquals("root", entityProps.get("jdbc-user"));
}
}
@@ -105,15 +105,15 @@ public class TestSecretPropertyUtils {
new SecretBinding("memory", "custom-value"),
"s3-secret-access-key",
new SecretBinding("memory", "s3-secret-value"));
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
Map.of("jdbc-url", "jdbc:mysql://localhost/db", "jdbc-user",
"root"),
entityProps,
"catalog",
42L,
bindings,
Map.of());
- sm.writeSecrets(writes);
+ sm.stageSecrets(null, entityProps, "catalog", 42L, plaintexts);
entityProps.put("s3-access-key-id", "AKIA");
entityProps.put("visible", "ok");
@@ -191,9 +191,9 @@ public class TestSecretPropertyUtils {
entityProps.put("jdbc-password", "inline-secret");
Map<String, SecretBinding> bindings =
Map.of("custom-secret", new SecretBinding("memory", "custom-value"));
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(Map.of(), entityProps, "catalog", 42L,
bindings, Map.of());
- sm.writeSecrets(writes);
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(Map.of(), entityProps, "catalog", 42L,
bindings, Map.of());
+ sm.stageSecrets(null, entityProps, "catalog", 42L, plaintexts);
Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm,
entityProps, null);
Assertions.assertEquals("custom-value", secrets.get("custom-secret"));
@@ -298,9 +298,9 @@ public class TestSecretPropertyUtils {
@Test
void testAssembleWithNullTargetWhenNoSecrets() {
try (SecretManager sm = memorySecretManager()) {
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(null, null, "schema", 1L, null, null);
- Assertions.assertTrue(writes.isEmpty());
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(null, null, "schema", 1L, null, null);
+ Assertions.assertTrue(plaintexts.isEmpty());
}
}
diff --git a/design-docs/gravitino-entity-secrets.md
b/design-docs/gravitino-entity-secrets.md
index 6e3ec86f2d..f7fc32f8c0 100644
--- a/design-docs/gravitino-entity-secrets.md
+++ b/design-docs/gravitino-entity-secrets.md
@@ -69,9 +69,9 @@ instead of plaintext for marked keys, expose a clear **REST
create/alter contrac
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).
+ `urn:gravitino-secret` and ends with that property's key. Whether drop
calls `deleteSecret`, or
+ an alter release deletes the current version, 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
work as plaintext with no migration required.
@@ -361,7 +361,9 @@ public interface GravitinoSecretProvider {
String type();
/**
- * Write-through: store plaintext in this backend and return a durable
reference URN.
+ * Store plaintext in this backend and return a durable reference URN.
+ * Core calls it only for setProperty on a secret URN the entity does not
own (§5.5.3);
+ * create and alter of the entity's own write-through secrets use the
version methods.
* Read-only / external-ref-only implementations throw
UnsupportedOperationException.
* Core may wrap a provider-returned type-specific identifier into the full
URN using the
* factory-bound provider name — or the impl returns the full URN.
@@ -372,16 +374,16 @@ public interface GravitinoSecretProvider {
String readSecret(String urn);
/**
- * Best-effort delete of every version. Used on entity drop and create
rollback for
- * <b>Gravitino-managed</b> (write-through) secrets only — see §5.5.2 C.
Alter uses the
- * version methods instead (§5.5.3).
+ * Best-effort delete of every version. Used on entity drop for
<b>Gravitino-managed</b>
+ * (write-through) secrets only — see §5.5.2 C. Create and alter use the
version methods
+ * instead (§5.5.3).
*/
void deleteSecret(String urn);
}
/**
* Context for write-through path generation / GC metadata (Polaris forEntity
analogue).
- * External-ref path never calls writeSecret — this type is unused there.
+ * Creating or setting a secret reference never calls writeSecret — this type
is unused there.
*
* <p>Do <b>not</b> put renameable names (metalake / catalog / schema /
fileset <b>names</b>) into
* generated URNs. Prefer stable ids so renames do not orphan or collide paths.
@@ -396,10 +398,11 @@ public final class SecretWriteContext {
**Mapping to entity property JSON** after write-through:
```text
-writeSecret → urn string
- (URN envelope provider_name from factory binding; identifier includes
entityType + entityId + propertyKey)
+Core builds urn
+ (URN envelope provider_name from the binding; identifier is entityType +
entityId + propertyKey)
+writeSecretVersion(urn, plaintext) → first version of urn (§5.5.3)
Core persists:
- "jdbc-password": "<returned-urn>"
+ "jdbc-password": "<urn>"
```
URN / write-through paths must use **stable entity ids** + **entity type** +
**property key**, not
@@ -414,8 +417,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 typed `secretBindings` (`jdbc-password` → `{ "provider":
"memory",
-"plaintext": "…" }`). Core calls `writeSecret(plaintext,
SecretWriteContext("catalog", entityId,
-"jdbc-password"))`, persists e.g.:
+"plaintext": "…" }`). Core builds the URN from `("catalog", entityId,
"jdbc-password")`, writes
+the plaintext as its first version (§5.5.3), and persists e.g.:
```text
jdbc-password = urn:gravitino-secret:memory:catalog:10042:jdbc-password
@@ -454,7 +457,7 @@ full check.
Rationale: write-through secrets are **Gravitino-managed**; once the property
(or entity) is gone,
leaving material in the provider would orphan it. External refs are owned
outside Gravitino.
-#### 5.5.3 Alter: versioned write-through secrets
+#### 5.5.3 Create and alter: versioned write-through secrets
Secret material and the entity live in different stores, so an alter that
fails after touching the
provider must not leave the entity referencing a deleted or changed
write-through secret of its own.
@@ -465,7 +468,7 @@ A `setCurrentSecretVersion` call that throws must not take
effect afterwards, an
`currentSecretVersion` must already report whether it did: a provider settles
an unknown outcome
before throwing, for example with a conditional update, and reads with
read-after-write
consistency.
-If a provider of a written or released URN does not implement them, the alter
fails with
+If a provider of a written or released URN does not implement them, the create
or alter fails with
`UnsupportedOperationException`. Released URNs are checked before any version
is written; versions
already written for other keys in the batch are deleted best-effort.
@@ -485,6 +488,13 @@ already written for other keys in the batch are deleted
best-effort.
3. Rollback (`rollbackSecrets`, entity update failed): delete the new
versions. The entity keeps
reading the versions that were current before the alter.
+Create runs the same steps with no start properties, so it releases nothing.
Its URNs carry the new
+entity id and have no current version, so each new version is current once
written and commit has
+nothing to switch. If the create fails, rollback deletes those versions. A
schema already created in
+the external catalog, or a fileset the catalog already created, keeps them
even if a later step
+fails. A stored catalog whose create then fails keeps them if its entity
cannot be removed, and the
+create fails with an error that asks to drop the catalog with force.
+
An alter releases a write-through URN of the entity when the final properties
no longer hold it,
for example after `removeProperty`, `setSecretReference`, or a binding to
another provider. Working
from the start and final properties means a batch that changes one key several
times is handled by
@@ -529,7 +539,7 @@ map[URN] = { versions: version id → Base64(plaintext),
current: version id }
| ---------------------- |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| `writeSecret` | Base64-encode plaintext. Allocate URN
`urn:gravitino-secret:<provider_name>:<entityType>:<entityId>:<propertyKey>`
from `SecretWriteContext`. Store Base64 as the only version of that URN and
make it current. Return the URN. |
| `readSecret` | Look up map by URN; Base64-decode the current
version; return plaintext. Missing URN or no current version →
`IllegalArgumentException`.
|
-| `deleteSecret` | `map.remove(urn)`, all versions — best-effort; used
by create rollback and entity drop for **managed** (write-through) secrets
(§5.5.2 C).
|
+| `deleteSecret` | `map.remove(urn)`, all versions — best-effort; used
by entity drop for **managed** (write-through) secrets (§5.5.2 C).
|
| `writeSecretVersion` | Add a version under an id that increases per
provider instance; make it current only when the URN has no current version.
|
| `setCurrentSecretVersion` | Make an existing version current; unknown
version → `IllegalArgumentException` without changing state (synchronous, so a
call that throws never takes effect).
|
| `deleteSecretVersion` | Remove one version; deleting the current one leaves
no readable value; unknown version → no-op.
|
@@ -649,7 +659,7 @@ 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`**
| Validate binding; `plaintext` (not `******`) → `writeSecret` via named
provider; persist **returned URN string**; key **must not** be in `properties`.
|
+| Key in **`secretBindings`**
| Validate binding; `plaintext` (not `******`) → first version of the URN
on the named provider (§5.5.3); persist **URN string**; key **must not** be in
`properties`. |
| Key in **both** `secretReferences` and `secretBindings`
| **Reject**.
|
| Key in `secretReferences` **or** `secretBindings` **and** also present in
`properties` | **Reject** (no overlap with `properties`).
|
| `secretBindings` missing `provider` / `plaintext`, or `plaintext` is
`******` | **Reject**.
|
@@ -714,8 +724,8 @@ 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) + `plaintext` (plaintext
string) | Write-through bind/re-bind
(`writeSecret`); persist returned URN
|
+| `setProperty` | `value` (**string** plaintext)
| Today’s plaintext set. If the **current**
value is a write-through URN of this entity, write `value` as a new version of
it (§5.5.3); if it is another secret URN, rewrite it in place with
`writeSecret` via its provider and persist the returned URN |
+| `setSecretBinding` | `provider` (instance name) + `plaintext` (plaintext
string) | Write-through bind/re-bind: build the
URN and write `plaintext` as a new version of it (§5.5.3); persist the 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
|
@@ -769,7 +779,7 @@ Request:
}
```
-DB `properties` (illustrative returned URN):
+DB `properties` (illustrative URN):
```json
{
diff --git
a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java
b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java
index 046422b2ce..109807de4f 100644
---
a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java
+++
b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/store/TestGravitinoCatalogStore.java
@@ -46,7 +46,6 @@ import
org.apache.gravitino.flink.connector.catalog.BaseCatalogFactory;
import org.apache.gravitino.flink.connector.catalog.GravitinoCatalogManager;
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.SecretProviderRegistry;
import org.apache.gravitino.secret.SupportsSecrets;
@@ -237,15 +236,15 @@ public class TestGravitinoCatalogStore {
try (SecretManager sm = memorySecretManager()) {
Map<String, String> entityProps = new HashMap<>();
entityProps.put("custom-token", "placeholder");
- java.util.List<SecretMaterial> writes =
- sm.assembleSecretMaterials(
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
Map.of(),
entityProps,
"catalog",
2L,
Map.of("custom-token", new SecretBinding("memory", "mem-tok")),
Map.of());
- sm.writeSecrets(writes);
+ sm.stageSecrets(null, entityProps, "catalog", 2L, plaintexts);
Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm,
entityProps);
Catalog catalog = mock(Catalog.class);
diff --git
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
index 44089c0a55..0c39c40425 100644
---
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
+++
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/provider/TestDynamicIcebergConfigProvider.java
@@ -48,7 +48,6 @@ import
org.apache.gravitino.iceberg.service.authorization.IcebergRESTServerConte
import org.apache.gravitino.meta.CatalogEntity;
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.SecretProviderRegistry;
import org.apache.gravitino.secret.SupportsSecrets;
@@ -702,15 +701,15 @@ public class TestDynamicIcebergConfigProvider {
try (SecretManager sm = memorySecretManager()) {
Map<String, String> entityProps = new HashMap<>();
entityProps.put("custom-token", "placeholder");
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
Map.of(),
entityProps,
"catalog",
3L,
Map.of("custom-token", new SecretBinding("memory",
"mem-custom-tok")),
Map.of());
- sm.writeSecrets(writes);
+ sm.stageSecrets(null, entityProps, "catalog", 3L, plaintexts);
Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm,
entityProps);
String metalakeName = "test_metalake";
@@ -765,8 +764,8 @@ public class TestDynamicIcebergConfigProvider {
entityProps.put(IcebergConstants.CATALOG_BACKEND, "jdbc");
entityProps.put(IcebergConstants.CATALOG_BACKEND_NAME, catalogName);
entityProps.put(IcebergConstants.GRAVITINO_JDBC_USER, "root");
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
Map.of(IcebergConstants.GRAVITINO_JDBC_USER, "root"),
entityProps,
"catalog",
@@ -775,7 +774,7 @@ public class TestDynamicIcebergConfigProvider {
IcebergConstants.GRAVITINO_JDBC_PASSWORD,
new SecretBinding("memory", "aux-mem-pwd")),
Map.of());
- sm.writeSecrets(writes);
+ sm.stageSecrets(null, entityProps, "catalog", 9L, plaintexts);
@SuppressWarnings("unchecked")
BaseCatalog<?> baseCatalog = Mockito.mock(BaseCatalog.class);
diff --git
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java
index 69a33ebb74..3968a389d6 100644
---
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java
+++
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/catalog/TestBaseCatalogSecrets.java
@@ -26,7 +26,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
@@ -42,7 +41,6 @@ import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.exceptions.RESTException;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretManager;
-import org.apache.gravitino.secret.SecretMaterial;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretProviderRegistry;
import org.apache.gravitino.secret.SupportsSecrets;
@@ -104,15 +102,15 @@ public class TestBaseCatalogSecrets {
try (SecretManager sm = memorySecretManager()) {
Map<String, String> entityProps = new HashMap<>();
entityProps.put("custom-token", "placeholder");
- List<SecretMaterial> writes =
- sm.assembleSecretMaterials(
+ Map<String, String> plaintexts =
+ sm.assembleSecretPlaintexts(
Map.of(),
entityProps,
"catalog",
1L,
Map.of("custom-token", new SecretBinding("memory",
"from-memory")),
Map.of());
- sm.writeSecrets(writes);
+ sm.stageSecrets(null, entityProps, "catalog", 1L, plaintexts);
Map<String, String> secrets = SecretPropertyUtils.buildSecrets(sm,
entityProps);
setUpCatalog(