Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# MCP service server names are unique, and a masked value is kept only where a stored value exists

- **Status:** Accepted
- **Revisions:** v1 2026-11-11 (initial); v2 2026-11-14 (checked on any server change, order included); v3 2026-11-19 (secret ids of list elements stay distinct once cleaned)
- **Revisions:** v1 2026-11-11 (initial); v2 2026-11-14 (checked on any server change, order included); v3 2026-11-19 (secret ids of list elements stay distinct once cleaned); v4 2026-11-19 (a stored reference follows its element)
- **Deciders:** backend
- **Guard:** `PasswordEntityMaskerTest.testMaskedSecretWithNoStoredValueIsRejected`, `PasswordEntityMaskerTest.testNamesSharingASecretIdKeepTheirOwnKeysWhenReordered`; `ReflectionUtilCollectionKeysTest`, `SecretMapEntriesExternalStoreTest.reorderingServersThatShareACleanedNameThenReplacingOneKeyKeepsTheOther`; `McpServiceResourceIT.post_mcpServiceWithDuplicateServerNames_400`, `McpServiceResourceIT.put_renamedServerWithMaskedApiKey_400_keepsStoredKey`, `McpServiceResourceIT.put_reorderedStoredServersWithSameName_400_otherEditsStillSave`
- **Guard:** `PasswordEntityMaskerTest.testMaskedSecretWithNoStoredValueIsRejected`, `PasswordEntityMaskerTest.testNamesSharingASecretIdKeepTheirOwnKeysWhenReordered`; `ReflectionUtilCollectionKeysTest`, `SecretMapEntriesExternalStoreTest.reorderingServersThatShareACleanedNameThenReplacingOneKeyKeepsTheOther`, `SecretMapEntriesExternalStoreTest.aRenamedServerKeepsItsKeyWhenItsOldNameIsReusedLater`; `McpServiceResourceIT.post_mcpServiceWithDuplicateServerNames_400`, `McpServiceResourceIT.put_renamedServerWithMaskedApiKey_400_keepsStoredKey`, `McpServiceResourceIT.put_reorderedStoredServersWithSameName_400_otherEditsStillSave`
- **Related:** open-metadata/openmetadata-collate#7962, ADR:2026-10-24-a-masked-connection-secret-is-kept-only-while-the-endpoint-is-unchanged

## Context
Expand Down Expand Up @@ -52,3 +52,28 @@ deleted from, the id computed for the element on that save. With position ids, s
and then editing one key overwrote, or deleted, the secret the other server still referenced.
Server names are still only refused when they repeat exactly: `Prod` and `prod` are accepted, keep
their own keys through a reorder, and get distinct, stable secret ids.

## Amendment (v4, 2026-11-19)

After a save to an external secrets manager, every list element's secret reference is the id
computed for that element on that save. A save used to keep an existing `secret:` reference as it
was, so a server renamed from `alpha` to `beta` (or one keyed by position and moved) still read
`alpha`'s secret, and a server later saved as `alpha` overwrote it.

- Before anything in a list is written, a reference to the same field of another element of the
list is read back into its value; the save then writes it under the element's own id. All reads
come first, so two elements that swap ids keep their own values.
- A move never overwrites a secret it could not put back: the value at the element's own id is
read too, and a save that fails part way writes it back (or removes what the move created). If
that id cannot be read, the reference is kept. A secret store is not transactional, so a server
dropped in the same failed save can still be left with a moved value.
- A reference outside the list was given by the user and is kept, as is one whose secret no longer
exists or cannot be read (a server that may write secrets but not read them): the save then
succeeds with the reference unchanged. Lists nested inside an element are covered too.
- Whether a reference is another element's is read from its id: inside the list's id, ending like
the field's own. Where the provider's separator (`-`, `_`) can also appear in names, a reference a
user typed to a secret whose id happens to start like this list's ids is treated as the list's.
- Preparing a change for approval moves nothing, and the database secrets manager, which holds no
references, is unaffected.
- The secret left under the old id still belongs to the service and goes when the service is
hard-deleted.
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,24 @@ protected boolean isNameReserved(Throwable failure) {
return false;
}

@Override
protected boolean storesSecretsByReference() {
return true;
}

@Override
protected void restoreMovedSecret(final MovedSecret moved) {
moved
.previous()
.ifPresentOrElse(
value -> upsertSecret(moved.secretId(), value), () -> deleteSecret(moved.secretId()));
Comment on lines +155 to +159

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Failed renames block retries. When a rename creates a new destination secret and a later list write fails, this rollback deletes the new secret. Azure Key Vault keeps deleted names reserved, so retrying the rename fails when storeValue tries to write the same id. The reserved-name fallback in storeOwnedValue does not cover this path.

Make rollback and retry work with Azure's soft deletion, rather than leaving the destination name unusable until recovery or the retention period ends.

}

