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)
- **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)
- **Deciders:** backend
- **Guard:** `PasswordEntityMaskerTest.testMaskedSecretWithNoStoredValueIsRejected`; `McpServiceResourceIT.post_mcpServiceWithDuplicateServerNames_400`, `McpServiceResourceIT.put_renamedServerWithMaskedApiKey_400_keepsStoredKey`, `McpServiceResourceIT.put_reorderedStoredServersWithSameName_400_otherEditsStillSave`
- **Guard:** `PasswordEntityMaskerTest.testMaskedSecretWithNoStoredValueIsRejected`, `PasswordEntityMaskerTest.testNamesSharingASecretIdKeepTheirOwnKeysWhenReordered`; `ReflectionUtilCollectionKeysTest`; `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 All @@ -30,3 +30,21 @@ names, saved before this rule, stay editable outside `servers`; reordering or ed
servers asks for unique names first, since repeated names could only be matched by position. The
masked-value rule applies to every service connection, where a masked value can only come from a
stored one.

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

Matching a masked value back to its stored one and naming an element inside a secrets manager's
secret id are now two keys (`ReflectionUtil.getCollectionElementIdentities` and
`getCollectionElementKeys`).

- **Matching a masked value:** unchanged. An element is matched by its exact `name` when it occurs
once in the list, and by position (`#<index>`) otherwise. A name starting with `#` gets one more
`#`, so it never equals a position key.
- **Secret id:** an element is named by its `name` only when the name, lowercased and reduced to
ASCII letters and digits, contains a letter and occurs once in the list; otherwise by
`#<index>`. Secrets managers lowercase an id and drop or replace other characters, so `Prod` and
`prod`, or `prod-1` and `prod_1`, would otherwise share one stored secret.

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 secret ids. A reference to an existing secret is
kept as it is on save, so a reorder never moves one server's secret onto another.
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ private void visitSecretMap(Map<?, ?> secretMap, String fieldKey, PasswordFieldV
}

