diff --git a/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java b/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java index fb6f7596b5d..73d1324415e 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java +++ b/java-checks-test-sources/default/src/main/java/checks/SQLInjection.java @@ -7,15 +7,21 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; +import java.util.Collections; +import java.util.List; import java.util.Locale; +import java.util.function.Supplier; +import java.util.stream.Collectors; import org.hibernate.Session; import javax.persistence.EntityManager; import javax.jdo.PersistenceManager; +import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.PreparedStatementCreatorFactory; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; class SQLInjection { private static final String CONSTANT = "SELECT * FROM TABLE"; @@ -428,10 +434,9 @@ public void plusAssignment(String input) throws SQLException { } public void plusAssignmentConst() throws SQLException { - // FP, but probably rare and not worth complicating the code to fix it. String query = "SELECT"; query += String.format("WHERE col = \"%c\"", "value"); - this.stmt.execute(query); // Noncompliant + this.stmt.execute(query); // Compliant } public void plusAssignmentClassName(String input) throws SQLException { @@ -458,4 +463,256 @@ public void constantTernaryAndPrimitives(boolean asc, int offset, Integer limit, em.createNativeQuery("SELECT * FROM entity ORDER BY " + (asc ? input : "DESC")); // Noncompliant em.createNativeQuery("SELECT * FROM entity ORDER BY " + (asc ? (offset > 0 ? "A" : "B") : "C")); // Compliant } + + private static final String PRODUCT_OPERAND = "p.product_id"; + private static final String IN_TEMPLATE = "SELECT * FROM t WHERE id IN (%s)"; + private JdbcTemplate fixedJdbc; + private String fieldFragment; + @Value("${query.hint:/*+ x */}") + private String configuredHint; + + private String literalWhere(boolean a, boolean b) { + StringBuilder sb = new StringBuilder(); + if (a) { + sb.append(" AND account_id = :accountId"); + } + if (b) { + sb.append(" AND room_id = :roomId").append(" AND x = 1"); + } + return sb.toString(); + } + + private StringBuilder literalBuilder(boolean a) { + StringBuilder sb = new StringBuilder(""); + if (a) { + sb.append(" AND x = :x"); + } + return sb; + } + + private static String literalStatic() { + return " AND y = :y"; + } + + private String literalConcat(boolean a) { + if (a) { + return " AND a = :a" + " AND b = :b"; + } + return ""; + } + + private String dynamicWhere(String param) { + return " AND x = " + param; + } + + private String dynamicBuilderWhere(String param) { + StringBuilder sb = new StringBuilder(); + sb.append(" AND x = ").append(param); + return sb.toString(); + } + + private String dynamicBuilderAliasWhere(String param) { + StringBuilder sb = new StringBuilder(); + StringBuilder alias = sb; + alias.append(param); + return sb.toString(); + } + + private String escapedBuilderWhere(String param) { + StringBuilder sb = new StringBuilder(); + consume(sb); + return sb.toString(); + } + + private String builderFromParam(String param) { + StringBuilder sb = new StringBuilder(param); + return sb.toString(); + } + + private String mixedReturns(boolean a, String param) { + if (a) { + return " AND a = :a"; + } + return " AND b = " + param; + } + + private String fieldReturn() { + return fieldFragment; + } + + private String recursiveHelper(int n) { + return " AND r = :r" + recursiveHelper(n - 1); + } + + private String callingHelper() { + return " AND c = :c" + literalConcat(true); + } + + private String lambdaReturn() { + Supplier supplier = () -> { + return fieldFragment; + }; + return " AND l = :l"; + } + + private String anonymousClassReturn() { + Supplier supplier = new Supplier<>() { + @Override + public String get() { + return fieldFragment; + } + }; + return " AND a = :a"; + } + + String nonPrivateHelper() { + return " AND n = :n"; + } + + private void consume(StringBuilder sb) { + } + + void fixedFragmentHelpers(boolean a, boolean b, String param, MapSqlParameterSource params) { + fixedJdbc.query("SELECT count(*) FROM assignment" + literalWhere(a, b), (rs, i) -> 1); // Compliant + String sql = "SELECT count(*) FROM assignment" + literalWhere(a, b); + fixedJdbc.query(sql, (rs, i) -> 1); // Compliant + StringBuilder where = literalBuilder(a); + fixedJdbc.query("SELECT 1 FROM t" + where, (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t" + literalStatic(), (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t" + literalConcat(a), (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t WHERE x = %s".formatted(literalStatic()), (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t" + callingHelper(), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + lambdaReturn(), (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t" + anonymousClassReturn(), (rs, i) -> 1); // Compliant + + fixedJdbc.query("SELECT 1 FROM t" + dynamicWhere(param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + dynamicBuilderWhere(param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + dynamicBuilderAliasWhere(param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + escapedBuilderWhere(param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + builderFromParam(param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + mixedReturns(a, param), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + fieldReturn(), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + recursiveHelper(3), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + nonPrivateHelper(), (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + fieldFragment, (rs, i) -> 1); // Noncompliant + fixedJdbc.query("SELECT 1 FROM t" + param, (rs, i) -> 1); // Noncompliant + } + + void repeatedPlaceholders(List ids, String param) { + String placeholders = String.join(",", Collections.nCopies(ids.size(), "?")); + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + placeholders + ")", (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + String.join(", ", Collections.nCopies(ids.size(), "(?)")) + ")", (rs, i) -> 1); // Compliant + fixedJdbc.query(IN_TEMPLATE.formatted(placeholders), (rs, i) -> 1); // Compliant + fixedJdbc.query(String.format(IN_TEMPLATE, placeholders), (rs, i) -> 1); // Compliant + + String badElement = String.join(",", Collections.nCopies(ids.size(), param)); + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + badElement + ")", (rs, i) -> 1); // Noncompliant + String badDelimiter = String.join(param, Collections.nCopies(ids.size(), "?")); + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + badDelimiter + ")", (rs, i) -> 1); // Noncompliant + String plainJoin = String.join(",", ids); + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + plainJoin + ")", (rs, i) -> 1); // Noncompliant + String reassigned = String.join(",", Collections.nCopies(ids.size(), "?")); + reassigned = param; + fixedJdbc.query("SELECT 1 FROM t WHERE id IN (" + reassigned + ")", (rs, i) -> 1); // Noncompliant + } + + void mappedPlaceholders(List rows, String param) { + String values = rows.stream().map(r -> "(?, ?)").collect(Collectors.joining(", ")); + fixedJdbc.query("INSERT INTO t VALUES %s".formatted(values), (rs, i) -> 1); // Compliant + fixedJdbc.query("INSERT INTO t VALUES " + rows.stream().map(r -> "(?)").collect(Collectors.joining(",")), (rs, i) -> 1); // Compliant + + String fromElement = rows.stream().map(r -> "(" + r + ")").collect(Collectors.joining(", ")); + fixedJdbc.query("INSERT INTO t VALUES " + fromElement, (rs, i) -> 1); // Noncompliant + String badDelimiter = rows.stream().map(r -> "(?)").collect(Collectors.joining(param)); + fixedJdbc.query("INSERT INTO t VALUES " + badDelimiter, (rs, i) -> 1); // Noncompliant + String blockLambda = rows.stream().map(r -> { return "(?)"; }).collect(Collectors.joining(",")); + fixedJdbc.query("INSERT INTO t VALUES " + blockLambda, (rs, i) -> 1); // Noncompliant + } + + void loopsAndConstants(List ids, List columns) { + StringBuilder literalLoop = new StringBuilder("SELECT 1 FROM t WHERE 1 = 0"); + for (String id : ids) { + literalLoop.append(" OR code = ?"); + } + fixedJdbc.query(literalLoop.toString(), (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t WHERE 1 = 0" + literalLoop.toString(), (rs, i) -> 1); // Compliant + + String concatenatedLoop = "SELECT 1 FROM t WHERE 1 = 0"; + for (String id : ids) { + concatenatedLoop += " OR code = ?"; + } + fixedJdbc.query(concatenatedLoop, (rs, i) -> 1); // Compliant + + String elementLoop = "SELECT 1 FROM t WHERE 1 = 0"; + for (String column : columns) { + elementLoop += " OR " + column + " = ?"; + } + fixedJdbc.query(elementLoop, (rs, i) -> 1); // Noncompliant + + fixedJdbc.query("SELECT 1 FROM t WHERE %1$s = ?".formatted(PRODUCT_OPERAND), (rs, i) -> 1); // Compliant + String clause = "WHERE %1$s = ?".formatted(PRODUCT_OPERAND); + fixedJdbc.query("SELECT 1 FROM t " + clause, (rs, i) -> 1); // Compliant + } + + void dynamicBuilderInCaller(String param) { + StringBuilder sb = new StringBuilder("SELECT 1 FROM t WHERE x = "); + sb.append(param); + fixedJdbc.query("SELECT 1 FROM t" + sb.toString(), (rs, i) -> 1); // Noncompliant + StringBuilder passed = new StringBuilder("SELECT 1 FROM t"); + consume(passed); + fixedJdbc.query("SELECT 1 FROM t" + passed.toString(), (rs, i) -> 1); // Noncompliant + StringBuilder fixed = new StringBuilder("SELECT 1 FROM t"); + fixed.append(" WHERE x = 1"); + fixedJdbc.query("SELECT 1 FROM t" + fixed.toString(), (rs, i) -> 1); // Compliant + } + + void builderEdgeCases(boolean a, String param) { + StringBuilder self = new StringBuilder("SELECT 1"); + self.append(self.toString()); + fixedJdbc.query("x" + self.toString(), (rs, i) -> 1); // Noncompliant + + StringBuilder indirect = new StringBuilder("SELECT 1"); + String snapshot = indirect.toString(); + indirect.append(snapshot); + fixedJdbc.query("x" + indirect.toString(), (rs, i) -> 1); // Noncompliant + + StringBuilder extended = literalBuilder(a); + extended.append(param); + fixedJdbc.query("SELECT 1 FROM t" + extended, (rs, i) -> 1); // Noncompliant + + StringBuilder original = literalBuilder(a); + StringBuilder alias = original; + alias.append(param); + fixedJdbc.query("SELECT 1 FROM t" + original, (rs, i) -> 1); // Noncompliant + + StringBuilder escaping = literalBuilder(a); + Supplier blockLeak = () -> { + return escaping; + }; + blockLeak.get().append(param); + fixedJdbc.query("SELECT 1 FROM t" + escaping, (rs, i) -> 1); // Noncompliant + + StringBuilder escapingAnonymous = literalBuilder(a); + Supplier anonymousLeak = new Supplier<>() { + @Override + public StringBuilder get() { + return escapingAnonymous; + } + }; + anonymousLeak.get().append(param); + fixedJdbc.query("SELECT 1 FROM t" + escapingAnonymous, (rs, i) -> 1); // Noncompliant + + StringBuilder returned = literalBuilder(a); + fixedJdbc.query("SELECT 1 FROM t" + returned, (rs, i) -> 1); // Compliant + fixedJdbc.query("SELECT 1 FROM t %s".formatted(returned), (rs, i) -> 1); // Compliant + } + + void formatWithLocale(String param, Locale locale) { + fixedJdbc.query(String.format(locale, "SELECT %s", "1"), (rs, i) -> 1); // Compliant + fixedJdbc.query(String.format("SELECT '%s'", new Locale(param)), (rs, i) -> 1); // Noncompliant + } + + void configuredValue() { + fixedJdbc.query("SELECT " + configuredHint + " 1 FROM t", (rs, i) -> 1); // Noncompliant + } } diff --git a/java-checks-test-sources/default/src/main/java/checks/SQLInjectionWithoutSemantic.java b/java-checks-test-sources/default/src/main/java/checks/SQLInjectionWithoutSemantic.java index ab4e7496c96..2893dbff376 100644 --- a/java-checks-test-sources/default/src/main/java/checks/SQLInjectionWithoutSemantic.java +++ b/java-checks-test-sources/default/src/main/java/checks/SQLInjectionWithoutSemantic.java @@ -306,9 +306,8 @@ public void plusAssignment(String input) throws SQLException { } public void plusAssignmentConst() throws SQLException { - // FP, but probably rare and not worth complicating the code to fix it. String query = "SELECT"; query += String.format("WHERE col = \"%c\"", "value"); - this.stmt.execute(query); // Noncompliant + this.stmt.execute(query); // Compliant } } diff --git a/java-checks/src/main/java/org/sonar/java/checks/SQLInjectionCheck.java b/java-checks/src/main/java/org/sonar/java/checks/SQLInjectionCheck.java index f66ceb9e8a0..c8fdbbdc259 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/SQLInjectionCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/SQLInjectionCheck.java @@ -37,10 +37,19 @@ import org.sonar.plugins.java.api.tree.BinaryExpressionTree; import org.sonar.plugins.java.api.tree.ConditionalExpressionTree; import org.sonar.plugins.java.api.tree.ExpressionTree; +import org.sonar.plugins.java.api.tree.Arguments; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.ExpressionStatementTree; import org.sonar.plugins.java.api.tree.IdentifierTree; +import org.sonar.plugins.java.api.tree.LambdaExpressionTree; +import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; import org.sonar.plugins.java.api.tree.MethodInvocationTree; +import org.sonar.plugins.java.api.tree.MethodTree; import org.sonar.plugins.java.api.tree.NewClassTree; +import org.sonar.plugins.java.api.tree.ReturnStatementTree; import org.sonar.plugins.java.api.tree.Tree; +import org.sonar.plugins.java.api.tree.VariableTree; import static org.sonar.java.checks.helpers.ReassignmentFinder.getInitializerOrExpression; import static org.sonar.java.checks.helpers.ReassignmentFinder.getReassignments; @@ -127,6 +136,52 @@ public class SQLInjectionCheck extends IssuableSubscriptionVisitor { .withAnyParameters() .build(); + private static final String JAVA_UTIL_STREAM = "java.util.stream.Stream"; + private static final String STRING_BUILDER = "java.lang.StringBuilder"; + private static final String STRING_BUFFER = "java.lang.StringBuffer"; + + private static final MethodMatchers STRING_JOIN = MethodMatchers.create() + .ofTypes(JAVA_LANG_STRING) + .names("join") + .withAnyParameters() + .build(); + + private static final MethodMatchers N_COPIES = MethodMatchers.create() + .ofTypes("java.util.Collections") + .names("nCopies") + .withAnyParameters() + .build(); + + private static final MethodMatchers STREAM_MAP = MethodMatchers.create() + .ofSubTypes(JAVA_UTIL_STREAM) + .names("map") + .withAnyParameters() + .build(); + + private static final MethodMatchers STREAM_COLLECT = MethodMatchers.create() + .ofSubTypes(JAVA_UTIL_STREAM) + .names("collect") + .withAnyParameters() + .build(); + + private static final MethodMatchers COLLECTORS_JOINING = MethodMatchers.create() + .ofTypes("java.util.stream.Collectors") + .names("joining") + .withAnyParameters() + .build(); + + private static final MethodMatchers BUILDER_APPEND = MethodMatchers.create() + .ofTypes(STRING_BUILDER, STRING_BUFFER) + .names("append") + .withAnyParameters() + .build(); + + private static final MethodMatchers BUILDER_TO_STRING = MethodMatchers.create() + .ofTypes(STRING_BUILDER, STRING_BUFFER) + .names("toString") + .addWithoutParametersMatcher() + .build(); + private static final MethodMatchers CLASS_NAME_METHODS = MethodMatchers.create() .ofTypes("java.lang.Class") .names("getName", "getSimpleName", "getCanonicalName", "getTypeName") @@ -141,6 +196,24 @@ public class SQLInjectionCheck extends IssuableSubscriptionVisitor { .addParametersMatcher(JAVA_LANG_STRING, "boolean") .build()); + /** + * Bounds the recursive analysis of helper methods and StringBuilder usages: inside a helper body other helpers are not + * followed, and inside the arguments appended to a builder neither helpers nor other builders are followed. + */ + private enum Scope { + FULL(true, true), + IN_HELPER(false, true), + IN_BUILDER(false, false); + + private final boolean followsHelpers; + private final boolean followsBuilders; + + Scope(boolean followsHelpers, boolean followsBuilders) { + this.followsHelpers = followsHelpers; + this.followsBuilders = followsBuilders; + } + } + private static final String MAIN_MESSAGE = "Make sure using a dynamically formatted SQL query is safe here."; @Override @@ -234,16 +307,22 @@ private static boolean isDynamicConcatenation(ExpressionTree arg) { } private static boolean hasDynamicConcatenationOperand(ExpressionTree arg) { + return hasDynamicConcatenationOperand(arg, Scope.FULL); + } + + private static boolean hasDynamicConcatenationOperand(ExpressionTree arg, Scope scope) { ExpressionTree expression = ExpressionUtils.skipParentheses(arg); if (expression.asConstant().isPresent() || isPrimitiveOrWrapper(expression.symbolType()) - || isSafeExpression(expression, SAFE_CONCATENATION_METHODS, new HashSet<>())) { + || isSafeExpression(expression, SAFE_CONCATENATION_METHODS, new HashSet<>(), scope)) { return false; } if (expression instanceof ConditionalExpressionTree conditional) { - return hasDynamicConcatenationOperand(conditional.trueExpression()) || hasDynamicConcatenationOperand(conditional.falseExpression()); + return hasDynamicConcatenationOperand(conditional.trueExpression(), scope) + || hasDynamicConcatenationOperand(conditional.falseExpression(), scope); } if (expression instanceof BinaryExpressionTree binaryExpression && expression.is(Tree.Kind.PLUS)) { - return hasDynamicConcatenationOperand(binaryExpression.leftOperand()) || hasDynamicConcatenationOperand(binaryExpression.rightOperand()); + return hasDynamicConcatenationOperand(binaryExpression.leftOperand(), scope) + || hasDynamicConcatenationOperand(binaryExpression.rightOperand(), scope); } return true; } @@ -252,21 +331,182 @@ private static boolean isPrimitiveOrWrapper(Type type) { return type.isPrimitive() || type.isPrimitiveWrapper(); } - private static boolean isSafeExpression(ExpressionTree arg, MethodMatchers safeMethods, Set visitedSymbols) { + private static boolean isSafeExpression(ExpressionTree arg, MethodMatchers safeMethods, Set visitedSymbols, Scope scope) { ExpressionTree expression = ExpressionUtils.skipParentheses(arg); if (expression instanceof MethodInvocationTree methodInvocation) { - return safeMethods.matches(methodInvocation); + return safeMethods.matches(methodInvocation) || hasFixedContent(methodInvocation, scope); } if (expression instanceof IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (symbol.isLocalVariable() && !symbol.isParameter() && visitedSymbols.add(symbol)) { + if (isBuilder(symbol.type())) { + return scope.followsBuilders && isFixedContentBuilder(symbol, scope); + } ExpressionTree singleWrite = ExpressionsHelper.getSingleWriteUsage(symbol); - return singleWrite != null && isSafeExpression(singleWrite, safeMethods, visitedSymbols); + return singleWrite != null && isSafeExpression(singleWrite, safeMethods, visitedSymbols, scope); } } return false; } + private static boolean hasFixedContent(MethodInvocationTree mit, Scope scope) { + return isJoinOfRepeatedFixedElement(mit, scope) + || isJoinOfMappedFixedElement(mit, scope) + || isFormatOfFixedContent(mit, scope) + || (scope.followsBuilders && isFixedContentBuilderToString(mit, scope)) + || (scope.followsHelpers && isFixedContentHelperCall(mit)); + } + + private static boolean isFixed(ExpressionTree expression, Scope scope) { + return !hasDynamicConcatenationOperand(expression, scope); + } + + private static boolean isJoinOfRepeatedFixedElement(MethodInvocationTree mit, Scope scope) { + if (!STRING_JOIN.matches(mit) || mit.arguments().size() != 2) { + return false; + } + ExpressionTree delimiter = mit.arguments().get(0); + return ExpressionUtils.skipParentheses(mit.arguments().get(1)) instanceof MethodInvocationTree copies + && N_COPIES.matches(copies) + && copies.arguments().size() == 2 + && isFixed(delimiter, scope) + && isFixed(copies.arguments().get(1), scope); + } + + private static boolean isJoinOfMappedFixedElement(MethodInvocationTree collect, Scope scope) { + if (!STREAM_COLLECT.matches(collect) || collect.arguments().size() != 1 + || !(ExpressionUtils.skipParentheses(collect.arguments().get(0)) instanceof MethodInvocationTree joining) + || !COLLECTORS_JOINING.matches(joining) + || !joining.arguments().stream().allMatch(argument -> isFixed(argument, scope))) { + return false; + } + return collect.methodSelect() instanceof MemberSelectExpressionTree select + && ExpressionUtils.skipParentheses(select.expression()) instanceof MethodInvocationTree map + && STREAM_MAP.matches(map) + && map.arguments().size() == 1 + && map.arguments().get(0) instanceof LambdaExpressionTree lambda + && lambda.body() instanceof ExpressionTree body + && isFixed(body, scope); + } + + private static boolean isFormatOfFixedContent(MethodInvocationTree mit, Scope scope) { + if (!FORMAT_METHODS.matches(mit)) { + return false; + } + boolean isStatic = mit.methodSymbol().isStatic(); + boolean fixedReceiver = isStatic || (mit.methodSelect() instanceof MemberSelectExpressionTree select && isFixed(select.expression(), scope)); + List arguments = mit.arguments(); + for (int i = 0; i < arguments.size(); i++) { + boolean isLeadingLocale = isStatic && i == 0 && arguments.get(i).symbolType().is("java.util.Locale"); + if (!isLeadingLocale && !isFixed(arguments.get(i), scope)) { + return false; + } + } + return fixedReceiver; + } + + private static boolean isFixedContentBuilderToString(MethodInvocationTree mit, Scope scope) { + if (!BUILDER_TO_STRING.matches(mit) || !(mit.methodSelect() instanceof MemberSelectExpressionTree select)) { + return false; + } + ExpressionTree root = ExpressionUtils.skipParentheses(select.expression()); + while (root instanceof MethodInvocationTree call && call.methodSelect() instanceof MemberSelectExpressionTree callSelect && BUILDER_APPEND.matches(call)) { + root = ExpressionUtils.skipParentheses(callSelect.expression()); + } + return root instanceof IdentifierTree identifier && isBuilder(identifier.symbol().type()) && isFixedContentBuilder(identifier.symbol(), scope); + } + + private static boolean isBuilder(Type type) { + return type.is(STRING_BUILDER) || type.is(STRING_BUFFER); + } + + /** + * A local StringBuilder/StringBuffer is fixed-content when it is created with fixed arguments (or returned by a fixed + * helper) and every usage is either an append of fixed content (possibly chained), a toString call, or a read-only + * use (return, expression statement, operand of a concatenation, argument of format). Any other usage (passed as + * argument, aliased, reassigned) makes its content unknown. + */ + private static boolean isFixedContentBuilder(Symbol symbol, Scope scope) { + return symbol.isLocalVariable() && !symbol.isParameter() + && symbol.declaration() instanceof VariableTree variable + && isFixedBuilderInitializer(variable.initializer(), scope) + && symbol.usages().stream().allMatch(usage -> isFixedContentBuilderUsage(usage, variable)); + } + + private static boolean isFixedBuilderInitializer(@Nullable ExpressionTree initializer, Scope scope) { + if (initializer instanceof NewClassTree creation) { + return creation.arguments().stream().allMatch(argument -> isFixed(argument, Scope.IN_BUILDER)); + } + return scope.followsHelpers && initializer instanceof MethodInvocationTree call && isFixedContentHelperCall(call); + } + + private static boolean isFixedContentBuilderUsage(IdentifierTree usage, VariableTree declaration) { + Tree current = usage; + while (current.parent() instanceof MemberSelectExpressionTree select && select.expression() == current + && select.parent() instanceof MethodInvocationTree call && call.methodSelect() == select) { + if (BUILDER_TO_STRING.matches(call)) { + return true; + } + if (!BUILDER_APPEND.matches(call) || !call.arguments().stream().allMatch(argument -> isFixed(argument, Scope.IN_BUILDER))) { + return false; + } + current = call; + } + Tree parent = current.parent(); + return (parent instanceof ReturnStatementTree && enclosingScope(parent) == enclosingScope(declaration)) + || parent instanceof ExpressionStatementTree + || parent.is(Tree.Kind.PLUS) + || (parent instanceof Arguments arguments && arguments.parent() instanceof MethodInvocationTree call && FORMAT_METHODS.matches(call)); + } + + @Nullable + private static Tree enclosingScope(Tree tree) { + Tree current = tree.parent(); + while (current != null && !(current instanceof MethodTree || current instanceof LambdaExpressionTree || current instanceof ClassTree)) { + current = current.parent(); + } + return current; + } + + /** + * A call to a non-overridable method declared in the same file is fixed-content when it has at least one return + * statement and all of them return fixed content. Other helpers called from inside the helper are not followed. + */ + private static boolean isFixedContentHelperCall(MethodInvocationTree mit) { + Symbol.MethodSymbol method = mit.methodSymbol(); + MethodTree declaration = method.declaration(); + if (declaration == null || declaration.block() == null || !(method.isPrivate() || method.isStatic() || method.isFinal())) { + return false; + } + Type returnType = method.returnType().type(); + if (!(returnType.is(JAVA_LANG_STRING) || returnType.is(STRING_BUILDER) || returnType.is(STRING_BUFFER))) { + return false; + } + ReturnCollector collector = new ReturnCollector(); + declaration.block().accept(collector); + return !collector.returns.isEmpty() + && collector.returns.stream().allMatch(returnTree -> returnTree.expression() != null && isFixed(returnTree.expression(), Scope.IN_HELPER)); + } + + private static class ReturnCollector extends BaseTreeVisitor { + private final List returns = new ArrayList<>(); + + @Override + public void visitReturnStatement(ReturnStatementTree tree) { + returns.add(tree); + } + + @Override + public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) { + // do not descend into nested lambdas: their return statements belong to a different method + } + + @Override + public void visitClass(ClassTree tree) { + // do not descend into nested/anonymous classes: their return statements belong to a different method + } + } + private static boolean isDynamicFormat(Tree tree) { return tree instanceof MethodInvocationTree mit && FORMAT_METHODS.matches(mit) @@ -284,7 +524,7 @@ private static boolean hasDynamicStringParameters(MethodInvocationTree mit) { boolean isFirstLocaleArgument = firstArg && type.is("java.util.Locale"); // Primitives will not lead to SQL injection, so the code is compliant. if (!isFirstLocaleArgument && !type.isUnknown() && !isPrimitiveOrWrapper(type) - && arg.asConstant().isEmpty() && !isSafeExpression(arg, CLASS_NAME_METHODS, new HashSet<>())) { + && arg.asConstant().isEmpty() && !isSafeExpression(arg, CLASS_NAME_METHODS, new HashSet<>(), Scope.FULL)) { return true; } firstArg = false;