@Override
protected void validateBeforeStore(final String fieldName, final String value) {
rejectReservedPlaceholder(fieldName, value);
}

@Override
protected Optional<String> findSecretValue(String reference) {
Optional<String> secretValue = Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,192 @@ static void forEachTraversableElement(Object obj, BiConsumer<Object, String> act
}
}

/** Rejects a value a save would refuse, before any secret of the save is written. */
protected void validateBeforeStore(final String fieldName, final String value) {}

/** Whether a stored secret field holds a {@code secret:} reference to a secret held elsewhere. */
protected boolean storesSecretsByReference() {
return false;
}

/**
* Turns each reference an element of {@code collection} holds to a secret stored under another
* element's id back into its value, so the save that follows writes it to the element's own id.
*
* <p>A secret id comes from an element's name, or its position when the name is missing or
* repeated, and a save keeps an existing reference as it is. So a server renamed from {@code
* alpha} to {@code beta}, or moved to another position, would still read {@code alpha}'s secret,
* and a server later saved as {@code alpha} would overwrite it. Every reference is read before
* anything is written, so two elements that swap ids keep their own values. A reference outside
* the collection was given by the user and is kept, as is one whose secret no longer exists.
*/
/**
* Encrypts each element of {@code obj} when it is a collection. Saving to an external secrets
* manager first moves references to other elements' secrets, and puts back what the moves
* overwrote if the save then fails part way.
*/
private void encryptCollection(
final Object obj,
final CollectionSecretId collection,
final boolean store,
final boolean persistExternalSecrets) {
final boolean isMovable =
obj instanceof Collection<?>
&& store
&& persistExternalSecrets
&& storesSecretsByReference();
final List<MovedSecret> moves =
isMovable
? resolveReferencesInCollection(obj, collection.secretId(), collection.field())
: List.of();
try {
Comment on lines +532 to +546

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bug: Moved secrets aren't restored when the save fails after encryption

restoreMovedSecrets only runs when encryptCollection itself throws. In ServiceEntityRepository.store, encryptConnection(service) runs inside writeWithSecretOwnership, and after it come super.store(service, update, expectedVersion) and ownership.recordWrite, all in the same DB transaction. If any of those fail (a version conflict, a DB error, an ownership failure), the transaction rolls back but the vault writes stay. Take a swap of alpha/beta: alpha's id now holds beta-key and the reverse, while the stored entity still has the old config, so each server sends the other's credential. updateMany has the same problem: if encrypting a later service throws, the moves already done for earlier services in the batch are never undone. The amendment says "a save that fails part way writes it back", but that only holds for failures during encryption, and the caveat lists only dropped servers.

Fix: have the encrypt step return the MovedSecret list, or record it on a per-save context. writeWithSecretOwnership can then restore it when write.run() or the transaction fails, for example from a rollback hook or a try/catch around executeInTransaction. Add a test where super.store throws after a swap.

Was this helpful? React with 👍 / 👎

forEachTraversableElement(
obj,
(element, elementKey) ->
encryptPasswordFields(
element,
buildSecretId(false, collection.secretId(), collection.field(), elementKey),
store,
persistExternalSecrets));
} catch (RuntimeException e) {
restoreMovedSecrets(moves);
throw e;
}
}

private List<MovedSecret> resolveReferencesInCollection(
final Object collection, final String secretId, final String collectionField) {
final String collectionSecretId = buildSecretId(false, secretId, collectionField);
final List<MovedSecret> moves = new ArrayList<>();
forEachTraversableElement(
collection,
(element, elementKey) -> {
final String elementSecretId =
buildSecretId(false, secretId, collectionField, elementKey);
final ElementSecretIds ids = new ElementSecretIds(collectionSecretId, elementSecretId);
resolveReferencesInObject(element, new MovePass(ids, moves), elementSecretId);
});
return List.copyOf(moves);
}

/** Walks the fields, nested objects and nested lists of one element, as encryption does. */
private void resolveReferencesInObject(
final Object holder, final MovePass pass, final String secretId) {
if (!DO_NOT_ENCRYPT_CLASSES.contains(holder.getClass())) {
Arrays.stream(holder.getClass().getMethods())
.filter(ReflectionUtil::isGetMethodOfObject)
.forEach(method -> resolveReferencesInField(holder, method, pass, secretId));
}
}