private void walkCollection(Collection<?> collection, String key, PasswordFieldVisitor visitor) {
List<String> elementKeys = ReflectionUtil.getCollectionElementKeys(collection);
List<String> elementKeys = ReflectionUtil.getCollectionElementIdentities(collection);
int index = 0;
for (Object element : collection) {
if (isTraversable(element)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.openmetadata.schema.entity.services.ServiceType;
import org.openmetadata.service.exception.ReflectionException;
Expand All @@ -32,6 +36,8 @@
public class ReflectionUtil {
// Distinguishes a positional key from a name, so the two can never collide.
private static final String POSITION_KEY_PREFIX = "#";
private static final Pattern NOT_LETTER_OR_DIGIT = Pattern.compile("[^a-z0-9]");
private static final Pattern DIGITS_ONLY = Pattern.compile("[0-9]*");

private ReflectionUtil() {
/* Hidden construction */
Expand Down Expand Up @@ -92,7 +98,8 @@ public static boolean isGetMethodOfObject(Method method) {
}

/**
* Identifies each element of a collection for secret bookkeeping.
* Identifies each element of a collection, to restore a masked secret onto the element it was
* stored for.
*
* <p>Position is not a stable identity. Secrets are stored against the original configuration and
* restored onto the updated one, so keying by index would restore a secret onto whichever element
Expand All @@ -101,29 +108,62 @@ public static boolean isGetMethodOfObject(Method method) {
*
* <p>A name is only an identity if it is unique. {@code mcpServerConfig} requires a name but does
* not constrain it to be unique, and two elements sharing a key would overwrite one another in the
* password map and in the secret store. Names are therefore used only where they occur once in the
* collection; duplicates and unnamed elements fall back to position, which is the best available
* answer for elements that are genuinely indistinguishable.
* password map. Names are therefore used only where they occur once in the collection; duplicates
* and unnamed elements fall back to position, which is the best available answer for elements
* that are genuinely indistinguishable. A name starting with {@code #} gets one more {@code #}, so
* it never equals a position key.
*/
public static List<String> getCollectionElementIdentities(Collection<?> collection) {
return elementKeys(collection, Function.identity(), ReflectionUtil::escapePositionPrefix);
}

/**
* Names each element of a collection inside its secret id in a secrets manager.
*
* <p>Every secrets manager lowercases a secret id and drops or replaces its other characters, so
* {@code Prod} and {@code prod} would share one stored secret. A name is therefore used only where
* it is still unique when lowercased and reduced to letters and digits, and has a letter: a name like
* {@code #1} or {@code 3} could match a position key once cleaned. Any other element is named by
* position. Restoring a masked secret does not use these keys - see {@link
* #getCollectionElementIdentities}.
*/
public static List<String> getCollectionElementKeys(Collection<?> collection) {
List<String> names = new ArrayList<>(collection.size());
return elementKeys(
collection,
ReflectionUtil::secretIdForm,
name -> DIGITS_ONLY.matcher(secretIdForm(name)).matches() ? null : name);
}

/**
* Keys each element by its name where {@code form} of the name occurs once and {@code key} gives
* one, and by position otherwise.
*/
private static List<String> elementKeys(
Collection<?> collection, Function<String, String> form, UnaryOperator<String> key) {
List<String> names = collection.stream().map(ReflectionUtil::readName).toList();
Map<String, Integer> occurrences = new HashMap<>();
for (Object element : collection) {
String name = readName(element);
names.add(name);
if (name != null) {
occurrences.merge(name, 1, Integer::sum);
}
}
names.stream()
.filter(Objects::nonNull)
.forEach(name -> occurrences.merge(form.apply(name), 1, Integer::sum));
List<String> keys = new ArrayList<>(names.size());
for (int index = 0; index < names.size(); index++) {
String name = names.get(index);
boolean usable = name != null && occurrences.get(name) == 1;
keys.add(usable ? name : POSITION_KEY_PREFIX + index);
String nameKey =
name != null && occurrences.get(form.apply(name)) == 1 ? key.apply(name) : null;
keys.add(nameKey != null ? nameKey : POSITION_KEY_PREFIX + index);
}
return keys;
}

private static String escapePositionPrefix(String name) {
return name.startsWith(POSITION_KEY_PREFIX) ? POSITION_KEY_PREFIX + name : name;
}

/** A name as any secrets manager could clean it into a secret id: lowercase letters and digits. */
private static String secretIdForm(String name) {
return NOT_LETTER_OR_DIGIT.matcher(name.toLowerCase(Locale.ROOT)).replaceAll("");
}

/** The name an element reports, or null when it has none - see {@link #getCollectionElementKeys}. */
private static String readName(Object element) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public class PasswordEntityMaskerTest extends TestEntityMasker {
private static final String CUSTOM_SECRET = "plugin-secret";
private static final String TOKEN = "openmetadata-token";
private static final String ALPHA_KEY = "alpha-api-key";
private static final String GAMMA_KEY = "gamma-key";
private static final String BETA_KEY = "beta-api-key";
private static final String SFTP_PASSWORD = "openmetadata-sftp-secret";
private static final String NESTED_SECRET = "openmetadata-nested-secret";
Expand Down Expand Up @@ -243,6 +244,63 @@ void testDuplicateNamesDoNotShareASecret() {
assertEquals(BETA_KEY, restored.getServers().get(1).getApiKey());
}

/**
* Names that share one secret id once cleaned (case, punctuation) are still distinct servers: a
* masked key follows its own server through a reorder.
*/
@Test
void testNamesSharingASecretIdKeepTheirOwnKeysWhenReordered() {
McpConnection restored =
unmaskServers(
List.of(server("Prod", ALPHA_KEY), server("prod", BETA_KEY)),
List.of(server("prod", getMaskedPassword()), server("Prod", getMaskedPassword())));

assertEquals(BETA_KEY, restored.getServers().get(0).getApiKey());
assertEquals(ALPHA_KEY, restored.getServers().get(1).getApiKey());
}

/** Deleting server "1" must not hand its key to server "2", which then sits in slot 0. */
@Test
void testDigitOnlyNamesKeepTheirOwnKeysWhenOneIsDeleted() {
McpConnection restored =
unmaskServers(
List.of(server("1", ALPHA_KEY), server("2", BETA_KEY)),
List.of(server("2", getMaskedPassword())));

assertEquals(BETA_KEY, restored.getServers().getFirst().getApiKey());
}

/** A server named like a position key must not take the key of the server in that position. */
@Test
void testANameLikeAPositionKeyKeepsItsOwnKey() {
McpConnection restored =
unmaskServers(
List.of(server("#1", ALPHA_KEY), server("dup", BETA_KEY), server("dup", GAMMA_KEY)),
List.of(
server("#1", getMaskedPassword()),
server("dup", getMaskedPassword()),
server("dup", getMaskedPassword())));

assertEquals(ALPHA_KEY, restored.getServers().get(0).getApiKey());
assertEquals(BETA_KEY, restored.getServers().get(1).getApiKey());
assertEquals(GAMMA_KEY, restored.getServers().get(2).getApiKey());
}

private static McpServerConfig server(String name, String apiKey) {
return new McpServerConfig().withName(name).withApiKey(apiKey);
}

private static McpConnection unmaskServers(
List<McpServerConfig> original, List<McpServerConfig> edited) {
return (McpConnection)
EntityMaskerFactory.createEntityMasker()
.unmaskServiceConnectionConfig(
new McpConnection().withServers(edited),
new McpConnection().withServers(original),
"Mcp",
ServiceType.MCP);
}

/**
* A masked value means "keep the stored secret". Renaming a server while sending its key back
* masked leaves nothing stored under the new name, so it must be refused rather than storing the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2026 Collate
* Licensed 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.openmetadata.service.util;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.openmetadata.schema.services.connections.mcp.McpServerConfig;

/** Secret ids of list elements stay distinct; masked secrets follow the element they belong to. */
class ReflectionUtilCollectionKeysTest {

@Test
void keysUniqueNamesByName() {
assertEquals(List.of("alpha", "beta"), keys("alpha", "beta"));
}

@Test
void keysRepeatedAndMissingNamesByPosition() {
assertEquals(List.of("#0", "#1", "#2", "solo"), keys("dup", "dup", null, "solo"));
}

@Test
void neverKeysANameThatLooksLikeAPosition() {
assertEquals(List.of("#0", "#1", "#2"), keys("#1", "dup", "dup"));
}

/** Secret ids are lowercased and stripped of other characters, so these share one secret. */
@Test
void keysNamesThatShareASecretIdByPosition() {
assertEquals(List.of("#0", "#1", "other"), keys("Prod", "prod", "other"));
assertEquals(List.of("#0", "#1"), keys("prod-1", "prod_1"));
}

/** A name made only of digits would share a secret id with a position once "#" is removed. */
@Test
void keysNamesWithoutLettersByPosition() {
assertEquals(List.of("#0", "#1", "named"), keys("3", "##", "named"));
}

/** Restoring a masked secret matches the exact name, so distinct names keep their own keys. */
@Test
void identifiesDistinctNamesByNameAndEscapesAPositionLikeName() {
assertEquals(List.of("Prod", "prod", "3"), identities("Prod", "prod", "3"));
assertEquals(List.of("##1", "#1", "#2"), identities("#1", "dup", "dup"));
}

private static List<String> identities(String... names) {
return ReflectionUtil.getCollectionElementIdentities(servers(names));
}

private static List<McpServerConfig> servers(String... names) {
return Arrays.stream(names).map(name -> new McpServerConfig().withName(name)).toList();
}

private static List<String> keys(String... names) {
return ReflectionUtil.getCollectionElementKeys(servers(names));
}
}
Loading