This is an automated email from the ASF dual-hosted git repository.

jerryshao 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 e20a6b0558 [#14978] fix(core): Mask sensitive local job command logs 
including --conf (#14979)
e20a6b0558 is described below

commit e20a6b05588f8136ab5f4042326d1d86c578fb4a
Author: MaSai <[email protected]>
AuthorDate: Mon Nov 16 19:32:14 2026 +0800

    [#14978] fix(core): Mask sensitive local job command logs including --conf 
(#14979)
    
    ### What changes were proposed in this pull request?
    
    - Mask `--updater-options` / `--spark-conf` JSON bags before INFO
    logging in `SparkProcessBuilder` and `ShellProcessBuilder`;
    `ProcessBuilder` still gets the plaintext list.
    - Also mask `--conf key=value` / `--conf=key=value` in
    `maskSensitiveArguments` when the key matches
    `SecretPropertyUtils.isSensitivePropertyKey` (covers template `configs`
    emitted as `--conf`).
    - Keep malformed-JSON masking WARN messages as fixed text (no
    `e.toString()`), so Jackson exception text cannot re-leak credentials.
    - Add unit tests for sensitive `--conf` masking and a log-capture
    regression that asserts malformed credential input is absent from
    emitted log messages.
    
    ### Why are the changes needed?
    
    Local executor INFO logs previously joined the raw command and leaked
    credential JSON that API/event paths already mask. Custom templates can
    also put catalog credentials in `configs` (`--conf`). Separately, WARN
    logs during malformed JSON masking could embed the original input via
    Jackson exception text.
    
    Fixes #14978
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. Log/API display masking is stronger; job execution behavior is
    unchanged.
    
    ### How was this patch tested?
    
    `./gradlew spotlessApply :core:test --tests
    org.apache.gravitino.job.TestJobRuntimeTemplateMaskUtils --tests
    org.apache.gravitino.connector.TestHiddenPropertyMaskUtils -PskipITs`
    
    ---------
    
    Co-authored-by: Cursor <[email protected]>
---
 .../connector/HiddenPropertyMaskUtils.java         |  57 ++---
 .../gravitino/job/JobRuntimeTemplateMaskUtils.java | 130 +++++++++--
 .../gravitino/job/local/ShellProcessBuilder.java   |   6 +-
 .../gravitino/job/local/SparkProcessBuilder.java   |   4 +-
 .../connector/TestHiddenPropertyMaskUtils.java     |  28 ++-
 .../job/TestJobRuntimeTemplateMaskUtils.java       | 238 +++++++++++++++++++--
 6 files changed, 392 insertions(+), 71 deletions(-)

diff --git 
a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
 
b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
index c14487402d..163b06a2cb 100644
--- 
a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
+++ 
b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
@@ -75,10 +75,19 @@ public final class HiddenPropertyMaskUtils {
 
   /**
    * Mapper for nest-JSON masking. Uses {@link JsonNode} with big-decimal 
floats so rewritten JSON
-   * keeps numeric fidelity better than {@code Map}/{@code List} round-trips.
+   * keeps numeric fidelity better than {@code Map}/{@code List} round-trips. 
{@link
+   * DeserializationFeature#FAIL_ON_TRAILING_TOKENS} rejects concatenated 
values (for example {@code
+   * {} {"password":"secret"}}), and {@link 
DeserializationFeature#FAIL_ON_READING_DUP_TREE_KEY}
+   * rejects duplicate object fields (for example {@code 
{"config":{"password":"x"},"config":{}}}),
+   * so a dropped earlier field cannot leave a secret in the original string 
when the walk sees only
+   * the last value.
    */
   private static final ObjectMapper NEST_JSON_MAPPER =
-      
JsonUtils.anyFieldMapper().copy().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
+      JsonUtils.anyFieldMapper()
+          .copy()
+          .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+          .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+          .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
 
   private HiddenPropertyMaskUtils() {}
 
@@ -200,17 +209,16 @@ public final class HiddenPropertyMaskUtils {
   }
 
   /**
-   * Parses {@code value} as JSON and masks sensitive-named keys in objects 
(recursively through
-   * nested objects and arrays). Blank strings and non-JSON plain text 
(trimmed value does not start
-   * with '{' or '[') are returned unchanged. Values that look like a JSON 
object/array but fail to
-   * parse are replaced with {@link #MASKED_VALUE}. Scalar JSON roots are 
returned unchanged.
+   * Parses {@code value} as exactly one JSON object and masks sensitive-named 
keys. Used for
+   * credential JSON bags such as job {@code updater_options} / {@code 
spark_conf}.
    *
-   * <p>Useful when a caller already knows a string is a nested JSON map (for 
example a CLI argument
-   * following {@code --spark-conf}).
+   * <p>Useful when a caller already knows a string should be a nested JSON 
map (for example a CLI
+   * argument following {@code --spark-conf}).
    *
    * @param value JSON string to mask; may be null
-   * @return masked JSON, {@link #MASKED_VALUE} on object/array parse failure, 
or the original value
-   *     when blank, plain non-JSON, scalar JSON, or null
+   * @return masked JSON object, {@link #MASKED_VALUE} when the value is not 
exactly one JSON object
+   *     (parse failure, trailing tokens, duplicate fields, array, or scalar), 
the original value
+   *     when blank, or null when {@code value} is null
    */
   @Nullable
   public static String maskSensitiveJsonValue(@Nullable String value) {
@@ -221,34 +229,29 @@ public final class HiddenPropertyMaskUtils {
   }
 
   /**
-   * Parses {@code value} as JSON and masks sensitive-named keys in objects 
(recursively through
-   * nested objects and arrays). Blank / plain non-JSON strings are returned 
unchanged. Malformed
-   * object/array-looking JSON is replaced with {@link #MASKED_VALUE}.
+   * Parses {@code value} as exactly one JSON object (no trailing tokens) and 
masks sensitive-named
+   * keys recursively through nested objects and arrays inside that object. 
Blank strings are
+   * returned unchanged. Anything else — malformed JSON, concatenated values 
such as {@code {}
+   * {"password":"secret"}}, duplicate object fields, {@code true {...}}, root 
arrays, or scalars —
+   * becomes {@link #MASKED_VALUE}.
    */
   private static String maskNestedJsonValue(String value) {
     // Empty / whitespace-only values carry no secret (common for unresolved 
{{spark_conf:-}}).
     if (StringUtils.isBlank(value)) {
       return value;
     }
-    // Bare words (e.g. --options=verbose) are not JSON maps; do not treat 
parse failure as secret.
-    String trimmed = value.trim();
-    if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
-      return value;
-    }
     try {
       JsonNode root = NEST_JSON_MAPPER.readTree(value);
-      if (!root.isObject() && !root.isArray()) {
-        // Scalar JSON (string/number/boolean/null) — nothing to walk by key 
name.
-        return value;
+      // Credential bags are JSON maps. Scalars/arrays/concatenated values are 
not mask-walked.
+      if (!root.isObject()) {
+        return MASKED_VALUE;
       }
       MaskedJson masked = maskJsonNode(root);
       return masked.changed ? 
NEST_JSON_MAPPER.writeValueAsString(masked.value) : value;
-    } catch (Exception e) {
-      // Malformed object/array JSON on a caller-declared nest key — do not 
leave a secret blob.
-      // Do not log the value; it may contain credentials.
-      LOG.warn(
-          "Replacing malformed nest JSON with masked placeholder after parse 
failure: {}",
-          e.toString());
+    } catch (Exception ignored) {
+      // Malformed / trailing-token / duplicate-key JSON — do not leave a 
secret blob.
+      // Fixed message only: Jackson exception text can embed the input (and 
credentials).
+      LOG.warn("Replacing malformed nest JSON with masked placeholder after 
parse failure");
       return MASKED_VALUE;
     }
   }
diff --git 
a/core/src/main/java/org/apache/gravitino/job/JobRuntimeTemplateMaskUtils.java 
b/core/src/main/java/org/apache/gravitino/job/JobRuntimeTemplateMaskUtils.java
index cd1ad5cc4d..f066b3e748 100644
--- 
a/core/src/main/java/org/apache/gravitino/job/JobRuntimeTemplateMaskUtils.java
+++ 
b/core/src/main/java/org/apache/gravitino/job/JobRuntimeTemplateMaskUtils.java
@@ -29,31 +29,39 @@ import 
org.apache.gravitino.connector.HiddenPropertyMaskUtils;
 import org.apache.gravitino.dto.job.JobTemplateDTO;
 import org.apache.gravitino.dto.job.ShellJobTemplateDTO;
 import org.apache.gravitino.dto.job.SparkJobTemplateDTO;
+import org.apache.gravitino.secret.SecretPropertyUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
- * Display-masks credentials in a Spark job's {@code updater_options} and 
{@code spark_conf} JSON
- * before that JSON is returned by an API or placed on an event. 
Sensitive-named keys inside the
- * JSON are replaced with {@link HiddenPropertyMaskUtils#MASKED_VALUE}. This 
is not encryption: the
- * stored runtime template and the map passed to job execution stay plaintext.
+ * Display-masks credentials before a runtime template is returned by an API, 
placed on an event, or
+ * written to a local-executor INFO log. Sensitive-named keys are replaced 
with {@link
+ * HiddenPropertyMaskUtils#MASKED_VALUE}. This is not encryption: the stored 
runtime template and
+ * the command list / map passed to job execution stay plaintext.
  *
- * <p>Only those two JSON bags are masked.
+ * <p>What {@link #maskSensitiveArguments} masks on a command or argument list:
  *
  * <ul>
  *   <li>Spark template arguments {@code --updater-options} and {@code 
--spark-conf}. One list
  *       element is one argument, so the JSON is the whole next element (or 
the text after {@code =}
- *       in {@code --flag=json}). It is not split on whitespace.
- *   <li>{@code jobConf} entries {@code updater_options} and {@code 
spark_conf} on the run-job
- *       events. Those names are the Spark template placeholders {@code 
{{updater_options}}} and
- *       {@code {{spark_conf}}}, not the hyphenated CLI flags.
+ *       in {@code --flag=json}). It is not split on whitespace. The same walk 
applies to a full
+ *       process command list (for example {@code spark-submit ...}) used only 
for logging.
+ *   <li>{@code --conf key=value} and {@code --conf=key=value} when {@code 
key} matches {@link
+ *       SecretPropertyUtils#isSensitivePropertyKey(String)}. Local Spark 
emits template {@code
+ *       configs} as {@code --conf}. Non-sensitive {@code --conf} entries stay 
plaintext.
  * </ul>
  *
- * <p>Shell jobs have neither bag. Other arguments ({@code --password}, {@code 
--conf}, {@code -c},
- * {@code --options}) and map fields ({@code environments}, {@code 
customFields}, Spark {@code
- * configs}) are copied unchanged. A blank value, which is what {@code 
{{spark_conf:-}}} becomes
- * when unset, is left unchanged.
+ * <p>{@link #maskSensitiveJobConf} masks {@code jobConf} entries {@code 
updater_options} and {@code
+ * spark_conf} on run-job events (placeholder names, not the hyphenated CLI 
flags).
+ *
+ * <p>Other arguments ({@code --password}, {@code -c}, {@code --options}) and 
map fields ({@code
+ * environments}, {@code customFields}, Spark {@code configs} as a map) are 
copied unchanged. A
+ * blank value, which is what {@code {{spark_conf:-}}} becomes when unset, is 
left unchanged.
  */
 public final class JobRuntimeTemplateMaskUtils {
 
+  private static final Logger LOG = 
LoggerFactory.getLogger(JobRuntimeTemplateMaskUtils.class);
+
   /**
    * Argument flags whose following value is a JSON map that may contain 
credentials.
    *
@@ -65,6 +73,9 @@ public final class JobRuntimeTemplateMaskUtils {
   static final Set<String> JSON_ARGUMENT_FLAGS =
       ImmutableSet.of("--updater-options", "--spark-conf");
 
+  /** Spark-submit flag that carries a single {@code key=value} config from 
template configs. */
+  static final String CONF_ARGUMENT_FLAG = "--conf";
+
   /**
    * {@code jobConf} keys for the Spark placeholders {@code 
{{updater_options}}} and {@code
    * {{spark_conf}}}. The CLI flags in {@link #JSON_ARGUMENT_FLAGS} use 
hyphens and are a different
@@ -102,9 +113,9 @@ public final class JobRuntimeTemplateMaskUtils {
   }
 
   /**
-   * Returns a copy of a Spark runtime template with {@code --updater-options} 
and {@code
-   * --spark-conf} JSON masked, or {@code null} when the input is null. Spark 
{@code configs},
-   * {@code environments}, and {@code customFields} are not masked. A Shell 
template is rebuilt with
+   * Returns a copy of a runtime template with {@link #maskSensitiveArguments} 
applied to {@code
+   * arguments}, or {@code null} when the input is null. Spark {@code 
configs}, {@code
+   * environments}, and {@code customFields} maps are not masked. A Shell 
template is rebuilt with
    * the same argument walk so a hand-written template that uses these flags 
does not leak; built-in
    * credential JSON lives on the Spark template.
    *
@@ -158,11 +169,21 @@ public final class JobRuntimeTemplateMaskUtils {
   }
 
   /**
-   * Masks the JSON value of {@link #JSON_ARGUMENT_FLAGS}. The value is one 
list element, including
-   * any spaces inside the JSON. Other arguments are copied unchanged.
+   * Returns a copy of {@code arguments} with credential-bearing values 
masked: the JSON value of
+   * {@link #JSON_ARGUMENT_FLAGS}, and {@link #CONF_ARGUMENT_FLAG} entries 
whose key matches {@link
+   * SecretPropertyUtils#isSensitivePropertyKey(String)}. The JSON value is 
one list element,
+   * including any spaces inside the JSON. Other arguments are copied 
unchanged. Does not mutate the
+   * input; callers must pass the original list to process execution and use 
this copy only for
+   * display (API, events, or logs).
+   *
+   * <p>Masking is per argument: if one JSON value fails, that slot becomes 
{@link
+   * HiddenPropertyMaskUtils#MASKED_VALUE} and later arguments are still 
walked and masked.
+   *
+   * @param arguments process command tokens or template arguments; may be null
+   * @return a masked copy, or null when {@code arguments} is null
    */
   @Nullable
-  private static List<String> maskSensitiveArguments(@Nullable List<String> 
arguments) {
+  public static List<String> maskSensitiveArguments(@Nullable List<String> 
arguments) {
     if (arguments == null) {
       return null;
     }
@@ -171,23 +192,39 @@ public final class JobRuntimeTemplateMaskUtils {
     }
     List<String> result = new ArrayList<>(arguments.size());
     boolean maskNextJson = false;
+    boolean maskNextConf = false;
     for (String arg : arguments) {
       if (maskNextJson) {
         maskNextJson = false;
         if (arg != null && !arg.startsWith("--")) {
-          result.add(HiddenPropertyMaskUtils.maskSensitiveJsonValue(arg));
+          result.add(safeMaskSensitiveJsonValue(arg));
           continue;
         }
         // Missing value for the previous flag; this element may itself be a 
flag.
       }
+      if (maskNextConf) {
+        maskNextConf = false;
+        if (arg != null && !arg.startsWith("--")) {
+          result.add(maskConfKeyValue(arg));
+          continue;
+        }
+        // Missing value for --conf; this element may itself be a flag.
+      }
       String equalsForm = maskEqualsForm(arg);
       if (equalsForm != null) {
         result.add(equalsForm);
         continue;
       }
+      String confEqualsForm = maskConfEqualsForm(arg);
+      if (confEqualsForm != null) {
+        result.add(confEqualsForm);
+        continue;
+      }
       result.add(arg);
       if (arg != null && JSON_ARGUMENT_FLAGS.contains(arg)) {
         maskNextJson = true;
+      } else if (CONF_ARGUMENT_FLAG.equals(arg)) {
+        maskNextConf = true;
       }
     }
     return result;
@@ -205,10 +242,59 @@ public final class JobRuntimeTemplateMaskUtils {
     for (String flag : JSON_ARGUMENT_FLAGS) {
       String prefix = flag + "=";
       if (arg.startsWith(prefix)) {
-        return prefix
-            + 
HiddenPropertyMaskUtils.maskSensitiveJsonValue(arg.substring(prefix.length()));
+        return prefix + 
safeMaskSensitiveJsonValue(arg.substring(prefix.length()));
       }
     }
     return null;
   }
+
+  /**
+   * @return {@code --conf=...} with a sensitive value masked, or {@code null} 
when {@code arg} is
+   *     not the equals form of {@link #CONF_ARGUMENT_FLAG}
+   */
+  @Nullable
+  private static String maskConfEqualsForm(@Nullable String arg) {
+    if (arg == null) {
+      return null;
+    }
+    String prefix = CONF_ARGUMENT_FLAG + "=";
+    if (!arg.startsWith(prefix)) {
+      return null;
+    }
+    return prefix + maskConfKeyValue(arg.substring(prefix.length()));
+  }
+
+  /**
+   * Masks {@code key=value} when {@code key} looks sensitive. Tokens without 
{@code =}, or with a
+   * non-sensitive key, are returned unchanged.
+   */
+  private static String maskConfKeyValue(String keyValue) {
+    int eq = keyValue.indexOf('=');
+    if (eq <= 0) {
+      return keyValue;
+    }
+    String key = keyValue.substring(0, eq);
+    if (!SecretPropertyUtils.isSensitivePropertyKey(key)) {
+      return keyValue;
+    }
+    return key + "=" + HiddenPropertyMaskUtils.MASKED_VALUE;
+  }
+
+  /**
+   * Masks one JSON argument value. Unexpected failures become {@link
+   * HiddenPropertyMaskUtils#MASKED_VALUE} so the argument walk can continue. 
Catches {@link
+   * Exception} (same scope as {@link 
HiddenPropertyMaskUtils#maskSensitiveJsonValue}) rather than
+   * only unchecked exceptions.
+   */
+  private static String safeMaskSensitiveJsonValue(String arg) {
+    try {
+      return HiddenPropertyMaskUtils.maskSensitiveJsonValue(arg);
+    } catch (Exception ignored) {
+      // Fixed message only: exception text may embed the argument (and 
credentials).
+      // Distinct from HiddenPropertyMaskUtils' malformed-JSON WARN (that path 
does not rethrow).
+      LOG.warn(
+          "Unexpected failure while masking a sensitive JSON argument; 
replacing with placeholder");
+      return HiddenPropertyMaskUtils.MASKED_VALUE;
+    }
+  }
 }
diff --git 
a/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java 
b/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
index 2096c7bf0f..4aa6fd2160 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/ShellProcessBuilder.java
@@ -25,6 +25,7 @@ import java.io.File;
 import java.util.List;
 import java.util.Map;
 import org.apache.gravitino.connector.job.JobResourceUtils;
+import org.apache.gravitino.job.JobRuntimeTemplateMaskUtils;
 import org.apache.gravitino.job.ShellJobTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -62,7 +63,10 @@ public class ShellProcessBuilder extends LocalProcessBuilder 
{
     builder.redirectOutput(outputFile);
     builder.redirectError(errorFile);
 
-    LOG.info("Starting local shell job with command: {}", Joiner.on(" 
").join(commandList));
+    // Mask JSON bags and sensitive --conf for the log only; ProcessBuilder 
keeps plaintext.
+    LOG.info(
+        "Starting local shell job with command: {}",
+        Joiner.on(" 
").join(JobRuntimeTemplateMaskUtils.maskSensitiveArguments(commandList)));
 
     try {
       return builder.start();
diff --git 
a/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java 
b/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
index ec79f5e4b7..a277f01f69 100644
--- a/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
+++ b/core/src/main/java/org/apache/gravitino/job/local/SparkProcessBuilder.java
@@ -31,6 +31,7 @@ import java.util.Map;
 import java.util.Optional;
 import javax.annotation.Nullable;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.job.JobRuntimeTemplateMaskUtils;
 import org.apache.gravitino.job.SparkJobTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -152,9 +153,10 @@ public class SparkProcessBuilder extends 
LocalProcessBuilder {
     builder.redirectOutput(outputFile);
     builder.redirectError(errorFile);
 
+    // Mask JSON bags and sensitive --conf for the log only; ProcessBuilder 
keeps plaintext.
     LOG.info(
         "Starting local Spark job with command: {}, environment variable 
names: {}",
-        Joiner.on(" ").join(commandList),
+        Joiner.on(" 
").join(JobRuntimeTemplateMaskUtils.maskSensitiveArguments(commandList)),
         Joiner.on(", ").join(sparkJobTemplate.environments().keySet()));
 
     try {
diff --git 
a/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
 
b/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
index 8fb062cf97..60c3841d07 100644
--- 
a/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
+++ 
b/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
@@ -237,12 +237,34 @@ public class TestHiddenPropertyMaskUtils {
   }
 
   @Test
-  void testMaskSensitiveJsonValueLeavesPlainNonJsonUnchanged() {
-    Assertions.assertEquals("verbose", 
HiddenPropertyMaskUtils.maskSensitiveJsonValue("verbose"));
-    Assertions.assertEquals("5", 
HiddenPropertyMaskUtils.maskSensitiveJsonValue("5"));
+  void testMaskSensitiveJsonValueRequiresSingleJsonObject() {
+    // Non-objects / invalid bags become ****** (credential JSON must be one 
map).
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        HiddenPropertyMaskUtils.maskSensitiveJsonValue("verbose"));
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE, 
HiddenPropertyMaskUtils.maskSensitiveJsonValue("5"));
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        HiddenPropertyMaskUtils.maskSensitiveJsonValue("true"));
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        
HiddenPropertyMaskUtils.maskSensitiveJsonValue("[{\"password\":\"x\"}]"));
     Assertions.assertEquals(
         HiddenPropertyMaskUtils.MASKED_VALUE,
         
HiddenPropertyMaskUtils.maskSensitiveJsonValue("{not-json,\"password\":\"x\"}"));
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        HiddenPropertyMaskUtils.maskSensitiveJsonValue("{} 
{\"password\":\"secret\"}"));
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        HiddenPropertyMaskUtils.maskSensitiveJsonValue("true 
{\"password\":\"secret\"}"));
+    // Duplicate fields: Jackson would keep only the last value; reject so the 
dropped secret
+    // cannot remain in the original argument when the walk sees a no-op last 
field.
+    Assertions.assertEquals(
+        HiddenPropertyMaskUtils.MASKED_VALUE,
+        HiddenPropertyMaskUtils.maskSensitiveJsonValue(
+            "{\"config\":{\"password\":\"example\"},\"config\":{}}"));
   }
 
   @Test
diff --git 
a/core/src/test/java/org/apache/gravitino/job/TestJobRuntimeTemplateMaskUtils.java
 
b/core/src/test/java/org/apache/gravitino/job/TestJobRuntimeTemplateMaskUtils.java
index 5e36821073..bc17a52d53 100644
--- 
a/core/src/test/java/org/apache/gravitino/job/TestJobRuntimeTemplateMaskUtils.java
+++ 
b/core/src/test/java/org/apache/gravitino/job/TestJobRuntimeTemplateMaskUtils.java
@@ -20,19 +20,45 @@ package org.apache.gravitino.job;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
 import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
 import org.apache.gravitino.dto.AuditDTO;
 import org.apache.gravitino.dto.job.ShellJobTemplateDTO;
 import org.apache.gravitino.dto.job.SparkJobTemplateDTO;
 import org.apache.gravitino.job.JobTemplate.JobType;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.layout.PatternLayout;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
 public class TestJobRuntimeTemplateMaskUtils {
 
+  private static final class LogCollector extends AbstractAppender {
+    private final List<LogEvent> events = new CopyOnWriteArrayList<>();
+
+    private LogCollector() {
+      super(
+          "jobRuntimeTemplateMaskUtilsLogCollector",
+          null,
+          PatternLayout.createDefaultLayout(),
+          true,
+          null);
+    }
+
+    @Override
+    public void append(LogEvent event) {
+      events.add(event.toImmutable());
+    }
+  }
+
   @Test
   void testMaskSensitiveFieldsMasksUpdaterOptionsAndSparkConf() {
     SparkJobTemplateDTO input =
@@ -125,35 +151,213 @@ public class TestJobRuntimeTemplateMaskUtils {
             .withJobType(JobType.SHELL)
             .withExecutable("/bin/sh")
             .withArguments(
-                ImmutableList.of(
-                    "-c",
-                    command,
-                    "--password",
-                    "my secret pass",
-                    "--conf",
-                    "spark.jdbc.password=my pass",
-                    "--where",
-                    where))
+                ImmutableList.of("-c", command, "--password", "my secret 
pass", "--where", where))
             .build();
 
     ShellJobTemplateDTO shell =
         (ShellJobTemplateDTO) 
JobRuntimeTemplateMaskUtils.maskSensitiveFields(input);
     Assertions.assertEquals(
+        ImmutableList.of("-c", command, "--password", "my secret pass", 
"--where", where),
+        shell.arguments());
+  }
+
+  @Test
+  void testMaskSensitiveArgumentsMasksSensitiveConf() {
+    List<String> command =
         ImmutableList.of(
-            "-c",
-            command,
-            "--password",
-            "my secret pass",
+            "/path/to/spark-submit",
             "--conf",
-            "spark.jdbc.password=my pass",
-            "--where",
-            where),
-        shell.arguments());
+            "spark.executor.memory=2g",
+            "--conf",
+            "spark.sql.catalog.ice.rest.auth.basic.password=catalog-pw",
+            "--conf=spark.hadoop.fs.s3a.secret.key=s3-secret",
+            "--conf",
+            "--spark-conf",
+            "{\"password\":\"bag-pw\"}",
+            "local:///app.jar");
+
+    List<String> masked = 
JobRuntimeTemplateMaskUtils.maskSensitiveArguments(command);
+
+    Assertions.assertEquals("spark.executor.memory=2g", masked.get(2));
+    Assertions.assertEquals(
+        "spark.sql.catalog.ice.rest.auth.basic.password=" + 
HiddenPropertyMaskUtils.MASKED_VALUE,
+        masked.get(4));
+    Assertions.assertEquals(
+        "--conf=spark.hadoop.fs.s3a.secret.key=" + 
HiddenPropertyMaskUtils.MASKED_VALUE,
+        masked.get(5));
+    // Missing --conf value; next flag is still walked.
+    Assertions.assertEquals("--spark-conf", masked.get(7));
+    Assertions.assertFalse(masked.get(8).contains("bag-pw"));
+    Assertions.assertTrue(command.get(4).contains("catalog-pw"));
+    Assertions.assertTrue(command.get(5).contains("s3-secret"));
   }
 
   @Test
   void testMaskSensitiveFieldsNull() {
     
Assertions.assertNull(JobRuntimeTemplateMaskUtils.maskSensitiveFields(null));
+    
Assertions.assertNull(JobRuntimeTemplateMaskUtils.maskSensitiveArguments(null));
+  }
+
+  @Test
+  void testMaskSensitiveArgumentsOnFullSparkSubmitCommand() {
+    // Same shape as SparkProcessBuilder.generateSparkSubmitCommand: mask for 
INFO logs only.
+    List<String> command =
+        ImmutableList.of(
+            "/path/to/spark-submit",
+            "--class",
+            "org.example.App",
+            "--conf",
+            "spark.executor.memory=2g",
+            "--conf",
+            "spark.sql.catalog.ice.rest.auth.basic.password=catalog-pw",
+            "local:///app.jar",
+            "--updater-options",
+            "{\"password\":\"arg-pw\",\"gravitino_uri\":\"http://localhost\"}";,
+            "--spark-conf",
+            "{\"spark.sql.catalog.ice.rest.auth.basic.password\":\"jdbc-pw\","
+                + "\"spark.executor.memory\":\"1g\"}",
+            "--table",
+            "db.t");
+
+    List<String> masked = 
JobRuntimeTemplateMaskUtils.maskSensitiveArguments(command);
+
+    Assertions.assertEquals(command.size(), masked.size());
+    Assertions.assertEquals("/path/to/spark-submit", masked.get(0));
+    Assertions.assertEquals("spark.executor.memory=2g", masked.get(4));
+    Assertions.assertEquals(
+        "spark.sql.catalog.ice.rest.auth.basic.password=" + 
HiddenPropertyMaskUtils.MASKED_VALUE,
+        masked.get(6));
+    Assertions.assertFalse(masked.get(9).contains("arg-pw"));
+    Assertions.assertTrue(masked.get(9).contains("http://localhost";));
+    
Assertions.assertTrue(masked.get(9).contains(HiddenPropertyMaskUtils.MASKED_VALUE));
+    Assertions.assertFalse(masked.get(11).contains("jdbc-pw"));
+    Assertions.assertTrue(masked.get(11).contains("1g"));
+    Assertions.assertEquals("db.t", masked.get(13));
+    // Original list used for ProcessBuilder must stay plaintext.
+    Assertions.assertTrue(command.get(6).contains("catalog-pw"));
+    Assertions.assertTrue(command.get(9).contains("arg-pw"));
+    Assertions.assertTrue(command.get(11).contains("jdbc-pw"));
+  }
+
+  @Test
+  void testMaskSensitiveArgumentsContinuesAfterOneValueFails() {
+    // Malformed object-looking JSON is replaced with ******; later flags are 
still masked.
+    List<String> arguments =
+        ImmutableList.of(
+            "--updater-options",
+            "{not-valid-json",
+            "--spark-conf",
+            "{\"password\":\"later-pw\",\"spark.executor.memory\":\"1g\"}",
+            "--table",
+            "db.t");
+
+    List<String> masked = 
JobRuntimeTemplateMaskUtils.maskSensitiveArguments(arguments);
+
+    Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(1));
+    Assertions.assertEquals("--spark-conf", masked.get(2));
+    Assertions.assertFalse(masked.get(3).contains("later-pw"));
+    Assertions.assertTrue(masked.get(3).contains("1g"));
+    
Assertions.assertTrue(masked.get(3).contains(HiddenPropertyMaskUtils.MASKED_VALUE));
+    Assertions.assertEquals("db.t", masked.get(5));
+  }
+
+  @Test
+  void testMaskSensitiveArgumentsMasksNonSingleJsonObjectBags() {
+    String concatenated = "{} {\"password\":\"concat-secret\"}";
+    String scalarThenObject = "true {\"password\":\"scalar-secret\"}";
+    String duplicateField = 
"{\"config\":{\"password\":\"dup-secret\"},\"config\":{}}";
+    List<String> masked =
+        JobRuntimeTemplateMaskUtils.maskSensitiveArguments(
+            ImmutableList.of(
+                "--updater-options",
+                concatenated,
+                "--spark-conf",
+                scalarThenObject,
+                "--updater-options",
+                duplicateField,
+                "--table",
+                "db.t"));
+
+    Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(1));
+    Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(3));
+    Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(5));
+    Assertions.assertFalse(masked.get(1).contains("concat-secret"));
+    Assertions.assertFalse(masked.get(3).contains("scalar-secret"));
+    Assertions.assertFalse(masked.get(5).contains("dup-secret"));
+    Assertions.assertEquals("db.t", masked.get(7));
+  }
+
+  @Test
+  void testMalformedCredentialJsonDoesNotLeakInMaskingLogs() {
+    // Regression for review on #14979: Jackson exception text must not reach 
WARN logs.
+    String malformed = "{\"password\":\"malformed-credential-secret\",";
+    List<String> arguments =
+        ImmutableList.of("--updater-options", malformed, "--spark-conf", 
malformed);
+
+    List<LogEvent> events =
+        captureMaskingLogs(
+            () -> {
+              List<String> masked = 
JobRuntimeTemplateMaskUtils.maskSensitiveArguments(arguments);
+              Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(1));
+              Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, 
masked.get(3));
+            });
+
+    Assertions.assertFalse(events.isEmpty(), "expected a WARN from malformed 
nest JSON masking");
+    for (LogEvent event : events) {
+      String rendered = renderLogEvent(event);
+      Assertions.assertFalse(
+          rendered.contains("malformed-credential-secret"),
+          () -> "masking log leaked credential input: " + rendered);
+      Assertions.assertFalse(
+          rendered.contains(malformed),
+          () -> "masking log leaked malformed JSON input: " + rendered);
+    }
+  }
+
+  private static List<LogEvent> captureMaskingLogs(Runnable action) {
+    LoggerContext context =
+        (LoggerContext)
+            
LogManager.getContext(JobRuntimeTemplateMaskUtils.class.getClassLoader(), 
false);
+    var jobMaskLogger = 
context.getLogger(JobRuntimeTemplateMaskUtils.class.getName());
+    var hiddenMaskLogger = 
context.getLogger(HiddenPropertyMaskUtils.class.getName());
+    LogCollector collector = new LogCollector();
+    collector.start();
+    synchronized (jobMaskLogger) {
+      synchronized (hiddenMaskLogger) {
+        Level previousJob = jobMaskLogger.getLevel();
+        Level previousHidden = hiddenMaskLogger.getLevel();
+        jobMaskLogger.addAppender(collector);
+        hiddenMaskLogger.addAppender(collector);
+        jobMaskLogger.setLevel(Level.DEBUG);
+        hiddenMaskLogger.setLevel(Level.DEBUG);
+        try {
+          action.run();
+        } finally {
+          jobMaskLogger.removeAppender(collector);
+          hiddenMaskLogger.removeAppender(collector);
+          jobMaskLogger.setLevel(previousJob);
+          hiddenMaskLogger.setLevel(previousHidden);
+          collector.stop();
+        }
+      }
+    }
+    return List.copyOf(collector.events);
+  }
+
+  private static String renderLogEvent(LogEvent event) {
+    List<String> parts = new ArrayList<>();
+    if (event.getMessage() != null) {
+      parts.add(event.getMessage().getFormattedMessage());
+    }
+    Throwable thrown = event.getThrown();
+    while (thrown != null) {
+      parts.add(String.valueOf(thrown));
+      if (thrown.getMessage() != null) {
+        parts.add(thrown.getMessage());
+      }
+      thrown = thrown.getCause();
+    }
+    return String.join("\n", parts);
   }
 
   @Test

Reply via email to