private void resolveReferencesInField(
final Object holder, final Method method, final MovePass pass, final String secretId) {
final Object value = ReflectionUtil.getObjectFromMethod(method, holder);
final String field = method.getName().replaceFirst("get", "").toLowerCase(Locale.ROOT);
final String fieldSecretId = buildSecretId(false, secretId, field);
if (Boolean.TRUE.equals(CommonUtil.isOpenMetadataObject(value))) {
resolveReferencesInObject(value, pass, fieldSecretId);
}
if (value instanceof String text && method.getAnnotation(PasswordField.class) != null) {
resolvePasswordField(holder, method, text, pass, fieldSecretId);
}
forEachTraversableElement(
value,
(element, elementKey) ->
resolveReferencesInObject(
element, pass, buildSecretId(false, secretId, field, elementKey)));
}

private void resolvePasswordField(
final Object holder,
final Method method,
final String value,
final MovePass pass,
final String fieldSecretId) {
final String fieldName = method.getName().replaceFirst("get", "");
validateBeforeStore(fieldName, fernet.decryptIfApplies(value));
otherElementReference(value, pass.ids(), fieldSecretId)
.flatMap(reference -> readMove(reference, fieldSecretId))
.ifPresent(
move -> {
pass.moves().add(move.restore());
ReflectionUtil.setValueInMethod(
holder, move.value(), ReflectionUtil.getToSetMethod(holder, value, fieldName));
});
}

/**
* The value to move under {@code fieldSecretId}, with what that id holds now so a failed save
* can put it back. Empty when either secret cannot be read - for instance when the server may
* write secrets but not read them - and the reference is then kept as it is.
*/
private Optional<Move> readMove(final String reference, final String fieldSecretId) {
Optional<Move> move = Optional.empty();
try {
final Optional<String> previous = findSecretValue(SECRET_FIELD_PREFIX + fieldSecretId);
move =
findSecretValue(SECRET_FIELD_PREFIX + reference)
.map(value -> new Move(value, new MovedSecret(fieldSecretId, previous)));
} catch (SecretsManagerException e) {
LOG.warn(
"Keeping the reference to secret [{}]: it could not be moved under [{}]: {}",
reference,
fieldSecretId,
e.getMessage());
}
return move;
}

/** Puts back what each move overwrote, after a save that failed part way. */
private void restoreMovedSecrets(final List<MovedSecret> moves) {
moves.forEach(
moved -> {
try {
restoreMovedSecret(moved);
} catch (RuntimeException e) {
LOG.error(
"Could not restore secret [{}] after a failed save: {}",
moved.secretId(),
e.getMessage());
}
});
}

/** Writes back, or removes, a secret a move overwrote. Only managers holding references move. */
protected void restoreMovedSecret(final MovedSecret moved) {}

/**
* The secret {@code fieldValue} references when it is the same field of another element of the
* collection: an id inside the collection that ends like this field's own id, but is not it.
*/
private Optional<String> otherElementReference(
final String fieldValue, final ElementSecretIds ids, final String fieldSecretId) {
final String clear = fernet.decryptIfApplies(fieldValue);
final String reference =
Boolean.TRUE.equals(isSecret(clear)) ? clear.substring(SECRET_FIELD_PREFIX.length()) : "";
final boolean isOtherElements =
fieldSecretId.startsWith(ids.element())
&& reference.startsWith(ids.collection() + secretsIdConfig.separator())
&& reference.endsWith(fieldSecretId.substring(ids.element().length()))
&& !reference.equals(fieldSecretId);
return isOtherElements ? Optional.of(reference) : Optional.empty();
}

/** The secret ids of a collection and of the element being walked inside it. */
private record ElementSecretIds(String collection, String element) {}

/** The secret id of the object holding a collection, and the collection's field name. */
private record CollectionSecretId(String secretId, String field) {}

/** The ids of the element being walked and the moves found so far in its collection. */
private record MovePass(ElementSecretIds ids, List<MovedSecret> moves) {}

/** A value read from another element's secret, and what writing it overwrites. */
private record Move(String value, MovedSecret restore) {}

/** A secret a move writes over, with the value it held before; empty when it did not exist. */
record MovedSecret(String secretId, Optional<String> previous) {}

