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

gavinchou pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new dc02018bb20 [fix](fe) Preserve SQL formatting when masking FE logs 
(#69467)
dc02018bb20 is described below

commit dc02018bb20baf1c66415c5324de1278965411b1
Author: Gavin Chou <[email protected]>
AuthorDate: Mon Nov 23 11:39:26 2026 +0800

    [fix](fe) Preserve SQL formatting when masking FE logs (#69467)
    
    SQL masking in FE execution logs rebuilds entire property lists, losing
    their line breaks, indentation, comments and original key formatting.
    Some retry, internal query and HTTP stream planning logs also print the
    original SQL. Parser exceptions can repeat the original SQL in their
    diagnostic text even when the main log message uses a masked statement.
    
    Reuse the audit masking parser and the existing sensitive/hidden
    property key policies, with a formatting-preserving mode that replaces
    only sensitive values. Use this shared path for StmtExecutor SQL logs
    before and after parsing, including statements whose audit-encryption
    flag is false. Normalize parser replacement ranges to inclusive UTF-16
    offsets for both formatting modes and direct streaming callers, so
    supplementary Unicode characters cannot shift the masked ranges. Keep
    audit logging's existing formatting and dispatch behavior.
    
    Masking failures return a fixed placeholder. Logs for masking and syntax
    failures record the exception type without input-bearing exception
    messages or stack traces. Logging pre-processing does not apply
    execution hints.
    
    ### Release note
    
    FE execution logs preserve SQL line breaks and formatting while masking
    recognized credential values. Syntax-error diagnostics no longer repeat
    the original SQL. Supplementary Unicode characters no longer leave
    recognized credentials unmasked in audit SQL.
---
 .../doris/nereids/parser/LogicalPlanBuilder.java   |   2 +-
 .../parser/LogicalPlanBuilderForEncryption.java    |  26 +++-
 .../apache/doris/nereids/parser/NereidsParser.java |  28 +++-
 .../trees/plans/commands/NeedAuditEncryption.java  |   7 +-
 .../java/org/apache/doris/qe/StmtExecutor.java     |  77 ++++-------
 .../doris/nereids/parser/EncryptSQLTest.java       |  99 ++++++++++++++
 .../java/org/apache/doris/qe/StmtExecutorTest.java | 152 +++++++++++++++------
 7 files changed, 298 insertions(+), 93 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
index 8afac7bce2c..d9225b7cf90 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java
@@ -5320,7 +5320,7 @@ public class LogicalPlanBuilder extends 
DorisParserBaseVisitor<Object> {
         }
     }
 
-    private String parsePropertyKey(PropertyKeyContext item) {
+    protected String parsePropertyKey(PropertyKeyContext item) {
         if (item.constant() != null) {
             return parseConstant(item.constant()).trim();
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilderForEncryption.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilderForEncryption.java
index a3b4227fc39..3cb93cf8c04 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilderForEncryption.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilderForEncryption.java
@@ -41,11 +41,35 @@ import java.util.Objects;
 /**LogicalPlanBuilderForEncryption*/
 public class LogicalPlanBuilderForEncryption extends LogicalPlanBuilder {
     private final Map<Pair<Integer, Integer>, String> indexInSqlToString;
+    private final boolean preserveFormatting;
 
     public LogicalPlanBuilderForEncryption(Map<Integer, ParserRuleContext> 
selectHintMap,
                                            Map<Pair<Integer, Integer>, String> 
indexInSqlToString) {
+        this(selectHintMap, indexInSqlToString, false);
+    }
+
+    public LogicalPlanBuilderForEncryption(Map<Integer, ParserRuleContext> 
selectHintMap,
+            Map<Pair<Integer, Integer>, String> indexInSqlToString, boolean 
preserveFormatting) {
         super(selectHintMap);
         this.indexInSqlToString = Objects.requireNonNull(indexInSqlToString, 
"indexInSqlToString is null");
+        this.preserveFormatting = preserveFormatting;
+    }
+
+    @Override
+    public Map<String, String> 
visitPropertyItemList(DorisParser.PropertyItemListContext ctx) {
+        Map<String, String> properties = super.visitPropertyItemList(ctx);
+        if (preserveFormatting && ctx != null) {
+            for (DorisParser.PropertyItemContext property : ctx.properties) {
+                String key = parsePropertyKey(property.key);
+                if (DatasourcePrintableMap.isSensitiveKey(key) || 
DatasourcePrintableMap.HIDDEN_KEY.contains(key)) {
+                    // Keep whitespace, comments, key spelling and the 
surrounding SQL unchanged.
+                    String quote = property.value.getText().startsWith("\"") ? 
"\"" : "'";
+                    
indexInSqlToString.put(Pair.of(property.value.start.getStartIndex(),
+                            property.value.stop.getStopIndex()), quote + 
DatasourcePrintableMap.PASSWORD_MASK + quote);
+                }
+            }
+        }
+        return properties;
     }
 
     // select into outfile clause
@@ -288,7 +312,7 @@ public class LogicalPlanBuilderForEncryption extends 
LogicalPlanBuilder {
     }
 
     private void encryptProperty(Map<String, String> properties, int start, 
int stop) {
-        if (MapUtils.isNotEmpty(properties)) {
+        if (!preserveFormatting && MapUtils.isNotEmpty(properties)) {
             DatasourcePrintableMap<String, String> printableMap = new 
DatasourcePrintableMap<>(properties, "=",
                     true, false, true);
             indexInSqlToString.put(Pair.of(start, stop), 
printableMap.toString());
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/NereidsParser.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/NereidsParser.java
index 0484c0145dc..8b1d81010db 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/NereidsParser.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/parser/NereidsParser.java
@@ -63,6 +63,7 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
+import java.util.TreeMap;
 import java.util.function.Function;
 import javax.annotation.Nullable;
 
@@ -365,15 +366,36 @@ public class NereidsParser {
         return (LogicalPlan) realLogicalPlanBuilder.visit(tree);
     }
 
-    /** Parse SQL for masking without applying execution hints to the session. 
*/
+    /** Parse SQL for masking without applying execution hints; output ranges 
use inclusive UTF-16 offsets. */
     public LogicalPlan parseForEncryption(String sql, Map<Pair<Integer, 
Integer>, String> indexInSqlToString) {
+        return parseForEncryption(sql, indexInSqlToString, false);
+    }
+
+    /** Parse SQL for masking with inclusive UTF-16 output ranges, optionally 
preserving property-list layout. */
+    public LogicalPlan parseForEncryption(String sql, Map<Pair<Integer, 
Integer>, String> indexInSqlToString,
+            boolean preserveFormatting) {
         CommonTokenStream tokenStream = parseLeanTokens(sql);
         ParserRuleContext tree = toAst(tokenStream, 
DorisParser::singleStatement);
         // SQL masking must not apply SET_VAR hints to the current session.
         // The original SQL, including its hints, is preserved by the property 
replacements.
+        TreeMap<Pair<Integer, Integer>, String> codePointRanges = new 
TreeMap<>(new Pair.PairComparator<>());
         LogicalPlanBuilder realLogicalPlanBuilder = new 
LogicalPlanBuilderForEncryption(
-                ImmutableMap.of(), indexInSqlToString);
-        return (LogicalPlan) realLogicalPlanBuilder.visit(tree);
+                ImmutableMap.of(), codePointRanges, preserveFormatting);
+        LogicalPlan plan = (LogicalPlan) realLogicalPlanBuilder.visit(tree);
+        // ANTLR indexes code points, while SQL rewriting uses Java UTF-16 
offsets. Normalize both
+        // masking modes here so audit, FE logs and direct parser callers 
share the same contract.
+        // Walk sorted ranges once rather than rescanning the prefix for every 
replacement.
+        int codePointOffset = 0;
+        int charOffset = 0;
+        for (Map.Entry<Pair<Integer, Integer>, String> entry : 
codePointRanges.entrySet()) {
+            Pair<Integer, Integer> range = entry.getKey();
+            int start = sql.offsetByCodePoints(charOffset, range.first - 
codePointOffset);
+            int end = sql.offsetByCodePoints(start, range.second - range.first 
+ 1);
+            indexInSqlToString.put(Pair.of(start, end - 1), entry.getValue());
+            codePointOffset = range.second + 1;
+            charOffset = end;
+        }
+        return plan;
     }
 
     /** parseForSyncMv */
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/NeedAuditEncryption.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/NeedAuditEncryption.java
index 823d9e6d4c3..0e4d4b08708 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/NeedAuditEncryption.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/NeedAuditEncryption.java
@@ -36,9 +36,14 @@ public interface NeedAuditEncryption {
         if (!needAuditEncryption()) {
             return sql;
         }
+        return maskSql(sql, false);
+    }
+
+    /** Apply audit masking rules, optionally retaining source formatting for 
FE logs. */
+    static String maskSql(String sql, boolean preserveFormatting) {
         TreeMap<Pair<Integer, Integer>, String> indexInSqlToString = new 
TreeMap<>(new Pair.PairComparator<>());
         NereidsParser parser = new NereidsParser();
-        parser.parseForEncryption(sql, indexInSqlToString);
+        parser.parseForEncryption(sql, indexInSqlToString, preserveFormatting);
         return BaseViewInfo.rewriteSql(indexInSqlToString, sql);
     }
 }
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java 
b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
index 5afb54d4813..e5f83d5fbd5 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/StmtExecutor.java
@@ -828,14 +828,20 @@ public class StmtExecutor {
                 executeByNereids(queryId);
             } catch (NereidsException | ParseException e) {
                 // COMPUTE_GROUPS_NO_ALIVE_BE, planner can't get alive be, 
need retry
-                if (Config.isCloudMode() && 
SystemInfoService.needRetryWithReplan(e.getMessage())) {
+                if (e instanceof NereidsException && Config.isCloudMode()
+                        && 
SystemInfoService.needRetryWithReplan(e.getMessage())) {
                     
profile.getSummaryProfile().recordFailedAttempt(context.queryId());
                     LOG.debug("planner failed with cloud compute group error, 
need retry. {}",
                             context.getQueryIdentifier(), e);
                     throw new UserException(e.getMessage());
                 }
-                ExceptionDiagnosticUtils.log(LOG, Level.WARN, "Analyze failed. 
{}",
-                        context.getQueryIdentifier(), e);
+                if (e instanceof ParseException) {
+                    // Parser diagnostics embed the original SQL, including 
any credentials.
+                    LOG.warn("Analyze failed. {} ({})", 
context.getQueryIdentifier(), e.getClass().getSimpleName());
+                } else {
+                    ExceptionDiagnosticUtils.log(LOG, Level.WARN, "Analyze 
failed. {}",
+                            context.getQueryIdentifier(), e);
+                }
                 // Planning wraps the window rejection in 
NereidsException/AnalysisException.
                 // NereidsException(Exception) keeps its wrapped exception 
outside Throwable.cause.
                 Throwable cause = e instanceof NereidsException
@@ -1352,7 +1358,7 @@ public class StmtExecutor {
                         // in the begining of retryTime/2
                         int randomMillis = 1000 + (int) (Math.random() * (1000 
- 500));
                         LOG.debug("stmt executor retry times {}, wait 
randomMillis:{}, stmt:{}",
-                                i, randomMillis, originStmt.originStmt);
+                                i, randomMillis, 
getStmtForLogging(originStmt.originStmt));
                         try {
                             if (i > retryTime / 2) {
                                 // sleep random millis [2000, 2500] ms
@@ -1429,11 +1435,11 @@ public class StmtExecutor {
                     // the plan would read nothing, or only what the failed 
attempt left, and succeed.
                     LOG.warn("not retrying query {} with the same plan: a scan 
node's ranges cannot be read"
                             + " again by the backend. stmt: {}",
-                            DebugUtil.printId(context.queryId()), 
originStmt.originStmt);
+                            DebugUtil.printId(context.queryId()), 
getStmtForLogging(originStmt.originStmt));
                     throw e;
                 }
                 if (i != retryTime - 1 && isNeedRetry && 
context.getProtocolAdapter().canRetryQuery(context)) {
-                    LOG.warn("retry {} times. stmt: {}", (i + 1), 
originStmt.originStmt);
+                    LOG.warn("retry {} times. stmt: {}", (i + 1), 
getStmtForLogging(originStmt.originStmt));
                     willRetry = true;
                 } else {
                     throw e;
@@ -1776,7 +1782,7 @@ public class StmtExecutor {
         
statementContext.validateOrRevalidatePartitionPoliciesForExecution(planner);
         if (LOG.isDebugEnabled()) {
             LOG.debug("Handling query {} with query id {}",
-                    originStmt.originStmt, DebugUtil.printId(context.queryId));
+                    getStmtForLogging(originStmt.originStmt), 
DebugUtil.printId(context.queryId));
         }
 
         ResultSender sender = context.getResultSender();
@@ -2282,7 +2288,7 @@ public class StmtExecutor {
 
     public List<ResultRow> executeInternalQuery() {
         if (LOG.isDebugEnabled()) {
-            LOG.debug("INTERNAL QUERY: {}", originStmt.toString());
+            LOG.debug("INTERNAL QUERY: {}", getStmtForLoggingBeforeParse());
         }
         try {
             return executeInternalQueryCommon(null, null);
@@ -2488,21 +2494,21 @@ public class StmtExecutor {
             }
             return httpStreamParams;
         } catch (QueryStateException e) {
-            LOG.debug("Command(" + originStmt.originStmt + ") process 
failed.", e);
+            LOG.debug("Command({}) process failed.", 
getStmtForLogging(originStmt.originStmt), e);
             context.setState(e.getQueryState());
-            throw new NereidsException("Command(" + originStmt.originStmt + ") 
process failed",
+            throw new NereidsException("Command(" + 
getStmtForLogging(originStmt.originStmt) + ") process failed",
                     new AnalysisException(e.getMessage(), e));
         } catch (UserException e) {
             // Return message to info client what happened.
-            LOG.debug("Command(" + originStmt.originStmt + ") process 
failed.", e);
+            LOG.debug("Command({}) process failed.", 
getStmtForLogging(originStmt.originStmt), e);
             context.getState().setError(e.getMysqlErrorCode(), e.getMessage());
-            throw new NereidsException("Command (" + originStmt.originStmt + 
") process failed",
+            throw new NereidsException("Command (" + 
getStmtForLogging(originStmt.originStmt) + ") process failed",
                     new AnalysisException(e.getMessage(), e));
         } catch (Exception e) {
             // Maybe our bug
-            LOG.debug("Command (" + originStmt.originStmt + ") process 
failed.", e);
+            LOG.debug("Command({}) process failed.", 
getStmtForLogging(originStmt.originStmt), e);
             context.getState().setError(ErrorCode.ERR_UNKNOWN_ERROR, 
e.getMessage());
-            throw new NereidsException("Command (" + originStmt.originStmt + 
") process failed.",
+            throw new NereidsException("Command (" + 
getStmtForLogging(originStmt.originStmt) + ") process failed.",
                     new AnalysisException(e.getMessage(), e));
         }
     }
@@ -2517,8 +2523,13 @@ public class StmtExecutor {
             } catch (NereidsException | ParseException e) {
                 // try to fall back to legacy planner
                 if (LOG.isDebugEnabled()) {
-                    LOG.debug("nereids cannot process statement\n{}\n because 
of {}",
-                            originStmt.originStmt, e.getMessage(), e);
+                    if (e instanceof ParseException) {
+                        LOG.debug("nereids cannot parse statement\n{} ({})",
+                                getStmtForLoggingBeforeParse(), 
e.getClass().getSimpleName());
+                    } else {
+                        ExceptionDiagnosticUtils.log(LOG, Level.DEBUG, 
"nereids cannot process statement\n{}",
+                                getStmtForLogging(originStmt.originStmt), e);
+                    }
                 }
                 if (e instanceof NereidsException) {
                     LOG.warn("Analyze failed. {}", 
context.getQueryIdentifier(), e);
@@ -2577,49 +2588,21 @@ public class StmtExecutor {
         if (stmt == null) {
             return stmt;
         }
-        if (!(parsedStmt instanceof LogicalPlanAdapter)) {
-            return getStmtForLoggingBeforeParse(stmt);
-        }
         // Internal export outfile tasks use an empty origin SQL, so audit 
masking must skip reparsing here.
         if (stmt.isEmpty()) {
             return stmt;
         }
-        LogicalPlan logicalPlan = ((LogicalPlanAdapter) 
parsedStmt).getLogicalPlan();
-        if (!(logicalPlan instanceof NeedAuditEncryption)) {
-            return stmt;
-        }
         try {
-            return ((NeedAuditEncryption) logicalPlan).geneEncryptionSQL(stmt);
+            return NeedAuditEncryption.maskSql(stmt, true);
         } catch (Exception e) {
             // Logging must not leak plaintext or change command behavior when 
masking fails.
-            LOG.warn("failed to mask statement for FE logging", e);
+            LOG.warn("failed to mask statement for FE logging ({})", 
e.getClass().getSimpleName());
             return MASKED_STMT_FALLBACK;
         }
     }
 
     private String getStmtForLoggingBeforeParse() {
-        return getStmtForLoggingBeforeParse(originStmt == null ? null : 
originStmt.originStmt);
-    }
-
-    private String getStmtForLoggingBeforeParse(String stmt) {
-        if (stmt == null) {
-            return null;
-        }
-        // Empty SQL cannot produce a valid parse tree for audit masking, so 
keep the original text.
-        if (stmt.isEmpty()) {
-            return stmt;
-        }
-        try {
-            LogicalPlan logicalPlan = new NereidsParser().parseSingle(stmt);
-            if (!(logicalPlan instanceof NeedAuditEncryption)) {
-                return stmt;
-            }
-            return ((NeedAuditEncryption) logicalPlan).geneEncryptionSQL(stmt);
-        } catch (Exception e) {
-            // Logging must fail closed before parsing so secrets never fall 
back to plaintext.
-            LOG.warn("failed to prepare masked statement for FE logging", e);
-            return MASKED_STMT_FALLBACK;
-        }
+        return getStmtForLogging(originStmt == null ? null : 
originStmt.originStmt);
     }
 
     public void sendProxyQueryResult() throws IOException {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/EncryptSQLTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/EncryptSQLTest.java
index 6b196f3e573..a49371578cc 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/EncryptSQLTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/parser/EncryptSQLTest.java
@@ -21,11 +21,14 @@ import org.apache.doris.analysis.AccessTestUtil;
 import org.apache.doris.analysis.StatementBase;
 import org.apache.doris.analysis.UserIdentity;
 import org.apache.doris.catalog.Env;
+import org.apache.doris.common.Pair;
 import org.apache.doris.common.jmockit.Deencapsulation;
 import org.apache.doris.common.profile.Profile;
 import org.apache.doris.datasource.InternalCatalog;
 import org.apache.doris.ha.FrontendNodeType;
 import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption;
+import org.apache.doris.nereids.trees.plans.commands.info.BaseViewInfo;
 import org.apache.doris.plugin.AuditEvent;
 import org.apache.doris.qe.ConnectContext;
 import org.apache.doris.qe.MysqlConnectProcessor;
@@ -34,10 +37,13 @@ import 
org.apache.doris.resource.workloadschedpolicy.WorkloadRuntimeStatusMgr;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 import org.mockito.MockedConstruction;
 import org.mockito.Mockito;
 
 import java.util.List;
+import java.util.TreeMap;
 
 public class EncryptSQLTest extends ParserTestBase {
 
@@ -642,4 +648,97 @@ public class EncryptSQLTest extends ParserTestBase {
         AuditEvent event = auditEvents.get(auditEvents.size() - 1);
         Assertions.assertEquals(expected, event.stmt);
     }
+
+    @Test
+    public void testLogMaskingPreservesPropertyFormatting() {
+        String sql = "/* πŸ˜€ catalog */\r\nCREATE CATALOG log_format PROPERTIES 
(\r\n"
+                + "\t'type' = 'jdbc', -- keep this comment\r\n"
+                + "\t' JDBC.PASSWORD ' /* value */ = 
'synthetic\\'password',\r\n"
+                + "\t\"jdbc.user\" = \"reader\",\r\n"
+                + "\t\"s3.access_key\" = \"synthetic-access-key\",\r\n"
+                + "\t\"s3.secret_key\" = \"synthetic-secret-key\"\r\n);";
+        String expected = sql.replace("'synthetic\\'password'", "'*XXX'")
+                .replace("synthetic-access-key", 
"*XXX").replace("synthetic-secret-key", "*XXX");
+        assertLogMasking(sql, expected);
+    }
+
+    @Test
+    public void testLogMaskingPreservesHiddenPropertyLayout() {
+        String sql = "CREATE CATALOG log_hidden PROPERTIES (\n"
+                + "  'type' = 'hms',\n"
+                + "  'AWS_ENDPOINT' /* keep */ = 'synthetic-endpoint',\n"
+                + "  'AWS_TOKEN' = 'synthetic-token',\n"
+                + "  'fluss.lake.paimon.fs.password' = 
'synthetic-password'\n)";
+        String expected = sql.replace("synthetic-endpoint", 
"*XXX").replace("synthetic-token", "*XXX")
+                .replace("synthetic-password", "*XXX");
+        assertLogMasking(sql, expected);
+    }
+
+    @Test
+    public void testLogPasswordMaskingWithSupplementaryCharacters() {
+        String sql = "/* πŸ˜€ */\nCREATE USER 'log_user'@'%'\nIDENTIFIED BY 
'synthetic-πŸ˜€-password';";
+        assertLogMasking(sql, sql.replace("synthetic-πŸ˜€-password", "*XXX"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"ASCII", "δΈ­ζ–‡", "πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€"})
+    public void testPasswordMaskingUsesUtf16OffsetsInBothModes(String prefix) {
+        for (String password : new String[] {"demo42", 
"synthetic-πŸ˜€-password"}) {
+            String sql = "/* " + prefix + " */ CREATE USER 'unicode_log_user' 
IDENTIFIED BY '" + password + "'";
+            String expected = sql.replace("'" + password + "'", "'*XXX'");
+            NeedAuditEncryption plan = (NeedAuditEncryption) new 
NereidsParser().parseSingle(sql);
+            Assertions.assertEquals(expected, plan.geneEncryptionSQL(sql));
+            Assertions.assertEquals(expected, NeedAuditEncryption.maskSql(sql, 
false));
+            Assertions.assertEquals(expected, NeedAuditEncryption.maskSql(sql, 
true));
+        }
+    }
+
+    @Test
+    public void testAuditPropertyMaskingKeepsExistingFormattingWithUnicode() {
+        String sql = "/* πŸ˜€πŸ˜€ */ CREATE CATALOG unicode_catalog PROPERTIES (\n"
+                + "  'type' = 'hms',\n"
+                + "  'AWS_ENDPOINT' = 'synthetic-endpoint',\n"
+                + "  's3.secret_key' = 'synthetic-πŸ˜€-secret',\n"
+                + "  'comment' = 'keep-πŸ˜€'\n)";
+        String expectedAudit = "/* πŸ˜€πŸ˜€ */ CREATE CATALOG unicode_catalog 
PROPERTIES (\n"
+                + "  \"type\" = \"hms\", \"s3.secret_key\" = \"*XXX\", 
\"comment\" = \"keep-πŸ˜€\"\n)";
+        NeedAuditEncryption plan = (NeedAuditEncryption) new 
NereidsParser().parseSingle(sql);
+        Assertions.assertEquals(expectedAudit, plan.geneEncryptionSQL(sql));
+        Assertions.assertEquals(expectedAudit, 
NeedAuditEncryption.maskSql(sql, false));
+        String expectedLog = sql.replace("'synthetic-endpoint'", "'*XXX'")
+                .replace("'synthetic-πŸ˜€-secret'", "'*XXX'");
+        Assertions.assertEquals(expectedLog, NeedAuditEncryption.maskSql(sql, 
true));
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void testEncryptionParserReturnsUtf16Ranges(boolean 
preserveFormatting) {
+        String first = "'uri' = 's3://bucket/πŸ˜€.csv', 'format' = 'csv', 
's3.secret_key' = 'first-πŸ˜€-secret'";
+        String second = "'uri' = 's3://bucket/other.csv', 'format' = 'csv', 
's3.secret_key' = 'second-secret'";
+        String sql = "/* πŸ˜€πŸ˜€ */ SELECT * FROM S3(" + first + ")\nUNION ALL /* πŸ˜€ 
*/ SELECT * FROM S3("
+                + second + ") /* keep-πŸ˜€ */";
+        TreeMap<Pair<Integer, Integer>, String> replacements = new 
TreeMap<>(new Pair.PairComparator<>());
+        new NereidsParser().parseForEncryption(sql, replacements, 
preserveFormatting);
+        Assertions.assertEquals(2, replacements.size());
+        Pair<Integer, Integer> firstRange = replacements.firstKey();
+        Pair<Integer, Integer> secondRange = replacements.lastKey();
+        Assertions.assertEquals(preserveFormatting ? "'first-πŸ˜€-secret'" : 
first,
+                sql.substring(firstRange.first, firstRange.second + 1));
+        Assertions.assertEquals(preserveFormatting ? "'second-secret'" : 
second,
+                sql.substring(secondRange.first, secondRange.second + 1));
+        String expected;
+        if (preserveFormatting) {
+            expected = sql.replace("'first-πŸ˜€-secret'", 
"'*XXX'").replace("'second-secret'", "'*XXX'");
+        } else {
+            expected = sql.replace(first,
+                    "\"uri\" = \"s3://bucket/πŸ˜€.csv\", \"format\" = \"csv\", 
\"s3.secret_key\" = \"*XXX\"")
+                    .replace(second,
+                            "\"uri\" = \"s3://bucket/other.csv\", \"format\" = 
\"csv\", \"s3.secret_key\" = \"*XXX\"");
+        }
+        Assertions.assertEquals(expected, 
BaseViewInfo.rewriteSql(replacements, sql));
+    }
+
+    private void assertLogMasking(String sql, String expected) {
+        Assertions.assertEquals(expected, NeedAuditEncryption.maskSql(sql, 
true));
+    }
 }
diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
index 48978622b6d..df2361612b8 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
@@ -105,6 +105,8 @@ import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
@@ -1613,27 +1615,16 @@ public class StmtExecutorTest extends TestWithFeService 
{
 
     @Test
     public void testEmptyOriginStmtSkipsAuditMaskingReparse() throws Exception 
{
-        org.apache.doris.nereids.trees.plans.logical.LogicalPlan logicalPlan = 
Mockito.mock(
-                org.apache.doris.nereids.trees.plans.logical.LogicalPlan.class,
-                Mockito.withSettings().extraInterfaces(
-                        
org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption.class));
-        Mockito.doThrow(new AssertionError("empty SQL should not trigger audit 
masking reparse"))
-                
.when((org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption) 
logicalPlan)
-                .geneEncryptionSQL("");
-
-        org.apache.doris.analysis.StatementBase parsedStmt = new 
org.apache.doris.nereids.glue.LogicalPlanAdapter(
-                logicalPlan, new org.apache.doris.nereids.StatementContext());
-        parsedStmt.setOrigStmt(new OriginStatement("", 0));
-        StmtExecutor executor = new StmtExecutor(connectContext, parsedStmt);
-
-        // Empty internal SQL must bypass audit masking reparsing in both 
logging paths.
-        Method getStmtForLogging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
-        getStmtForLogging.setAccessible(true);
-        Assertions.assertEquals("", getStmtForLogging.invoke(executor, ""));
-
-        Method getStmtForLoggingBeforeParse = 
StmtExecutor.class.getDeclaredMethod("getStmtForLoggingBeforeParse");
-        getStmtForLoggingBeforeParse.setAccessible(true);
-        Assertions.assertEquals("", 
getStmtForLoggingBeforeParse.invoke(executor));
+        StmtExecutor executor = new StmtExecutor(connectContext, "");
+        try (MockedConstruction<NereidsParser> parsers = 
Mockito.mockConstruction(NereidsParser.class)) {
+            Method logging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
+            logging.setAccessible(true);
+            Assertions.assertEquals("", logging.invoke(executor, ""));
+            Method beforeParse = 
StmtExecutor.class.getDeclaredMethod("getStmtForLoggingBeforeParse");
+            beforeParse.setAccessible(true);
+            Assertions.assertEquals("", beforeParse.invoke(executor));
+            Assertions.assertTrue(parsers.constructed().isEmpty());
+        }
     }
 
     @Test
@@ -1651,6 +1642,9 @@ public class StmtExecutorTest extends TestWithFeService {
             
Assertions.assertTrue(appender.contains(org.apache.logging.log4j.Level.INFO, 
"*XXX"));
             
Assertions.assertFalse(appender.contains(org.apache.logging.log4j.Level.DEBUG, 
AI_RESOURCE_LOG_SECRET));
             
Assertions.assertTrue(appender.contains(org.apache.logging.log4j.Level.DEBUG, 
"*XXX"));
+            String expected = buildCreateAiResourceSql(resourceName, "*XXX");
+            Assertions.assertTrue(appender.contains(Level.INFO, expected));
+            Assertions.assertTrue(appender.contains(Level.DEBUG, expected));
         } finally {
             Config.enable_print_request_before_execution = 
originalPrintRequest;
         }
@@ -1681,24 +1675,20 @@ public class StmtExecutorTest extends TestWithFeService 
{
 
     @Test
     public void testGetStmtForLoggingFailsClosedWhenMaskingThrows() throws 
Exception {
-        org.apache.doris.nereids.trees.plans.logical.LogicalPlan logicalPlan = 
Mockito.mock(
-                org.apache.doris.nereids.trees.plans.logical.LogicalPlan.class,
-                Mockito.withSettings().extraInterfaces(
-                        
org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption.class));
-        Mockito.doThrow(new IllegalStateException("masking failed"))
-                
.when((org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption) 
logicalPlan)
-                .geneEncryptionSQL(Mockito.anyString());
-
-        org.apache.doris.analysis.StatementBase parsedStmt = new 
org.apache.doris.nereids.glue.LogicalPlanAdapter(
-                logicalPlan, new org.apache.doris.nereids.StatementContext());
-        parsedStmt.setOrigStmt(new OriginStatement("CREATE EXTERNAL RESOURCE 
\"ai_resource\" PROPERTIES ("
-                + "\"ai.api_key\" = \"" + AI_RESOURCE_LOG_SECRET + "\")", 0));
-        StmtExecutor executor = new StmtExecutor(connectContext, parsedStmt);
-
-        Method getStmtForLogging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
-        getStmtForLogging.setAccessible(true);
-        Assertions.assertEquals(MASKED_STMT_FALLBACK, 
getStmtForLogging.invoke(executor,
-                parsedStmt.getOrigStmt().originStmt));
+        String sql = buildCreateAiResourceSql("ai_resource", 
AI_RESOURCE_LOG_SECRET);
+        StmtExecutor executor = new StmtExecutor(connectContext, sql);
+        Method logging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
+        logging.setAccessible(true);
+        try (TestLogAppender appender = 
TestLogAppender.attach(StmtExecutor.class);
+                MockedConstruction<NereidsParser> parsers = 
Mockito.mockConstruction(NereidsParser.class,
+                        (parser, context) -> Mockito.doThrow(
+                                new IllegalStateException("masking failed: " + 
AI_RESOURCE_LOG_SECRET))
+                                
.when(parser).parseForEncryption(Mockito.anyString(), Mockito.anyMap(),
+                                        Mockito.eq(true)))) {
+            Assertions.assertEquals(MASKED_STMT_FALLBACK, 
logging.invoke(executor, sql));
+            Assertions.assertEquals(1, parsers.constructed().size());
+            assertMaskingFailureDoesNotLogSql(appender);
+        }
     }
 
     @Test
@@ -1709,7 +1699,89 @@ public class StmtExecutorTest extends TestWithFeService {
 
         Method getStmtForLoggingBeforeParse = 
StmtExecutor.class.getDeclaredMethod("getStmtForLoggingBeforeParse");
         getStmtForLoggingBeforeParse.setAccessible(true);
-        Assertions.assertEquals(MASKED_STMT_FALLBACK, 
getStmtForLoggingBeforeParse.invoke(executor));
+        try (TestLogAppender appender = 
TestLogAppender.attach(StmtExecutor.class)) {
+            Assertions.assertEquals(MASKED_STMT_FALLBACK, 
getStmtForLoggingBeforeParse.invoke(executor));
+            assertMaskingFailureDoesNotLogSql(appender);
+        }
+    }
+
+    @Test
+    public void testPlainSqlLoggingPreservesFormatting() throws Exception {
+        String sql = "/* keep */\nSELECT\n\t1 AS value;";
+        StmtExecutor executor = new StmtExecutor(connectContext, sql);
+        Method beforeParse = 
StmtExecutor.class.getDeclaredMethod("getStmtForLoggingBeforeParse");
+        beforeParse.setAccessible(true);
+        Assertions.assertEquals(sql, beforeParse.invoke(executor));
+    }
+
+    @Test
+    public void testLoggingDoesNotApplyExecutionHints() throws Exception {
+        int queryTimeout = 
connectContext.getSessionVariable().getQueryTimeoutS();
+        String sql = "SELECT /*+ SET_VAR(query_timeout=123) */\n1";
+        StmtExecutor executor = new StmtExecutor(connectContext, sql);
+        Method beforeParse = 
StmtExecutor.class.getDeclaredMethod("getStmtForLoggingBeforeParse");
+        beforeParse.setAccessible(true);
+        Assertions.assertEquals(sql, beforeParse.invoke(executor));
+        Assertions.assertEquals(queryTimeout, 
connectContext.getSessionVariable().getQueryTimeoutS());
+    }
+
+    @Test
+    public void testParsedExplainLogsMaskedSql() throws Exception {
+        String sql = "EXPLAIN SELECT * FROM S3(\n"
+                + "  'uri' = 's3://test-bucket/file.csv',\n"
+                + "  'format' = 'csv',\n"
+                + "  's3.secret_key' = '" + AI_RESOURCE_LOG_SECRET + "'\n)";
+        org.apache.doris.nereids.trees.plans.logical.LogicalPlan plan =
+                new NereidsParser().parseSingle(sql);
+        org.apache.doris.analysis.StatementBase parsed = new 
LogicalPlanAdapter(
+                plan, new org.apache.doris.nereids.StatementContext());
+        parsed.setOrigStmt(new OriginStatement(sql, 0));
+        StmtExecutor executor = new StmtExecutor(connectContext, parsed);
+        Method logging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
+        logging.setAccessible(true);
+        Assertions.assertEquals(sql.replace(AI_RESOURCE_LOG_SECRET, "*XXX"), 
logging.invoke(executor, sql));
+    }
+
+    @Test
+    public void testParsedCtasLogsMaskedSqlWhenAuditGateSkipsIt() throws 
Exception {
+        String sql = "CREATE TABLE testDb.log_ctas ENGINE=OLAP AS SELECT * 
FROM S3(\n"
+                + "  'uri' = 's3://test-bucket/file.csv', 'format' = 'csv',\n"
+                + "  's3.secret_key' = '" + AI_RESOURCE_LOG_SECRET + "'\n)";
+        org.apache.doris.nereids.trees.plans.logical.LogicalPlan plan = new 
NereidsParser().parseSingle(sql);
+        
Assertions.assertFalse(((org.apache.doris.nereids.trees.plans.commands.NeedAuditEncryption)
 plan)
+                .needAuditEncryption());
+        org.apache.doris.analysis.StatementBase parsed = new 
LogicalPlanAdapter(
+                plan, new org.apache.doris.nereids.StatementContext());
+        parsed.setOrigStmt(new OriginStatement(sql, 0));
+        StmtExecutor executor = new StmtExecutor(connectContext, parsed);
+        Method logging = 
StmtExecutor.class.getDeclaredMethod("getStmtForLogging", String.class);
+        logging.setAccessible(true);
+        Assertions.assertEquals(sql.replace(AI_RESOURCE_LOG_SECRET, "*XXX"), 
logging.invoke(executor, sql));
+    }
+
+    @Test
+    public void testSyntaxErrorLogsDoNotContainSql() throws Exception {
+        boolean printRequest = Config.enable_print_request_before_execution;
+        Config.enable_print_request_before_execution = true;
+        try (TestLogAppender appender = 
TestLogAppender.attach(StmtExecutor.class)) {
+            connectContext.getState().reset();
+            StmtExecutor executor = new StmtExecutor(connectContext,
+                    "CREATE USER 'broken_log_user' IDENTIFIED BY '" + 
AI_RESOURCE_LOG_SECRET + "' PROPERTIES (");
+            executor.execute();
+            Assertions.assertEquals(QueryState.MysqlStateType.ERR, 
connectContext.getState().getStateType());
+            Assertions.assertFalse(appender.contains(Level.INFO, 
AI_RESOURCE_LOG_SECRET));
+            Assertions.assertFalse(appender.contains(Level.DEBUG, 
AI_RESOURCE_LOG_SECRET));
+            assertMaskingFailureDoesNotLogSql(appender);
+        } finally {
+            Config.enable_print_request_before_execution = printRequest;
+        }
+    }
+
+    private void assertMaskingFailureDoesNotLogSql(TestLogAppender appender) {
+        Assertions.assertTrue(appender.contains(Level.WARN, "FE logging"));
+        Assertions.assertFalse(appender.contains(Level.WARN, 
AI_RESOURCE_LOG_SECRET));
+        List<LogEvent> events = Deencapsulation.getField(appender, "events");
+        Assertions.assertTrue(events.stream().allMatch(event -> 
event.getThrown() == null));
     }
 
     @Test


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to