xiangfu0 commented on code in PR #19236: URL: https://github.com/apache/pinot/pull/19236#discussion_r4795799367
########## pinot-spi/src/main/java/org/apache/pinot/spi/config/table/TableConfigRedactionUtils.java: ########## @@ -0,0 +1,1872 @@ +/** + * 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.pinot.spi.config.table; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.apache.pinot.spi.utils.JsonUtils; + + +/// Produces the display-safe form of a table config and merges that form back into the stored config on update. +/// +/// Redaction is recursive so plugin-owned stream, batch, filesystem, decoder, provider, task, and custom property maps +/// receive the same treatment as first-class table config fields. Literal values under credential-bearing keys are +/// masked, as are JAAS/connection-string assignments and credentials embedded in URI user-info or query parameters. +/// Whole-value environment and system-property placeholders keep their variable name and are never resolved by this +/// class; a placeholder default is redacted like a literal value because it is the effective value whenever the +/// variable is unset. +/// +/// Credential-bearing keys are recognized by a deny-list of suffixes on the normalized property name (see +/// `isSensitiveKey`). The policy is not fail-closed: a property whose name matches no listed suffix is displayed +/// unless its value has a recognized credential shape (URI user-info or query credential, `key=value` assignment, or +/// JSON with credential-bearing keys). A new credential property must use a recognized suffix or be added to the +/// list. +/// +/// The redaction marker is reserved in credential-bearing positions. During an update, an unchanged marker restores +/// the corresponding value from the unresolved stored config. Marker-bearing array elements are matched to their +/// exact redacted stored form instead of by array position, which supports reordering without moving one source's +/// credentials to another. Ambiguous or edited marker-bearing elements are rejected. +/// +/// This class is stateless and thread-safe. +public final class TableConfigRedactionUtils { + public static final String REDACTION_MARKER = "*****"; + + private static final Pattern URI_REFERENCE_PATTERN = Pattern.compile("(?i)(?:[a-z][a-z0-9+.-]*:)?//"); + private static final Pattern CREDENTIAL_ASSIGNMENT_PATTERN = Pattern.compile( + "(?i)(\\b([a-z][a-z0-9._-]*)\\s*=\\s*)" + + "(\\\"(?:\\\\.|[^\\\"\\\\]++)*+\\\"|'(?:\\\\.|[^'\\\\]++)*+'|" + + "\\\"(?:\\\\.|[^\\\"\\\\]++)*+(?=;|\\r|\\n|$)|" + + "'(?:\\\\.|[^'\\\\]++)*+(?=;|\\r|\\n|$)|" + + "(?:(?![&,][a-z][a-z0-9._-]*\\s*=)(?!\\s+[a-z][a-z0-9._-]*\\s*=(?!=))" + + "[^;\\r\\n'\"])+)"); + private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^a-z0-9]"); + private static final Pattern JAAS_MODULE_PATTERN = Pattern.compile( + "(?i)([a-z_$][a-z0-9_.$-]*)\\s+(?:required|requisite|sufficient|optional)\\b"); + + private TableConfigRedactionUtils() { + } + + /// Returns a deep-copied table config with displayable credentials replaced by [#REDACTION_MARKER]. + public static TableConfig redact(TableConfig tableConfig) { + Objects.requireNonNull(tableConfig, "tableConfig must not be null"); + JsonNode redacted = redactNode(tableConfig.toJsonNode(), null, false); + return toTableConfig(redacted, "Unable to create redacted table config"); + } + + /// Redacts credential-bearing assignments and URI components from an arbitrary display string. + /// + /// This is the same leaf-value policy used by [#redact(TableConfig)]. Whole placeholders and ordinary text are + /// preserved. JSON-encoded object and array values are traversed recursively so plugin option blobs receive the + /// same key policy as native property maps. + public static String redactStructuredText(String value) { + Objects.requireNonNull(value, "value must not be null"); + if (isPlaceholder(value)) { + return redactPlaceholder(value, false); + } + return redactStructuredCredentials(value); + } + + /// Returns the placeholder with its default replaced by [#REDACTION_MARKER], or the value unchanged when it is not + /// a `${VAR:default}` placeholder. The default is the effective value whenever the variable is unset, so a + /// credential-bearing field must not display it. + public static String maskPlaceholderDefault(String value) { + Objects.requireNonNull(value, "value must not be null"); + return isPlaceholder(value) ? redactPlaceholder(value, true) : value; + } + + /// Returns a copy of a flat property map with the display policy of [#redact(TableConfig)] applied to each value: + /// values under credential-bearing keys are masked and other values have embedded credentials redacted. Use it for + /// representations derived from table configs, such as minion task configs, which copy filesystem properties and + /// auth tokens out of the table config. + public static Map<String, String> redactProperties(Map<String, String> properties) { + Objects.requireNonNull(properties, "properties must not be null"); + Map<String, String> redacted = new LinkedHashMap<>(); + for (Map.Entry<String, String> property : properties.entrySet()) { + String value = property.getValue(); + redacted.put(property.getKey(), value != null ? redactText(property.getKey(), value, false) : null); + } + return redacted; + } + + /// Returns whether a property name is classified as credential-bearing by the shared display policy. + public static boolean isSensitivePropertyName(String propertyName) { + return propertyName != null && isSensitiveKey(propertyName); + } + + /// Returns whether the whole value is an unresolved environment or system-property placeholder. + public static boolean isUnresolvedPlaceholder(String value) { + return value != null && isPlaceholder(value); + } + + /// Returns a deep-copied submitted config with unchanged redaction markers restored from the unresolved stored + /// config. New literal values are retained as intentional credential replacements. + /// + /// @throws IllegalArgumentException if a marker has no unambiguous stored credential to restore + public static TableConfig restoreRedactedValues(TableConfig submitted, @Nullable TableConfig stored) { + Objects.requireNonNull(submitted, "submitted table config must not be null"); + JsonNode submittedNode = submitted.toJsonNode(); + JsonNode storedNode = stored != null ? stored.toJsonNode() : null; + JsonNode restored = restoreNode(submittedNode, storedNode, null, false); + return toTableConfig(restored, "Unable to restore redacted table config"); + } + + /// Redacts credentials from a diagnostic that was produced while handling the supplied table config. This preserves + /// useful validation context without allowing literal config credentials to reach an error response or log record. + public static String redactDiagnostic(@Nullable String diagnostic, TableConfig tableConfig) { + Objects.requireNonNull(tableConfig, "tableConfig must not be null"); + if (diagnostic == null || diagnostic.isEmpty()) { + return "Invalid table config"; + } + // A diagnostic can contain the resolved value of a placeholder even though the unresolved config never contains + // that literal. There is no sound string-level way to discover and remove such a value, so fail closed. + if (containsPlaceholder(tableConfig.toJsonNode())) { + return "Invalid table config"; + } + String redacted = redactStructuredCredentials(diagnostic); + List<String> literalCredentials = new ArrayList<>(); + collectLiteralCredentials(tableConfig.toJsonNode(), null, false, literalCredentials); + literalCredentials.sort(Comparator.comparingInt(String::length).reversed()); + for (String credential : literalCredentials) { + if (!credential.isEmpty() && !isPlaceholder(credential)) { + redacted = redacted.replace(credential, REDACTION_MARKER); + redacted = redacted.replace(jsonEscaped(credential), REDACTION_MARKER); + } + } + return redacted; + } + + private static String jsonEscaped(String value) { + try { + String json = JsonUtils.objectToString(value); + return json.substring(1, json.length() - 1); + } catch (IOException e) { + return value; + } + } + + /// Returns whether replacing the JSON Pointer target with the supplied literal would reproduce its current masked + /// representation under this policy. This permits whole-leaf JAAS and URI replacements without allowing an override + /// to change non-credential content such as a URI host or JAAS principal. + public static boolean isValidCredentialOverride(JsonNode tableConfigNode, String jsonPointer, String replacement) { + Objects.requireNonNull(tableConfigNode, "tableConfigNode must not be null"); + Objects.requireNonNull(jsonPointer, "jsonPointer must not be null"); + Objects.requireNonNull(replacement, "replacement must not be null"); + String[] segments = jsonPointer.split("/", -1); + if (segments.length <= 1 || !segments[0].isEmpty()) { + return false; + } + JsonNode node = tableConfigNode; + boolean parentSensitive = false; + String fieldName = null; + for (int i = 1; i < segments.length; i++) { + String segment = decodeJsonPointerSegment(segments[i]); + if (node.isObject()) { + fieldName = segment; + parentSensitive |= isSensitiveKey(fieldName); + node = node.get(fieldName); + } else if (node.isArray()) { + int index; + try { + index = Integer.parseInt(segment); + } catch (NumberFormatException e) { + return false; + } + node = index >= 0 && index < node.size() ? node.get(index) : null; + } else { + return false; + } + if (node == null) { + return false; + } + } + if (!node.isTextual()) { + return false; + } + String current = node.textValue(); + boolean hasPolicyMarker = isPlaceholder(current) ? isMaskedPlaceholder(current) + : parentSensitive && REDACTION_MARKER.equals(current) || containsCredentialMarker(current); + return hasPolicyMarker && redactText(fieldName, replacement, parentSensitive).equals(current); + } + + private static String decodeJsonPointerSegment(String segment) { + return segment.replace("~1", "/").replace("~0", "~"); + } + + private static boolean containsPlaceholder(JsonNode node) { + if (node.isObject()) { + for (JsonNode value : node) { + if (containsPlaceholder(value)) { + return true; + } + } + return false; + } + if (node.isArray()) { + for (JsonNode value : node) { + if (containsPlaceholder(value)) { + return true; + } + } + return false; + } + return node.isTextual() && node.textValue().contains("${"); + } + + private static void collectLiteralCredentials(JsonNode node, @Nullable String fieldName, boolean parentSensitive, + List<String> credentials) { + boolean sensitive = parentSensitive || isSensitiveKey(fieldName); + if (node.isObject()) { + for (Map.Entry<String, JsonNode> field : node.properties()) { + collectLiteralCredentials(field.getValue(), field.getKey(), sensitive, credentials); + } + return; + } + if (node.isArray()) { + for (JsonNode element : node) { + collectLiteralCredentials(element, fieldName, sensitive, credentials); + } + return; + } + if (!node.isValueNode()) { + return; + } + if (sensitive) { + if (!node.isTextual() || !isPlaceholder(node.textValue())) { + credentials.add(node.asText()); + } + } else if (node.isTextual() && !isPlaceholder(node.textValue())) { + collectStructuredLiteralCredentials(node.textValue(), credentials); + } + } + + private static void collectStructuredLiteralCredentials(String value, List<String> credentials) { + JsonNode structuredJson = tryParseStructuredJson(value); + if (structuredJson != null) { + collectLiteralCredentials(structuredJson, null, false, credentials); + return; + } + List<UriSpan> uriSpans = findUriSpans(value); + int offset = 0; + for (UriSpan span : uriSpans) { + collectAssignmentLiteralCredentials(value.substring(offset, span._start), credentials); + collectUriLiteralCredentials(value.substring(span._start, span._end), credentials); + offset = span._end; + } + collectAssignmentLiteralCredentials(value.substring(offset), credentials); + } + + private static void collectAssignmentLiteralCredentials(String value, List<String> credentials) { + Matcher matcher = CREDENTIAL_ASSIGNMENT_PATTERN.matcher(value); + while (matcher.find()) { + String credential = unquote(matcher.group(3)); + if (isSensitiveKey(matcher.group(2)) && !isPlaceholder(credential)) { + credentials.add(credential); + } + } + } + + private static void collectUriLiteralCredentials(String uri, List<String> credentials) { + UriParts parts = new UriParts(uri); + if (parts._userInfo != null) { + for (String credential : splitOutsidePlaceholders(parts._userInfo, ':')) { + if (!credential.isEmpty() && !isPlaceholder(credential)) { + credentials.add(credential); + } + } + } + collectUriParameterLiteralCredentials(parts._query, credentials); + collectUriParameterLiteralCredentials(parameterLikeFragment(parts._fragment), credentials); + } + + private static void collectUriParameterLiteralCredentials(@Nullable String parameters, + List<String> credentials) { + if (parameters == null) { + return; + } + for (String parameter : splitQuery(parameters)) { + int equalsIndex = parameter.indexOf('='); + if (equalsIndex < 0) { + continue; + } + String key = stripQueryPrefix(parameter.substring(0, equalsIndex)); + String value = parameter.substring(equalsIndex + 1); + if (isSensitiveQueryKey(key) && !isPlaceholder(value)) { + credentials.add(value); + String decoded = decodeQueryValue(value); + if (decoded != null && !decoded.equals(value)) { + credentials.add(decoded); + } + } else if (!isPlaceholder(value)) { + collectStructuredLiteralCredentials(value, credentials); + String decoded = decodeQueryValue(value); + if (decoded != null && !decoded.equals(value)) { + collectStructuredLiteralCredentials(decoded, credentials); + } + } + } + } + + private static JsonNode redactNode(JsonNode node, @Nullable String fieldName, boolean parentSensitive) { + boolean sensitive = parentSensitive || isSensitiveKey(fieldName); + if (node.isObject()) { + ObjectNode copy = JsonUtils.newObjectNode(); + for (Map.Entry<String, JsonNode> field : node.properties()) { + copy.set(field.getKey(), redactNode(field.getValue(), field.getKey(), sensitive)); + } + return copy; + } + if (node.isArray()) { + ArrayNode copy = JsonUtils.newArrayNode(); + for (JsonNode element : node) { + copy.add(redactNode(element, fieldName, sensitive)); + } + return copy; + } + if (node.isTextual()) { + return JsonUtils.objectToJsonNode(redactText(fieldName, node.textValue(), sensitive)); + } + if (sensitive && node.isValueNode() && !node.isNull()) { + return JsonUtils.objectToJsonNode(REDACTION_MARKER); + } + return node.deepCopy(); + } + + private static JsonNode restoreNode(JsonNode submitted, @Nullable JsonNode stored, @Nullable String fieldName, + boolean parentSensitive) { + boolean sensitive = parentSensitive || isSensitiveKey(fieldName); + if (submitted.isObject()) { + validateObjectSecurityIdentity((ObjectNode) submitted, stored, fieldName, sensitive); + ObjectNode copy = (ObjectNode) submitted.deepCopy(); + for (Map.Entry<String, JsonNode> field : copy.properties()) { + JsonNode storedChild = stored != null && stored.isObject() ? stored.get(field.getKey()) : null; + copy.set(field.getKey(), restoreNode(field.getValue(), storedChild, field.getKey(), sensitive)); + } + return copy; + } + if (submitted.isArray()) { + return restoreArray((ArrayNode) submitted, stored, fieldName, sensitive); + } + if (sensitive && submitted.isTextual() && REDACTION_MARKER.equals(submitted.textValue())) { + if (stored == null || stored.isContainerNode()) { + throw unresolvedMarker(); + } + return stored.deepCopy(); + } + if (!submitted.isTextual()) { + return submitted.deepCopy(); + } + + String submittedValue = submitted.textValue(); + String storedValue = stored != null && stored.isTextual() ? stored.textValue() : null; + if (isMaskedPlaceholder(submittedValue)) { + // Only the stored placeholder for the same variable can supply the masked default. + if (storedValue == null || !isPlaceholder(storedValue) + || !placeholderKey(storedValue).equals(placeholderKey(submittedValue)) + || !redactText(fieldName, storedValue, sensitive).equals(submittedValue)) { + throw unresolvedMarker(); + } + return JsonUtils.objectToJsonNode(storedValue); + } + if (isPlaceholder(submittedValue)) { + return submitted.deepCopy(); + } + if (sensitive) { + if (submittedValue.contains(REDACTION_MARKER)) { + throw unresolvedMarker(); + } + return submitted.deepCopy(); + } + + if (storedValue != null) { + String redactedStoredValue = redactText(fieldName, storedValue, false); + if (!storedValue.equals(redactedStoredValue) && submittedValue.equals(redactedStoredValue)) { + return JsonUtils.objectToJsonNode(storedValue); + } + } + if (containsCredentialMarker(submittedValue)) { + if (storedValue == null) { + throw unresolvedMarker(); + } + return JsonUtils.objectToJsonNode(restoreStructuredCredentials(submittedValue, storedValue)); + } + return submitted.deepCopy(); + } + + private static JsonNode restoreArray(ArrayNode submitted, @Nullable JsonNode stored, @Nullable String fieldName, + boolean sensitive) { + ArrayNode copy = (ArrayNode) submitted.deepCopy(); + if (stored != null && stored.isArray() && submitted.equals(redactNode(stored, fieldName, sensitive))) { + for (int i = 0; i < copy.size(); i++) { + copy.set(i, restoreNode(copy.get(i), stored.get(i), fieldName, sensitive)); + } + return copy; + } + if (canRestoreArrayByPosition(submitted, stored, fieldName, sensitive)) { + for (int i = 0; i < copy.size(); i++) { + copy.set(i, restoreNode(copy.get(i), stored.get(i), fieldName, sensitive)); + } + return copy; + } + boolean[] usedStoredElements = stored != null && stored.isArray() ? new boolean[stored.size()] : new boolean[0]; + for (int i = 0; i < copy.size(); i++) { + JsonNode submittedElement = copy.get(i); + int match = -1; + if (containsRestorableMarker(submittedElement, fieldName, sensitive)) { + match = findExactStoredArrayElement(submittedElement, stored, fieldName, sensitive, usedStoredElements); + if (match >= 0) { + usedStoredElements[match] = true; + } + } + if (match < 0 && containsRestorableMarker(submittedElement, fieldName, sensitive)) { + throw unresolvedMarker(); + } + JsonNode storedElement = match >= 0 ? stored.get(match) : null; + copy.set(i, restoreNode(submittedElement, storedElement, fieldName, sensitive)); + } + return copy; + } + + private static boolean canRestoreArrayByPosition(ArrayNode submitted, @Nullable JsonNode stored, + @Nullable String fieldName, boolean sensitive) { + if (stored == null || !stored.isArray() || submitted.size() != stored.size()) { + return false; + } + if (submitted.size() <= 1) { + if (submitted.isEmpty() || !containsRestorableMarker(submitted.get(0), fieldName, sensitive)) { + return true; + } + Map<String, String> submittedIdentity = new HashMap<>(); + collectStableArrayIdentity(submitted.get(0), "", fieldName, sensitive, submittedIdentity); + if (submittedIdentity.isEmpty()) { + return false; + } + Map<String, String> storedIdentity = new HashMap<>(); + collectStableArrayIdentity(redactNode(stored.get(0), fieldName, sensitive), "", fieldName, sensitive, + storedIdentity); + return submittedIdentity.equals(storedIdentity); + } + Set<Map<String, String>> submittedIdentities = new HashSet<>(); + for (int i = 0; i < submitted.size(); i++) { + if (!containsRestorableMarker(submitted.get(i), fieldName, sensitive)) { + continue; + } + Map<String, String> submittedIdentity = new HashMap<>(); + collectStableArrayIdentity(submitted.get(i), "", fieldName, sensitive, submittedIdentity); + if (submittedIdentity.isEmpty()) { + return false; + } + Map<String, String> storedIdentity = new HashMap<>(); + collectStableArrayIdentity(redactNode(stored.get(i), fieldName, sensitive), "", fieldName, sensitive, + storedIdentity); + if (!submittedIdentity.equals(storedIdentity) || !submittedIdentities.add(submittedIdentity)) { + return false; + } + } + Set<Map<String, String>> storedIdentities = new HashSet<>(); + for (int i = 0; i < stored.size(); i++) { + JsonNode redactedStored = redactNode(stored.get(i), fieldName, sensitive); + if (!containsRestorableMarker(redactedStored, fieldName, sensitive)) { + continue; + } + Map<String, String> identity = new HashMap<>(); + collectStableArrayIdentity(redactedStored, "", fieldName, sensitive, identity); + if (identity.isEmpty()) { + return false; + } + if (!storedIdentities.add(identity)) { + return false; + } + } + return true; + } + + private static int findExactStoredArrayElement(JsonNode submittedElement, @Nullable JsonNode stored, + @Nullable String fieldName, boolean sensitive, boolean[] usedStoredElements) { + if (stored == null || !stored.isArray()) { + return -1; + } + int candidate = -1; + int candidateCount = 0; + for (int i = 0; i < stored.size(); i++) { + if (usedStoredElements[i]) { + continue; + } + if (!submittedElement.equals(redactNode(stored.get(i), fieldName, sensitive))) { + continue; + } + candidate = i; + candidateCount++; + } + return candidateCount == 1 ? candidate : -1; + } + + private static void collectStableArrayIdentity(JsonNode node, String path, @Nullable String fieldName, + boolean parentSensitive, Map<String, String> identity) { + boolean sensitive = parentSensitive || isSensitiveKey(fieldName); + if (node.isObject()) { + for (Map.Entry<String, JsonNode> field : node.properties()) { + String childPath = path.isEmpty() ? field.getKey() : path + "." + field.getKey(); + collectStableArrayIdentity(field.getValue(), childPath, field.getKey(), sensitive, identity); + } + return; + } + if (node.isArray()) { + for (int i = 0; i < node.size(); i++) { + collectStableArrayIdentity(node.get(i), path + "[" + i + "]", fieldName, sensitive, identity); + } + return; + } + if (!sensitive && isStableArrayIdentityKey(fieldName) && !containsRestorableMarker(node, fieldName, false)) { + identity.put(path, stableIdentityValue(node)); + } + } + + private static boolean isStableArrayIdentityKey(@Nullable String fieldName) { + if (fieldName == null) { + return false; + } + String normalized = normalizeKey(fieldName); + return normalized.equals("name") || normalized.equals("id") || normalized.equals("type") + || normalized.endsWith("tablename") || normalized.endsWith("tasktype") + || normalized.endsWith("streamtype") || normalized.endsWith("topic") + || normalized.endsWith("topicname") || normalized.endsWith("endpoint") + || normalized.endsWith("host") || normalized.endsWith("server") || normalized.endsWith("url") + || normalized.endsWith("uri") || normalized.endsWith("path") || normalized.endsWith("bootstrapservers") + || isExecutableClassSelectorKey(normalized); + } + + private static void validateObjectSecurityIdentity(ObjectNode submitted, @Nullable JsonNode stored, + @Nullable String fieldName, boolean parentSensitive) { + if (stored == null || !stored.isObject() + || !containsRestorableMarker(submitted, fieldName, parentSensitive)) { + return; + } + ObjectNode redactedStored = (ObjectNode) redactNode(stored, fieldName, parentSensitive); + rejectNormalizedKeyAliases(submitted); + Map<String, String> submittedIdentity = new HashMap<>(); + collectObjectSecurityIdentity(submitted, "", fieldName, parentSensitive, submittedIdentity); + Map<String, String> storedIdentity = new HashMap<>(); + collectObjectSecurityIdentity(redactedStored, "", fieldName, parentSensitive, storedIdentity); + if (!submittedIdentity.equals(storedIdentity)) { + throw unresolvedMarker(); + } + validateCredentialPairs(submitted, redactedStored); + validateCredentialEndpointBindings(submitted, redactedStored); + } + + private static void rejectNormalizedKeyAliases(JsonNode node) { + if (node.isObject()) { + Map<String, String> normalizedToRaw = new HashMap<>(); + for (Map.Entry<String, JsonNode> field : node.properties()) { + String normalized = normalizeKey(field.getKey()); + String previous = normalizedToRaw.putIfAbsent(normalized, field.getKey()); + if (previous != null && !previous.equals(field.getKey())) { + throw unresolvedMarker(); + } + rejectNormalizedKeyAliases(field.getValue()); + } + } else if (node.isArray()) { + for (JsonNode element : node) { + rejectNormalizedKeyAliases(element); + } + } + } + + private static void collectObjectSecurityIdentity(JsonNode node, String path, @Nullable String fieldName, + boolean parentSensitive, Map<String, String> identity) { + if (node.isObject()) { + for (Map.Entry<String, JsonNode> field : node.properties()) { + String childPath = path.isEmpty() ? field.getKey() : path + "." + field.getKey(); + JsonNode value = field.getValue(); + if (isObjectOwnerIdentityField(field.getKey()) && value.isValueNode() + && !containsRestorableMarker(value, field.getKey(), parentSensitive)) { + identity.put(childPath, stableIdentityValue(value)); + } + collectObjectSecurityIdentity(value, childPath, field.getKey(), parentSensitive, identity); + } + return; + } + // Array elements are matched and validated independently by restoreArray. + } + + private static boolean isObjectOwnerIdentityField(@Nullable String fieldName) { + if (fieldName == null) { + return false; + } + String normalized = normalizeKey(fieldName); + return normalized.equals("user") || normalized.equals("username") || normalized.equals("principal") + || normalized.equals("accountname") + || normalized.endsWith("brokerlist") || normalized.endsWith("bootstrapservers") + || isExecutableClassSelectorKey(normalized) + || normalized.endsWith("clientemail"); + } + + private static boolean isExecutableClassSelectorKey(String normalizedKey) { + return normalizedKey.equals("class") || normalizedKey.endsWith("interceptorclasses") + || normalizedKey.endsWith("metricreporters") || normalizedKey.endsWith("partitionassignmentstrategy") + || normalizedKey.endsWith("deserializer") || normalizedKey.endsWith("serializer") + || normalizedKey.endsWith("partitionerclass") || normalizedKey.endsWith("oauthprovidertype") + || normalizedKey.contains("fsazureaccountoauthprovidertype") + || normalizedKey.endsWith("securityproviders") + || normalizedKey.endsWith("classname") + || normalizedKey.endsWith("factoryclass") || normalizedKey.endsWith("providerclass") + || normalizedKey.endsWith("decoderclass") || normalizedKey.endsWith("callbackhandlerclass") + || normalizedKey.endsWith("loginmoduleclass") || normalizedKey.endsWith("loginclass") + || normalizedKey.endsWith("credentialsprovider") + || normalizedKey.endsWith("credentialprovider"); + } + + private static void validateCredentialPairs(ObjectNode submitted, ObjectNode redactedStored) { + Map<String, JsonNode> submittedFields = normalizedFields(submitted); + Map<String, JsonNode> storedFields = normalizedFields(redactedStored); + validateCredentialPair(submittedFields, storedFields, + List.of("accesskey", "accesskeyid", "awsaccesskeyid"), List.of("secretkey", "secretaccesskey")); + validateCredentialPair(submittedFields, storedFields, + List.of("clientid", "applicationid"), List.of("clientsecret")); + validateCredentialPair(submittedFields, storedFields, + List.of("sharedaccesskeyname", "sharedaccesspolicyname"), List.of("sharedaccesskey")); + validateCredentialPair(submittedFields, storedFields, + List.of("username", "user", "principal", "accountname"), + List.of("passwords", "password", "passwd", "pwd", "passphrases", "passphrase")); + for (Map.Entry<String, JsonNode> field : submitted.properties()) { + JsonNode storedChild = redactedStored.get(field.getKey()); + if (field.getValue().isObject() && storedChild != null && storedChild.isObject()) { + validateCredentialPairs((ObjectNode) field.getValue(), (ObjectNode) storedChild); + } + } + } + + private static void validateCredentialEndpointBindings(ObjectNode submitted, ObjectNode redactedStored) { + Map<String, String> submittedEndpoints = collectEndpointBindings(submitted); + Map<String, String> storedEndpoints = collectEndpointBindings(redactedStored); + for (Map.Entry<String, JsonNode> field : submitted.properties()) { + String normalizedKey = normalizeKey(field.getKey()); + String credentialSuffix = sensitiveBindingSuffix(normalizedKey); + if (credentialSuffix == null || !containsRestorableMarker(field.getValue(), field.getKey(), false)) { + continue; + } + String prefix = normalizedKey.substring(0, normalizedKey.length() - credentialSuffix.length()); + if (!endpointBindingsForPrefix(submittedEndpoints, prefix) + .equals(endpointBindingsForPrefix(storedEndpoints, prefix))) { + throw unresolvedMarker(); + } + } + } + + private static Map<String, String> collectEndpointBindings(ObjectNode node) { + Map<String, String> endpoints = new HashMap<>(); + for (Map.Entry<String, JsonNode> field : node.properties()) { + String normalizedKey = normalizeKey(field.getKey()); + String endpointSuffix = endpointBindingSuffix(normalizedKey); + JsonNode value = field.getValue(); + if (endpointSuffix != null && value.isValueNode() + && !containsRestorableMarker(value, field.getKey(), false)) { + String prefix = normalizedKey.substring(0, normalizedKey.length() - endpointSuffix.length()); + endpoints.put(prefix + ':' + normalizedKey, stableIdentityValue(value)); + } + } + return endpoints; + } + + private static Map<String, String> endpointBindingsForPrefix(Map<String, String> bindings, String prefix) { + Map<String, String> result = new HashMap<>(); + String mapPrefix = prefix + ':'; + for (Map.Entry<String, String> binding : bindings.entrySet()) { + if (binding.getKey().startsWith(mapPrefix)) { + result.put(binding.getKey(), binding.getValue()); + } + } + return result; + } + + @Nullable + private static String endpointBindingSuffix(String normalizedKey) { + return matchingSuffix(normalizedKey, + List.of("bootstrapservers", "serviceurl", "baseurl", "endpoint", "server", "host", "url", "uri")); + } + + @Nullable + private static String sensitiveBindingSuffix(String normalizedKey) { + return matchingSuffix(normalizedKey, List.of( + "secretaccesskey", "sharedaccesskey", "accesskeyid", "accesskey", "secretkey", "privatekey", + "accountkey", "storagekey", "clientkey", "hmackey", "encryptionkey", "signingkey", "apikey", + "passphrases", "passphrase", "passwords", "password", "credentials", "credential", "secrets", + "secret", "tokens", "token", "passwd", "pwd", "signature", "authorization", "authheader", "auth")); + } + + private static Map<String, JsonNode> normalizedFields(ObjectNode node) { + Map<String, JsonNode> fields = new HashMap<>(); + for (Map.Entry<String, JsonNode> field : node.properties()) { + fields.put(normalizeKey(field.getKey()), field.getValue()); + } + return fields; + } + + private static void validateCredentialPair(Map<String, JsonNode> submitted, Map<String, JsonNode> stored, + List<String> identityKeys, List<String> secretKeys) { + for (Map.Entry<String, JsonNode> secret : submitted.entrySet()) { + String secretSuffix = matchingSuffix(secret.getKey(), secretKeys); + if (secretSuffix == null || !containsRestorableMarker(secret.getValue(), null, true)) { + continue; + } + String prefix = secret.getKey().substring(0, secret.getKey().length() - secretSuffix.length()); + JsonNode submittedIdentity = firstFieldWithPrefix(submitted, identityKeys, prefix); + JsonNode storedIdentity = firstFieldWithPrefix(stored, identityKeys, prefix); + if (!Objects.equals(submittedIdentity, storedIdentity)) { + throw unresolvedMarker(); + } + } + } + + @Nullable + private static JsonNode firstFieldWithPrefix(Map<String, JsonNode> fields, List<String> keys, String prefix) { + for (Map.Entry<String, JsonNode> field : fields.entrySet()) { + String suffix = matchingSuffix(field.getKey(), keys); + if (suffix != null && field.getKey().substring(0, field.getKey().length() - suffix.length()).equals(prefix)) { + return field.getValue(); + } + } + return null; + } + + @Nullable + private static String matchingSuffix(String normalizedKey, List<String> suffixes) { + for (String suffix : suffixes) { + if (normalizedKey.equals(suffix) || normalizedKey.endsWith(suffix)) { + return suffix; + } + } + return null; + } + + private static String stableIdentityValue(JsonNode node) { + if (node.isTextual() && URI_REFERENCE_PATTERN.matcher(node.textValue()).lookingAt()) { + return uriIdentity(node.textValue()); + } + return node.toString(); + } + + private static boolean containsRestorableMarker(JsonNode node, @Nullable String fieldName, + boolean parentSensitive) { + boolean sensitive = parentSensitive || isSensitiveKey(fieldName); + if (node.isObject()) { + for (Map.Entry<String, JsonNode> field : node.properties()) { + if (containsRestorableMarker(field.getValue(), field.getKey(), sensitive)) { + return true; + } + } + return false; + } + if (node.isArray()) { + for (JsonNode element : node) { + if (containsRestorableMarker(element, fieldName, sensitive)) { + return true; + } + } + return false; + } + if (!node.isTextual()) { + return false; + } + String value = node.textValue(); + if (isPlaceholder(value)) { + return isMaskedPlaceholder(value); + } + if (!value.contains(REDACTION_MARKER)) { + return false; + } + return sensitive || containsCredentialMarker(value); + } + + private static IllegalArgumentException unresolvedMarker() { + return new IllegalArgumentException("Redacted credential has no unambiguous unchanged stored value"); + } + + private static String redactText(@Nullable String fieldName, String value, boolean sensitive) { + boolean sensitiveValue = sensitive || isSensitiveKey(fieldName); + if (isPlaceholder(value)) { + return redactPlaceholder(value, sensitiveValue); + } + if (sensitiveValue) { + return REDACTION_MARKER; + } + return redactStructuredCredentials(value); + } + + /// Redacts the default segment of a `${VAR:default}` placeholder: wholesale under a credential-bearing key, and by + /// the structured-text policy elsewhere so a URI or assignment default still hides its credentials. The variable + /// name is preserved because the restore path matches on it. + private static String redactPlaceholder(String placeholder, boolean sensitive) { + int defaultStart = placeholderDefaultStart(placeholder); + if (defaultStart < 0 || defaultStart == placeholder.length() - 1) { + return placeholder; + } + String defaultValue = placeholder.substring(defaultStart, placeholder.length() - 1); + String redactedDefault = sensitive ? REDACTION_MARKER : redactStructuredCredentials(defaultValue); + return placeholder.substring(0, defaultStart) + redactedDefault + "}"; + } + + /// Returns the index at which the default of a placeholder starts, or -1 when it declares no default. + private static int placeholderDefaultStart(String placeholder) { + int separator = placeholder.indexOf(':', 2); + return separator < 0 ? -1 : separator + 1; + } + + private static String placeholderKey(String placeholder) { + int separator = placeholder.indexOf(':', 2); + return placeholder.substring(2, separator < 0 ? placeholder.length() - 1 : separator); + } + + /// Returns whether a placeholder's default carries [#REDACTION_MARKER], meaning [#redactPlaceholder] produced it + /// and only the stored config can restore the default. + private static boolean isMaskedPlaceholder(String value) { + if (!isPlaceholder(value)) { + return false; + } + int defaultStart = placeholderDefaultStart(value); + return defaultStart >= 0 && value.substring(defaultStart, value.length() - 1).contains(REDACTION_MARKER); + } + + private static boolean isPlaceholder(String value) { + if (value.length() < 4 || !value.startsWith("${")) { + return false; + } + + int keyEnd = value.indexOf(':', 2); + if (keyEnd < 0) { + keyEnd = value.length() - 1; + } + if (keyEnd == 2) { + return false; + } + for (int i = 2; i < keyEnd; i++) { + char current = value.charAt(i); + if (Character.isWhitespace(current) || current == '{' || current == '}') { + return false; + } + } + return value.endsWith("}"); + } + + private static boolean isSensitiveKey(@Nullable String fieldName) { + if (fieldName == null) { + return false; + } + String normalized = normalizeKey(fieldName); + if (normalized.isEmpty() || normalized.equals("usekeytab")) { + return false; + } + return normalized.endsWith("password") || normalized.endsWith("passwords") + || normalized.endsWith("passwd") || normalized.endsWith("pwd") + || normalized.endsWith("passphrase") || normalized.endsWith("passphrases") + || normalized.endsWith("secret") || normalized.endsWith("secrets") + || normalized.endsWith("token") || normalized.endsWith("tokens") + || normalized.endsWith("credential") || normalized.endsWith("credentials") + || normalized.endsWith("accesskey") || normalized.endsWith("accesskeyid") + || normalized.endsWith("apikey") || normalized.endsWith("secretkey") + || normalized.endsWith("privatekey") || normalized.endsWith("accountkey") + || normalized.endsWith("storagekey") || normalized.endsWith("sharedkey") + || normalized.endsWith("masterkey") || normalized.endsWith("clientkey") + || normalized.endsWith("hmackey") || normalized.endsWith("encryptionkey") + || normalized.endsWith("signingkey") || normalized.endsWith("keytab") + || normalized.equals("sig") || normalized.endsWith("signature") + || normalized.equals("auth") + || normalized.endsWith("authorization") || normalized.endsWith("authheader") + || normalized.endsWith("serviceaccountjson") || normalized.endsWith("credentialjson") + || normalized.equals("gcpkey") || normalized.equals("jsonkey") Review Comment: The normalized jsonKey check now matches prefixed property names. The test covers masking and restoring input.fs.prop.jsonKey. Updated in 8ea94f4d7b. ########## pinot-spi/src/main/java/org/apache/pinot/spi/config/table/TableConfigRedactionUtils.java: ########## @@ -0,0 +1,1872 @@ +/** + * 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.pinot.spi.config.table; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.apache.pinot.spi.utils.JsonUtils; + + +/// Produces the display-safe form of a table config and merges that form back into the stored config on update. +/// +/// Redaction is recursive so plugin-owned stream, batch, filesystem, decoder, provider, task, and custom property maps +/// receive the same treatment as first-class table config fields. Literal values under credential-bearing keys are +/// masked, as are JAAS/connection-string assignments and credentials embedded in URI user-info or query parameters. +/// Whole-value environment and system-property placeholders keep their variable name and are never resolved by this +/// class; a placeholder default is redacted like a literal value because it is the effective value whenever the +/// variable is unset. +/// +/// Credential-bearing keys are recognized by a deny-list of suffixes on the normalized property name (see +/// `isSensitiveKey`). The policy is not fail-closed: a property whose name matches no listed suffix is displayed +/// unless its value has a recognized credential shape (URI user-info or query credential, `key=value` assignment, or +/// JSON with credential-bearing keys). A new credential property must use a recognized suffix or be added to the +/// list. +/// +/// The redaction marker is reserved in credential-bearing positions. During an update, an unchanged marker restores +/// the corresponding value from the unresolved stored config. Marker-bearing array elements are matched to their +/// exact redacted stored form instead of by array position, which supports reordering without moving one source's +/// credentials to another. Ambiguous or edited marker-bearing elements are rejected. +/// +/// This class is stateless and thread-safe. +public final class TableConfigRedactionUtils { + public static final String REDACTION_MARKER = "*****"; + + private static final Pattern URI_REFERENCE_PATTERN = Pattern.compile("(?i)(?:[a-z][a-z0-9+.-]*:)?//"); + private static final Pattern CREDENTIAL_ASSIGNMENT_PATTERN = Pattern.compile( Review Comment: URI discovery now locates double slashes directly and scans the adjacent scheme once. On my machine a 40 KB ordinary URL took about 1–1.4 ms per pass in a local smoke check. Updated in 8ea94f4d7b. ########## pinot-controller/src/main/resources/app/requests/index.ts: ########## @@ -71,8 +71,15 @@ export const getTenant = (name: string): Promise<AxiosResponse<TableData>> => export const getTenantTable = (name: string): Promise<AxiosResponse<TableName>> => baseApi.get(`/tenants/${name}/tables`); +// Ask for the versioned redacted table config envelope so unchanged masked credentials can be submitted back with +// the versions GET returned. The application/json fallback keeps the UI working against older controllers, which +// return the table config map directly. +const tableConfigHeaders = { + 'Accept': 'application/vnd.apache.pinot.redacted-table-config-v1+json, application/json;q=0.9' Review Comment: The interceptor sets Authorization on the existing AxiosHeaders. I checked that Basic and OIDC both preserve the requested Accept media type and a second header. The UI type-check passes. Updated in 8ea94f4d7b. ########## pinot-controller/src/main/java/org/apache/pinot/controller/api/access/BaseBasicAuthAccessControl.java: ########## @@ -105,6 +105,9 @@ private void warnOnceAboutTableScope(P principal, String endpointUrl) { @Override public final boolean hasAccess(HttpHeaders httpHeaders, TargetType targetType, String targetId, String action) { Optional<P> principal = getPrincipal(httpHeaders); + if (Actions.Cluster.GET_ZNODE.equals(action)) { + return principal.filter(p -> p.hasExplicitActionPermission(Actions.Cluster.GET_ZNODE)).isPresent(); Review Comment: Added upgrade guidance in the PR description and basic-auth configuration Javadoc. It covers the UI views, the unrestricted table scope, a read-only grant example, and the need to list any other CRUD permissions the operator needs. Updated in 8ea94f4d7b. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