private Object encryptPasswordFields(Object toEncryptObject, String secretId, boolean store) {
return encryptPasswordFields(toEncryptObject, secretId, store, true);
}
Expand Down Expand Up @@ -555,18 +741,11 @@ private Object encryptPasswordFields(
toSet);
}
} else {
forEachTraversableElement(
encryptCollection(
obj,
(element, elementKey) ->
encryptPasswordFields(
element,
buildSecretId(
false,
secretId,
fieldName.toLowerCase(Locale.ROOT),
elementKey),
store,
persistExternalSecrets));
new CollectionSecretId(secretId, fieldName.toLowerCase(Locale.ROOT)),
store,
persistExternalSecrets);
}
});
}
Expand Down Expand Up @@ -940,19 +1119,20 @@ private void visitStoredSecrets(
false));
}
} else {
final String collectionField = fieldName.toLowerCase(Locale.ROOT);
final String collectionSecretId = buildSecretId(false, secretId, collectionField);
forEachTraversableElement(
obj,
(element, elementKey) ->
visitStoredSecrets(
element,
withNestedSecretId(
secretIds,
buildSecretId(
false,
secretId,
fieldName.toLowerCase(Locale.ROOT),
elementKey)),
visitor));
(element, elementKey) -> {
final String elementSecretId =
buildSecretId(false, secretId, collectionField, elementKey);
final ElementSecretIds ids =
new ElementSecretIds(collectionSecretId, elementSecretId);
visitStoredSecrets(
element,
withNestedSecretId(secretIds, elementSecretId),
secret -> visitor.accept(withMove(secret, ids)));
});
}
});
}
Expand Down Expand Up @@ -1001,7 +1181,28 @@ public record SecretInventory(
Set<String> storedScalars,
Set<String> references) {}

private record StoredSecret(String name, String value, boolean mapEntry) {}
/**
* @param movedFrom the secret of another element of the same collection that this field still
* references; the next save writes its value under {@code name}
*/
private record StoredSecret(
String name, String value, boolean mapEntry, Optional<String> movedFrom) {
StoredSecret(final String name, final String value, final boolean mapEntry) {
this(name, value, mapEntry, Optional.empty());
}
}

private StoredSecret withMove(final StoredSecret secret, final ElementSecretIds ids) {
final boolean isMovable =
storesSecretsByReference() && !secret.mapEntry() && secret.movedFrom().isEmpty();
return isMovable
? otherElementReference(secret.value(), ids, secret.name())
.map(
reference ->
new StoredSecret(secret.name(), secret.value(), false, Optional.of(reference)))
.orElse(secret)
: secret;
}

@VisibleForTesting
SecretInventory secretInventory(Object config, String root) {
Expand Down Expand Up @@ -1035,13 +1236,17 @@ private void collectSecret(
return;
}
Optional<String> reference = referencedSecretName(clear);
// A reference to another element's secret is written under this field's own id on save, and
// the secret it leaves behind still belongs to the entity. It stays in use until that save.
final boolean isMoved = secret.movedFrom().isPresent();
reference.ifPresent(references::add);
if (reference.isEmpty()) {
if (reference.isEmpty() || isMoved) {
written.add(secret.name());
}
if (reference.isEmpty() || reference.get().equals(secret.name())) {
if (reference.isEmpty() || isMoved || reference.get().equals(secret.name())) {
stored.add(secret.name());
}
secret.movedFrom().ifPresent(stored::add);
}

private static List<String> withNestedSecretId(List<String> secretIds, String nestedSecretId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,16 +163,17 @@ private static String secretKey(
final int index,
final Map<String, Integer> exact,
final Map<String, Integer> cleaned) {
final boolean named = isUnique(name, name, exact);
final boolean readable =
named && isUnique(name, secretIdForm(name), cleaned) && !looksGenerated(secretIdForm(name));
String key = POSITION_KEY_PREFIX + index;
if (readable) {
key = name;
} else if (named) {
key = HASHED_NAME_PREFIX + DigestUtils.sha256Hex(name).substring(0, HASHED_NAME_LENGTH);
}
return key;
final boolean isNamed = isUnique(name, name, exact);
final boolean isReadable =
isNamed
&& isUnique(name, secretIdForm(name), cleaned)
&& !looksGenerated(secretIdForm(name));
final String unreadableKey = isNamed ? hashedName(name) : POSITION_KEY_PREFIX + index;
return isReadable ? name : unreadableKey;
}

private static String hashedName(final String name) {
return HASHED_NAME_PREFIX + DigestUtils.sha256Hex(name).substring(0, HASHED_NAME_LENGTH);
}

/** A cleaned name that could equal a position key or a hashed name of another element. */
Expand Down
Loading
Loading