924060929 commented on code in PR #71148:
URL: https://github.com/apache/doris/pull/71148#discussion_r4766943865


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/AuditSqlRedactor.java:
##########
@@ -0,0 +1,157 @@
+// 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.doris.nereids.parser;
+
+import org.apache.doris.common.Pair;
+import org.apache.doris.common.util.DatasourcePrintableMap;
+import org.apache.doris.load.routineload.kafka.KafkaConfiguration;
+import org.apache.doris.nereids.DorisParser;
+import org.apache.doris.nereids.DorisParserBaseVisitor;
+import org.apache.doris.nereids.trees.plans.commands.info.BaseViewInfo;
+import org.apache.doris.nereids.util.SqlLiteralUtils;
+
+import com.google.common.collect.ImmutableMap;
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.Token;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** Collects credential ranges from command syntax, including property lists 
nested inside other clauses. */
+public final class AuditSqlRedactor extends DorisParserBaseVisitor<Void> {
+    private final TreeMap<Pair<Integer, Integer>, String> replacements = new 
TreeMap<>(new Pair.PairComparator<>());
+    private boolean hasCredentials;
+
+    private AuditSqlRedactor() {
+    }
+
+    /** SQL safe for the audit event, with the credential flag used to 
suppress unsafe error details. */
+    public record RedactedCommand(String sql, boolean hasCredentials) {
+    }
+
+    /** Collect credential ranges from the parsed statement and apply them to 
the original SQL. */
+    public static RedactedCommand redactCommand(String sql, boolean 
normalizeProperties) {

Review Comment:
   [P1] Parallel SQL masking paths are out of sync and still leak the newly 
covered credentials into `fe.log`.
   
   `StmtExecutor.getStmtForLogging` (and `TableQueryPlanAction`) still call 
`NeedAuditEncryption.maskSql(stmt, true)` -> 
`LogicalPlanBuilderForEncryption(..., preserveFormatting=true)`, which does not 
handle `CREATE ENCRYPTKEY`, `storageBackend` / `installPlugin` URI tokens, 
`isAdditionalCredentialProperty` (`ak`, `sk`, Kafka `property.*`), or 
`DatasourcePrintableMap.redactProperty` (`jdbc_url` passwords).
   
   Please unify SQL redaction behind a single implementation (e.g., delegate 
`NeedAuditEncryption.maskSql` to `AuditSqlRedactor`) instead of maintaining two 
overlapping AST visitors.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/AuditSqlRedactor.java:
##########
@@ -0,0 +1,157 @@
+// 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.doris.nereids.parser;
+
+import org.apache.doris.common.Pair;
+import org.apache.doris.common.util.DatasourcePrintableMap;
+import org.apache.doris.load.routineload.kafka.KafkaConfiguration;
+import org.apache.doris.nereids.DorisParser;
+import org.apache.doris.nereids.DorisParserBaseVisitor;
+import org.apache.doris.nereids.trees.plans.commands.info.BaseViewInfo;
+import org.apache.doris.nereids.util.SqlLiteralUtils;
+
+import com.google.common.collect.ImmutableMap;
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.antlr.v4.runtime.Token;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** Collects credential ranges from command syntax, including property lists 
nested inside other clauses. */
+public final class AuditSqlRedactor extends DorisParserBaseVisitor<Void> {
+    private final TreeMap<Pair<Integer, Integer>, String> replacements = new 
TreeMap<>(new Pair.PairComparator<>());
+    private boolean hasCredentials;
+
+    private AuditSqlRedactor() {
+    }
+
+    /** SQL safe for the audit event, with the credential flag used to 
suppress unsafe error details. */
+    public record RedactedCommand(String sql, boolean hasCredentials) {
+    }
+
+    /** Collect credential ranges from the parsed statement and apply them to 
the original SQL. */
+    public static RedactedCommand redactCommand(String sql, boolean 
normalizeProperties) {
+        if (sql == null || sql.isEmpty()) {
+            return new RedactedCommand(sql, false);
+        }
+        AuditSqlRedactor redactor = new AuditSqlRedactor();
+        ParserRuleContext tree = NereidsParser.toAst(sql, 
DorisParser::singleStatement);
+        if (normalizeProperties) {
+            // Keep existing audit formatting when the command has a 
property-list renderer.
+            try {
+                new LogicalPlanBuilderForEncryption(ImmutableMap.of(), 
redactor.replacements).visit(tree);
+            } catch (RuntimeException e) {
+                // A syntax walk also works for commands that cannot be 
rebuilt in the audit context.
+                redactor.replacements.clear();
+            }
+        }
+        redactor.visit(tree);
+        return new 
RedactedCommand(BaseViewInfo.rewriteSql(redactor.replacements, sql), 
redactor.hasCredentials);
+    }
+
+    @Override
+    public Void visitPropertyItem(DorisParser.PropertyItemContext ctx) {
+        if (ctx.key.constant() instanceof DorisParser.PlaceholderContext
+                || ctx.value.constant() instanceof 
DorisParser.PlaceholderContext) {
+            // The template alone cannot determine whether a bound property 
contains a credential.
+            replace(ctx.value.start, ctx.value.stop, 
DatasourcePrintableMap.PASSWORD_MASK);
+            return null;
+        }
+        String key = LogicalPlanBuilder.decodePropertyKey(ctx.key);
+        String value = LogicalPlanBuilder.decodePropertyValue(ctx.value);
+        boolean sensitive = isAdditionalCredentialProperty(key) || 
DatasourcePrintableMap.HIDDEN_KEY.contains(key);
+        String masked = sensitive ? DatasourcePrintableMap.PASSWORD_MASK
+                : DatasourcePrintableMap.redactProperty(key, value);
+        if (sensitive || !masked.equals(value)) {
+            replace(ctx.value.start, ctx.value.stop, masked);
+        }
+        return null;
+    }
+
+    static boolean isAdditionalCredentialProperty(String key) {
+        // The short names are used by stage and KMS commands. Routine Load 
uses a pass-through namespace.
+        String lowerKey = key.toLowerCase(Locale.ROOT);
+        return "ak".equals(lowerKey) || "sk".equals(lowerKey)
+                || (lowerKey.startsWith("property.") && 
KafkaConfiguration.isSensitiveProperty(
+                        key.substring("property.".length())));
+    }
+
+    @Override
+    public Void visitGrantUserIdentify(DorisParser.GrantUserIdentifyContext 
ctx) {
+        if (ctx.pwd != null) {
+            mask(ctx.pwd);
+        }
+        return null;
+    }
+
+    @Override
+    public Void visitSetPassword(DorisParser.SetPasswordContext ctx) {
+        mask(ctx.pwd);
+        return null;
+    }
+
+    @Override
+    public Void 
visitSetLdapAdminPassword(DorisParser.SetLdapAdminPasswordContext ctx) {
+        mask(ctx.pwd);
+        return null;
+    }
+
+    @Override
+    public Void visitCreateEncryptkey(DorisParser.CreateEncryptkeyContext ctx) 
{
+        mask(ctx.STRING_LITERAL().getSymbol());
+        return null;
+    }
+
+    @Override
+    public Void visitStorageBackend(DorisParser.StorageBackendContext ctx) {
+        redactLocation(ctx.STRING_LITERAL().getSymbol());
+        return visitChildren(ctx);
+    }
+
+    @Override
+    public Void visitInstallPlugin(DorisParser.InstallPluginContext ctx) {
+        redactLocation(ctx.source.start);
+        return visitChildren(ctx);
+    }
+
+    private void redactLocation(Token location) {
+        String value = decode(location.getText());
+        String masked = DatasourcePrintableMap.redactProperty("location", 
value);
+        if (!value.equals(masked)) {
+            replace(location, location, masked);
+        }
+    }
+
+    private void replace(Token first, Token last, String value) {
+        hasCredentials = true;
+        Pair<Integer, Integer> range = Pair.of(first.getStartIndex(), 
last.getStopIndex());
+        Map.Entry<Pair<Integer, Integer>, String> enclosing = 
replacements.ceilingEntry(range);

Review Comment:
   [P3] Consider adding a brief comment explaining that `ceilingEntry(range)` 
finds an enclosing range only because `Pair.PairComparator` orders by 
`Pair.second` (stop index) rather than `Pair.first`. Otherwise this check looks 
inverted at first glance and is easy to break accidentally.



##########
fe/fe-core/src/main/java/org/apache/doris/qe/AuditLogHelper.java:
##########
@@ -395,25 +417,30 @@ private static void logAuditLogImpl(ConnectContext ctx, 
String origStmt, Stateme
 
         boolean isSyntaxErr = ctx.getState().getStateType() == 
MysqlStateType.ERR
                 && ctx.getState().getErrType() == 
QueryState.ErrType.SYNTAX_PARSE_ERR;
-        String encryptSql = isSyntaxErr ? "Syntax Error" : origStmt;
+        String encryptSql = origStmt;
+        RedactedCommand redactedCommand = null;
         if (isSyntaxErr) {
-            auditEventBuilder.setErrorMessage("Syntax Error");
-        }
-        // We put origin query stmt at the end of audit log, for parsing the 
log more convenient.
-        if (auditSqlRedactor != null) {
-            // A resolved file batch has trusted structure that a generic URI 
parser cannot recover from SQL text.
-            encryptSql = isSyntaxErr ? "Syntax Error" : 
auditSqlRedactor.apply(origStmt);
+            encryptSql = "Syntax Error";
+        } else if (renderSql != null) {
+            redactedCommand = renderSql.get();
         } else if (parsedStmt instanceof LogicalPlanAdapter) {
             LogicalPlan logicalPlan = ((LogicalPlanAdapter) 
parsedStmt).getLogicalPlan();
-            if ((logicalPlan instanceof NeedAuditEncryption)) {
+            if (logicalPlan instanceof Command) {
+                boolean normalizeProperties = logicalPlan instanceof 
NeedAuditEncryption
+                        && ((NeedAuditEncryption) 
logicalPlan).needAuditEncryption();
+                // Plain inserts can carry large VALUES batches and have no 
credential-bearing sources.
+                if (normalizeProperties || logicalPlan.stmtType() != 
StmtType.INSERT) {

Review Comment:
   [P2] Re-parsing every non-`INSERT` `Command` (`SET`, `USE`, `SHOW`, 
`UPDATE`, `DELETE`, `EXPLAIN <large query>`, `CREATE VIEW/MTMV`, etc.) on the 
audit hot path adds unnecessary ANTLR parse overhead (and `NeedAuditEncryption` 
commands walk the AST twice: `LogicalPlanBuilderForEncryption` + 
`AuditSqlRedactor`).
   
   Also, in the `parsedStmt == null` branch below, multi-statement SQL (`stmt1; 
stmt2`) will fail `DorisParser::singleStatement` and be misreported as 
`[statement redacted]`.



##########
fe/fe-core/src/main/java/org/apache/doris/qe/AuditLogHelper.java:
##########
@@ -395,25 +417,30 @@ private static void logAuditLogImpl(ConnectContext ctx, 
String origStmt, Stateme
 
         boolean isSyntaxErr = ctx.getState().getStateType() == 
MysqlStateType.ERR
                 && ctx.getState().getErrType() == 
QueryState.ErrType.SYNTAX_PARSE_ERR;
-        String encryptSql = isSyntaxErr ? "Syntax Error" : origStmt;
+        String encryptSql = origStmt;
+        RedactedCommand redactedCommand = null;
         if (isSyntaxErr) {
-            auditEventBuilder.setErrorMessage("Syntax Error");
-        }
-        // We put origin query stmt at the end of audit log, for parsing the 
log more convenient.
-        if (auditSqlRedactor != null) {
-            // A resolved file batch has trusted structure that a generic URI 
parser cannot recover from SQL text.
-            encryptSql = isSyntaxErr ? "Syntax Error" : 
auditSqlRedactor.apply(origStmt);
+            encryptSql = "Syntax Error";
+        } else if (renderSql != null) {
+            redactedCommand = renderSql.get();
         } else if (parsedStmt instanceof LogicalPlanAdapter) {
             LogicalPlan logicalPlan = ((LogicalPlanAdapter) 
parsedStmt).getLogicalPlan();
-            if ((logicalPlan instanceof NeedAuditEncryption)) {
+            if (logicalPlan instanceof Command) {
+                boolean normalizeProperties = logicalPlan instanceof 
NeedAuditEncryption
+                        && ((NeedAuditEncryption) 
logicalPlan).needAuditEncryption();
+                // Plain inserts can carry large VALUES batches and have no 
credential-bearing sources.
+                if (normalizeProperties || logicalPlan.stmtType() != 
StmtType.INSERT) {
+                    redactedCommand = redactCommandSql(origStmt, 
normalizeProperties);

Review Comment:
   [P1] Non-prepared commands do not restore 
`StatementContext.getParsedSqlMode(...)` before re-parsing `origStmt` here.
   
   If a command mutates the session `sql_mode` during execution (e.g., `SET 
sql_mode = 'NO_BACKSLASH_ESCAPES', var = 'a\'b'`), `logAuditLogImpl` runs after 
execution with the new `sql_mode`, causing `AuditSqlRedactor` to throw 
`SyntaxParseException` and silently replace the audit SQL with `[statement 
redacted]`.
   
   Wrap this call with `SqlModeHelper.withSqlMode(((LogicalPlanAdapter) 
parsedStmt).getStatementContext().getParsedSqlMode(SqlModeHelper.getEffectiveSqlMode()),
 ...)` just like `renderPreparedAuditSql`.



##########
fe/fe-core/src/main/java/org/apache/doris/mysql/authenticate/ldap/LdapClient.java:
##########
@@ -146,8 +146,14 @@ private void init() {
             throw new RuntimeException("LDAP configuration is incorrect or 
LDAP admin password is not set.");
         }
 
-        String ldapPassword = 
SymmetricEncryption.decrypt(ldapInfo.getLdapPasswdEncrypted(),
-                ldapInfo.getSecretKey(), ldapInfo.getIv());
+        String ldapPassword;
+        try {
+            ldapPassword = ldapInfo.decryptPassword();

Review Comment:
   [P3] `init()` now performs disk I/O (`Files.readString`) and AES-GCM 
decryption on every call, even when `ldapInfo` has not changed and `clientInfo` 
is already initialized. Since `Auth.ldapInfo` is replaced with a new immutable 
`LdapInfo` instance on update, comparing the `LdapInfo` reference before 
decrypting avoids redundant file reads and decryption.



##########
fe/fe-core/src/main/java/org/apache/doris/qe/AuditLogHelper.java:
##########
@@ -395,25 +417,30 @@ private static void logAuditLogImpl(ConnectContext ctx, 
String origStmt, Stateme
 
         boolean isSyntaxErr = ctx.getState().getStateType() == 
MysqlStateType.ERR
                 && ctx.getState().getErrType() == 
QueryState.ErrType.SYNTAX_PARSE_ERR;
-        String encryptSql = isSyntaxErr ? "Syntax Error" : origStmt;
+        String encryptSql = origStmt;
+        RedactedCommand redactedCommand = null;
         if (isSyntaxErr) {
-            auditEventBuilder.setErrorMessage("Syntax Error");
-        }
-        // We put origin query stmt at the end of audit log, for parsing the 
log more convenient.
-        if (auditSqlRedactor != null) {
-            // A resolved file batch has trusted structure that a generic URI 
parser cannot recover from SQL text.
-            encryptSql = isSyntaxErr ? "Syntax Error" : 
auditSqlRedactor.apply(origStmt);
+            encryptSql = "Syntax Error";
+        } else if (renderSql != null) {
+            redactedCommand = renderSql.get();
         } else if (parsedStmt instanceof LogicalPlanAdapter) {
             LogicalPlan logicalPlan = ((LogicalPlanAdapter) 
parsedStmt).getLogicalPlan();
-            if ((logicalPlan instanceof NeedAuditEncryption)) {
+            if (logicalPlan instanceof Command) {
+                boolean normalizeProperties = logicalPlan instanceof 
NeedAuditEncryption
+                        && ((NeedAuditEncryption) 
logicalPlan).needAuditEncryption();
+                // Plain inserts can carry large VALUES batches and have no 
credential-bearing sources.
+                if (normalizeProperties || logicalPlan.stmtType() != 
StmtType.INSERT) {
+                    redactedCommand = redactCommandSql(origStmt, 
normalizeProperties);
+                }
+            } else if (logicalPlan instanceof NeedAuditEncryption) {

Review Comment:
   [P2] Non-`Command` plans that implement `NeedAuditEncryption` (e.g., `SELECT 
* FROM s3(...)` / `SELECT ... INTO OUTFILE ...`) leave `redactedCommand` as 
`null`, so if they fail with an error message containing credentials, the 
error-message redaction below is bypassed.



-- 
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]

Reply via email to