This is an automated email from the ASF dual-hosted git repository.
sadadw1 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozhera.git
The following commit(s) were added to refs/heads/master by this push:
new d2afa0e2 refactor: build log query SQL with parameterized statements
(#690)
d2afa0e2 is described below
commit d2afa0e22a67696174a657a8e570287942c71f5b
Author: EricDing <[email protected]>
AuthorDate: Thu Oct 8 19:57:07 2026 +0800
refactor: build log query SQL with parameterized statements (#690)
* refactor: refactor ozhera intelligence
* feat: add coder tool and git mcp
* fix: update codefix agent and tool
* fix: add git suffix
* refactor: add log query tool
* fix: add endTime and update desc
* feat: add git checkout new branch and create MR flow
* fix: update intelligence compiler error
* fix: 删除SNAPSHOT
* refactor: build log query SQL with parameterized statements
Use PreparedStatement bind parameters for the Doris log query and
statistics paths, and validate sort key / tail / index identifiers
against an allow-list, instead of concatenating request input into
the SQL text.
---
.../manager/common/utils/LogQuerySqlBuilder.java | 251 +++++++++++++++++++++
.../manager/service/impl/EsDataServiceImpl.java | 127 +++++++----
.../common/utils/LogQuerySqlBuilderTest.java | 114 ++++++++++
3 files changed, 446 insertions(+), 46 deletions(-)
diff --git
a/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilder.java
b/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilder.java
new file mode 100644
index 00000000..13f1983c
--- /dev/null
+++
b/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilder.java
@@ -0,0 +1,251 @@
+/*
+ * 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.ozhera.log.manager.common.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Helper that turns user-supplied log-query input into parameterized SQL for
the
+ * Doris-backed log query path, so that the input cannot be used for SQL
injection.
+ *
+ * <p>Values are always emitted as JDBC bind parameters ({@code ?}) and never
+ * concatenated into the statement text. Identifiers (table/column names) are
+ * validated against a strict allow-list. Any input that cannot be safely
+ * represented is rejected (fail-closed) rather than passed through.</p>
+ *
+ * <p>Supported full-text search grammar:</p>
+ * <pre>
+ * expr := condition ( (AND|OR) condition )*
+ * condition := identifier operator value
+ * operator := = | != | <> | > | >= | < | <= | LIKE
+ * value := 'single-quoted' | "double-quoted" | number
+ * identifier := [A-Za-z_][A-Za-z0-9_]*
+ * </pre>
+ *
+ * <p>NOTE: this grammar covers the search expressions the front-end is known
to
+ * send (e.g. {@code level="ERROR"}). If a deployment relies on richer syntax
+ * (parentheses, IN(...), sub-queries, ...) those queries will be rejected and
the
+ * grammar must be extended deliberately — never by falling back to raw
+ * concatenation.</p>
+ */
+public final class LogQuerySqlBuilder {
+
+ /** Bare column / table identifier. */
+ private static final Pattern IDENTIFIER =
Pattern.compile("^[A-Za-z_][A-Za-z0-9_]*$");
+
+ /**
+ * Index / table name coming from server-side store configuration. Slightly
+ * broader than {@link #IDENTIFIER} to allow the dots and hyphens commonly
+ * found in index names, while still forbidding whitespace, quotes,
parentheses
+ * and statement terminators.
+ */
+ private static final Pattern INDEX_NAME =
Pattern.compile("^[A-Za-z0-9_.\\-]+$");
+
+ /** identifier operator value */
+ private static final Pattern CONDITION =
+
Pattern.compile("^([A-Za-z_][A-Za-z0-9_]*)\\s*(=|!=|<>|>=|<=|>|<|(?i:like))\\s*(.+)$");
+
+ private LogQuerySqlBuilder() {
+ }
+
+ /**
+ * A fragment of SQL together with the ordered bind parameters it
references.
+ */
+ public static final class SqlWithArgs {
+ private final String sql;
+ private final List<Object> args;
+
+ public SqlWithArgs(String sql, List<Object> args) {
+ this.sql = sql;
+ this.args = args;
+ }
+
+ public String getSql() {
+ return sql;
+ }
+
+ public List<Object> getArgs() {
+ return args;
+ }
+ }
+
+ /**
+ * Validate a table/index name that must be inlined into the statement text
+ * (table names cannot be bound as parameters).
+ *
+ * @throws IllegalArgumentException if the value is not a safe index name
+ */
+ public static String safeIndexName(String value) {
+ if (value == null || !INDEX_NAME.matcher(value).matches()) {
+ throw new IllegalArgumentException("Illegal log store index name:
" + value);
+ }
+ return value;
+ }
+
+ /**
+ * Validate a column identifier (sort key, tail field, ...) that must be
+ * inlined into the statement text.
+ *
+ * @throws IllegalArgumentException if the value is not a safe identifier
+ */
+ public static String safeIdentifier(String value, String field) {
+ if (value == null || !IDENTIFIER.matcher(value).matches()) {
+ throw new IllegalArgumentException("Illegal identifier for " +
field + ": " + value);
+ }
+ return value;
+ }
+
+ /**
+ * Parse the full-text search expression into a parameterized SQL fragment.
+ *
+ * @return the fragment and its bind parameters, or {@code null} when the
+ * expression is blank
+ * @throws IllegalArgumentException if the expression does not match the
+ * supported grammar
+ */
+ public static SqlWithArgs buildFullTextSearch(String expr) {
+ if (expr == null || expr.trim().isEmpty()) {
+ return null;
+ }
+ List<String> tokens = splitTopLevel(expr.trim());
+ StringBuilder sql = new StringBuilder();
+ List<Object> args = new ArrayList<>();
+ for (int idx = 0; idx < tokens.size(); idx++) {
+ String token = tokens.get(idx).trim();
+ if (idx % 2 == 1) {
+ // connector: already normalized to AND / OR by the scanner
+ sql.append(' ').append(token).append(' ');
+ continue;
+ }
+ Matcher matcher = CONDITION.matcher(token);
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("Illegal search expression:
" + token);
+ }
+ String field = matcher.group(1);
+ String operator = normalizeOperator(matcher.group(2));
+ Object value = parseValue(matcher.group(3).trim());
+ sql.append(field).append(' ').append(operator).append(" ?");
+ args.add(value);
+ }
+ return new SqlWithArgs(sql.toString(), args);
+ }
+
+ /**
+ * Split an expression into alternating condition / connector tokens at
the top
+ * level, i.e. ignoring AND / OR that appear inside quoted values. The
result
+ * is [condition, connector, condition, ...] with connectors at odd
indices.
+ */
+ private static List<String> splitTopLevel(String expr) {
+ List<String> tokens = new ArrayList<>();
+ StringBuilder current = new StringBuilder();
+ char quote = 0;
+ int i = 0;
+ int n = expr.length();
+ while (i < n) {
+ char c = expr.charAt(i);
+ if (quote != 0) {
+ current.append(c);
+ if (c == quote) {
+ quote = 0;
+ }
+ i++;
+ continue;
+ }
+ if (c == '\'' || c == '"') {
+ quote = c;
+ current.append(c);
+ i++;
+ continue;
+ }
+ if (c == ' ' || c == '\t') {
+ int j = i;
+ while (j < n && (expr.charAt(j) == ' ' || expr.charAt(j) ==
'\t')) {
+ j++;
+ }
+ String connector = matchConnector(expr, j);
+ int after = j + (connector == null ? 0 : connector.length());
+ if (connector != null && after < n
+ && (expr.charAt(after) == ' ' || expr.charAt(after) ==
'\t')) {
+ tokens.add(current.toString());
+ tokens.add(connector.toUpperCase());
+ current.setLength(0);
+ i = after;
+ continue;
+ }
+ }
+ current.append(c);
+ i++;
+ }
+ tokens.add(current.toString());
+ return tokens;
+ }
+
+ /**
+ * @return "AND" / "OR" if the expression contains that keyword at position
+ * {@code pos} (case-insensitive), otherwise {@code null}
+ */
+ private static String matchConnector(String expr, int pos) {
+ if (expr.regionMatches(true, pos, "AND", 0, 3)) {
+ return "AND";
+ }
+ if (expr.regionMatches(true, pos, "OR", 0, 2)) {
+ return "OR";
+ }
+ return null;
+ }
+
+ private static String normalizeOperator(String operator) {
+ return operator.equalsIgnoreCase("like") ? "LIKE" : operator;
+ }
+
+ /**
+ * Convert a raw value token into its bind value. Strings must be quoted
+ * (single or double); a matching quote inside the literal may be escaped
by
+ * doubling it. Unquoted tokens are only accepted when numeric.
+ */
+ private static Object parseValue(String raw) {
+ if (raw.length() >= 2) {
+ char first = raw.charAt(0);
+ char last = raw.charAt(raw.length() - 1);
+ if ((first == '"' || first == '\'') && last == first) {
+ String inner = raw.substring(1, raw.length() - 1);
+ String doubled = String.valueOf(first) + first;
+ // A lone (unescaped) quote inside the literal means the token
is malformed.
+ if (inner.replace(doubled, "").indexOf(first) >= 0) {
+ throw new IllegalArgumentException("Malformed quoted
value: " + raw);
+ }
+ return inner.replace(doubled, String.valueOf(first));
+ }
+ }
+ try {
+ return Long.parseLong(raw);
+ } catch (NumberFormatException ignored) {
+ // not a long
+ }
+ try {
+ return Double.parseDouble(raw);
+ } catch (NumberFormatException ignored) {
+ // not a number either
+ }
+ throw new IllegalArgumentException("Search value must be quoted or
numeric: " + raw);
+ }
+}
diff --git
a/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/service/impl/EsDataServiceImpl.java
b/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/service/impl/EsDataServiceImpl.java
index 46095cfd..e549c661 100644
---
a/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/service/impl/EsDataServiceImpl.java
+++
b/ozhera-log/log-manager/src/main/java/org/apache/ozhera/log/manager/service/impl/EsDataServiceImpl.java
@@ -41,6 +41,8 @@ import org.apache.ozhera.log.exception.CommonError;
import org.apache.ozhera.log.manager.common.context.MoneUserContext;
import org.apache.ozhera.log.manager.common.exception.MilogManageException;
import org.apache.ozhera.log.manager.common.utils.ExportUtils;
+import org.apache.ozhera.log.manager.common.utils.LogQuerySqlBuilder;
+import
org.apache.ozhera.log.manager.common.utils.LogQuerySqlBuilder.SqlWithArgs;
import org.apache.ozhera.log.manager.dao.MilogLogTailDao;
import org.apache.ozhera.log.manager.dao.MilogLogstoreDao;
import org.apache.ozhera.log.manager.dao.MilogSpaceDao;
@@ -82,10 +84,10 @@ import org.springframework.util.StopWatch;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
+import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
-import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;
@@ -337,61 +339,93 @@ public class EsDataServiceImpl implements EsDataService,
LogDataService, EsDataB
private List<Map<String, Object>> queryResult(LogQuery logQuery,
MilogLogStoreDO milogLogstoreDO, DataSource dataSource) throws SQLException {
List<Map<String, Object>> columns = new ArrayList<>();
- String querySql = buildQuerySql(logQuery, milogLogstoreDO);
+ SqlWithArgs querySql = buildQuerySql(logQuery, milogLogstoreDO);
- try (Statement statement =
dataSource.getConnection().createStatement();
- ResultSet resultSet = statement.executeQuery(querySql)) {
+ try (PreparedStatement statement =
dataSource.getConnection().prepareStatement(querySql.getSql())) {
+ bindArgs(statement, querySql.getArgs());
+ try (ResultSet resultSet = statement.executeQuery()) {
+ ResultSetMetaData metaData = resultSet.getMetaData();
+ int columnCount = metaData.getColumnCount();
- ResultSetMetaData metaData = resultSet.getMetaData();
- int columnCount = metaData.getColumnCount();
-
- while (resultSet.next()) {
- Map<String, Object> dataMap = new HashMap<>();
- for (int i = 1; i <= columnCount; i++) {
- dataMap.put(metaData.getColumnName(i),
resultSet.getObject(i));
+ while (resultSet.next()) {
+ Map<String, Object> dataMap = new HashMap<>();
+ for (int i = 1; i <= columnCount; i++) {
+ dataMap.put(metaData.getColumnName(i),
resultSet.getObject(i));
+ }
+ columns.add(dataMap);
}
- columns.add(dataMap);
}
}
return columns;
}
- private static String buildQuerySql(LogQuery logQuery, MilogLogStoreDO
milogLogstoreDO) {
- String sqlPrefix = getConditional(logQuery);
- String sortSql = StringUtils.isNotEmpty(logQuery.getSortKey()) ?
String.format("ORDER BY %s", logQuery.getSortKey()) : "";
- if (StringUtils.isNotEmpty(sortSql) && !logQuery.getAsc()) {
- sortSql += " DESC";
+ /**
+ * Bind the ordered parameters produced by {@link LogQuerySqlBuilder} onto
a
+ * {@link PreparedStatement}. Keeping user input in bind parameters
(instead of
+ * concatenating it into the statement text) is what prevents SQL
injection.
+ */
+ private static void bindArgs(PreparedStatement statement, List<Object>
args) throws SQLException {
+ for (int i = 0; i < args.size(); i++) {
+ statement.setObject(i + 1, args.get(i));
}
- String limitSql = String.format("LIMIT %s, %s", (logQuery.getPage() -
1) * logQuery.getPageSize(), logQuery.getPageSize());
- if (StringUtils.isNotEmpty(logQuery.getFullTextSearch())) {
- return String.format("SELECT * FROM %s WHERE %s AND %s %s %s",
- milogLogstoreDO.getEsIndex(), sqlPrefix,
logQuery.getFullTextSearch(), sortSql, limitSql);
+ }
+
+ private static SqlWithArgs buildQuerySql(LogQuery logQuery,
MilogLogStoreDO milogLogstoreDO) {
+ String table =
LogQuerySqlBuilder.safeIndexName(milogLogstoreDO.getEsIndex());
+ SqlWithArgs conditional = getConditional(logQuery);
+ List<Object> args = new ArrayList<>(conditional.getArgs());
+
+ StringBuilder sql = new StringBuilder();
+ SqlWithArgs fullText =
LogQuerySqlBuilder.buildFullTextSearch(logQuery.getFullTextSearch());
+ if (fullText != null) {
+ sql.append(String.format("SELECT * FROM %s WHERE %s AND %s",
table, conditional.getSql(), fullText.getSql()));
+ args.addAll(fullText.getArgs());
} else {
- return String.format("SELECT * FROM %s WHERE %s %s %s",
- milogLogstoreDO.getEsIndex(), sqlPrefix, sortSql,
limitSql);
+ sql.append(String.format("SELECT * FROM %s WHERE %s", table,
conditional.getSql()));
}
+
+ if (StringUtils.isNotEmpty(logQuery.getSortKey())) {
+ sql.append(" ORDER BY
").append(LogQuerySqlBuilder.safeIdentifier(logQuery.getSortKey(), "sortKey"));
+ if (!logQuery.getAsc()) {
+ sql.append(" DESC");
+ }
+ }
+
+ sql.append(" LIMIT ?, ?");
+ args.add((logQuery.getPage() - 1) * logQuery.getPageSize());
+ args.add(logQuery.getPageSize());
+ return new SqlWithArgs(sql.toString(), args);
}
- private static String buildQuerySqlConditional(LogQuery logQuery,
MilogLogStoreDO milogLogstoreDO) {
- String sqlPrefix = getConditional(logQuery);
- if (StringUtils.isNotEmpty(logQuery.getFullTextSearch())) {
- return String.format("SELECT * FROM %s WHERE %s AND %s",
- milogLogstoreDO.getEsIndex(), sqlPrefix,
logQuery.getFullTextSearch());
+ private static SqlWithArgs buildQuerySqlConditional(LogQuery logQuery,
MilogLogStoreDO milogLogstoreDO) {
+ String table =
LogQuerySqlBuilder.safeIndexName(milogLogstoreDO.getEsIndex());
+ SqlWithArgs conditional = getConditional(logQuery);
+ List<Object> args = new ArrayList<>(conditional.getArgs());
+
+ SqlWithArgs fullText =
LogQuerySqlBuilder.buildFullTextSearch(logQuery.getFullTextSearch());
+ String sql;
+ if (fullText != null) {
+ sql = String.format("SELECT * FROM %s WHERE %s AND %s", table,
conditional.getSql(), fullText.getSql());
+ args.addAll(fullText.getArgs());
} else {
- return String.format("SELECT * FROM %s WHERE %s ",
- milogLogstoreDO.getEsIndex(), sqlPrefix);
+ sql = String.format("SELECT * FROM %s WHERE %s ", table,
conditional.getSql());
}
+ return new SqlWithArgs(sql, args);
}
- private static String getConditional(LogQuery logQuery) {
- String sqlPrefix = String.format("timestamp >= %s AND timestamp <=
%s", logQuery.getStartTime(), logQuery.getEndTime());
+ private static SqlWithArgs getConditional(LogQuery logQuery) {
+ List<Object> args = new ArrayList<>();
+ StringBuilder sql = new StringBuilder("timestamp >= ? AND timestamp <=
?");
+ args.add(logQuery.getStartTime());
+ args.add(logQuery.getEndTime());
if (StringUtils.isNotEmpty(logQuery.getTail())) {
- String tailIdFields =
Arrays.stream(logQuery.getTail().split(",")).map(tail ->
org.apache.commons.lang3.StringUtils.wrap(tail,
"\"")).collect(Collectors.joining(","));
- String tailSql = String.format(" AND tail IN (%s)", tailIdFields);
- sqlPrefix += tailSql;
+ String[] tails = logQuery.getTail().split(",");
+ String placeholders = Arrays.stream(tails).map(tail ->
"?").collect(Collectors.joining(","));
+ sql.append(String.format(" AND tail IN (%s)", placeholders));
+ Collections.addAll(args, tails);
}
- return sqlPrefix;
+ return new SqlWithArgs(sql.toString(), args);
}
@@ -501,11 +535,11 @@ public class EsDataServiceImpl implements EsDataService,
LogDataService, EsDataB
private void handleDorisStat(EsStatisticResult result, LogQuery logQuery,
MilogLogStoreDO logStore) throws SQLException {
DataSource dataSource =
Ioc.ins().getBean(Constant.LOG_STORAGE_SERV_BEAN_PRE +
logStore.getEsClusterId());
- String querySql = buildQuerySqlConditional(logQuery, logStore);
- String staticSql = buildDorisStatSql(querySql);
+ SqlWithArgs querySql = buildQuerySqlConditional(logQuery, logStore);
+ String staticSql = buildDorisStatSql(querySql.getSql());
log.info("staticSql:{}", staticSql);
List<String> timestamps = Lists.newArrayList();
- List<Long> counts = executeDorisStatQuery(dataSource, staticSql,
timestamps);
+ List<Long> counts = executeDorisStatQuery(dataSource, staticSql,
querySql.getArgs(), timestamps);
result.setCounts(counts);
result.setTimestamps(timestamps);
@@ -521,14 +555,15 @@ public class EsDataServiceImpl implements EsDataService,
LogDataService, EsDataB
"ORDER BY time_bucket";
}
- private List<Long> executeDorisStatQuery(DataSource dataSource, String
staticSql, List<String> timestamps) throws SQLException {
+ private List<Long> executeDorisStatQuery(DataSource dataSource, String
staticSql, List<Object> args, List<String> timestamps) throws SQLException {
List<Long> counts = new ArrayList<>();
- try (Statement statement =
dataSource.getConnection().createStatement();
- ResultSet resultSet = statement.executeQuery(staticSql)) {
-
- while (resultSet.next()) {
- timestamps.add(resultSet.getString("time_bucket"));
- counts.add(resultSet.getLong("data_count"));
+ try (PreparedStatement statement =
dataSource.getConnection().prepareStatement(staticSql)) {
+ bindArgs(statement, args);
+ try (ResultSet resultSet = statement.executeQuery()) {
+ while (resultSet.next()) {
+ timestamps.add(resultSet.getString("time_bucket"));
+ counts.add(resultSet.getLong("data_count"));
+ }
}
}
return counts;
diff --git
a/ozhera-log/log-manager/src/test/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilderTest.java
b/ozhera-log/log-manager/src/test/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilderTest.java
new file mode 100644
index 00000000..15713b6c
--- /dev/null
+++
b/ozhera-log/log-manager/src/test/java/org/apache/ozhera/log/manager/common/utils/LogQuerySqlBuilderTest.java
@@ -0,0 +1,114 @@
+/*
+ * 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.ozhera.log.manager.common.utils;
+
+import
org.apache.ozhera.log.manager.common.utils.LogQuerySqlBuilder.SqlWithArgs;
+import org.junit.Test;
+
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
+public class LogQuerySqlBuilderTest {
+
+ @Test
+ public void blankExpressionYieldsNoFragment() {
+ assertNull(LogQuerySqlBuilder.buildFullTextSearch(null));
+ assertNull(LogQuerySqlBuilder.buildFullTextSearch(" "));
+ }
+
+ @Test
+ public void singleCondition() {
+ SqlWithArgs result =
LogQuerySqlBuilder.buildFullTextSearch("level=\"ERROR\"");
+ assertEquals("level = ?", result.getSql());
+ assertEquals(Arrays.asList("ERROR"), result.getArgs());
+ }
+
+ @Test
+ public void multipleConditionsAreParameterized() {
+ SqlWithArgs result =
LogQuerySqlBuilder.buildFullTextSearch("level=\"ERROR\" AND code=500");
+ assertEquals("level = ? AND code = ?", result.getSql());
+ assertEquals(Arrays.asList("ERROR", 500L), result.getArgs());
+ }
+
+ @Test
+ public void likeOperatorIsPreserved() {
+ SqlWithArgs result = LogQuerySqlBuilder.buildFullTextSearch("message
like \"%timeout%\"");
+ assertEquals("message LIKE ?", result.getSql());
+ assertEquals(Arrays.asList("%timeout%"), result.getArgs());
+ }
+
+ @Test
+ public void andInsideQuotedValueIsNotTreatedAsConnector() {
+ SqlWithArgs result =
LogQuerySqlBuilder.buildFullTextSearch("message=\"a AND b\"");
+ assertEquals("message = ?", result.getSql());
+ assertEquals(Arrays.asList("a AND b"), result.getArgs());
+ }
+
+ @Test
+ public void unionInjectionIsRejected() {
+ assertRejected("1=0 UNION SELECT pwd FROM secret_users");
+ }
+
+ @Test
+ public void statementTerminatorInjectionIsRejected() {
+ assertRejected("level=\"x\"; DROP TABLE hera_logs");
+ }
+
+ @Test
+ public void commentInjectionIsRejected() {
+ assertRejected("level=\"x\" OR 1=1 -- ");
+ }
+
+ @Test
+ public void bareUnquotedStringIsRejected() {
+ assertRejected("level=ERROR");
+ }
+
+ @Test
+ public void identifierAllowsPlainColumn() {
+ assertEquals("timestamp",
LogQuerySqlBuilder.safeIdentifier("timestamp", "sortKey"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void identifierRejectsInjection() {
+ LogQuerySqlBuilder.safeIdentifier("timestamp; DROP TABLE t",
"sortKey");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void indexNameRejectsWhitespace() {
+ LogQuerySqlBuilder.safeIndexName("hera_logs UNION SELECT");
+ }
+
+ @Test
+ public void indexNameAllowsDotsAndHyphens() {
+ assertEquals("hera-log.2026",
LogQuerySqlBuilder.safeIndexName("hera-log.2026"));
+ }
+
+ private static void assertRejected(String expr) {
+ try {
+ LogQuerySqlBuilder.buildFullTextSearch(expr);
+ fail("expected expression to be rejected: " + expr);
+ } catch (IllegalArgumentException expected) {
+ // ok
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]