-
Notifications
You must be signed in to change notification settings - Fork 724
SONARJAVA-6789: Implement S9353: disallow unescaped '.' as a regex literal #5955
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3b48418
Implement S9353
nathsou cc10792
fix-ci: add S9353 ruling expected issues
nathsou 755681e
Document explicit alternatives for intentional "." regexes
nathsou 9ebd36b
Fix duplicate compile literal in S9353 check
nathsou c46968a
Drop inexact any-character alternatives from S9353 docs
nathsou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "org.regex-examples:regex-examples:src/main/java/org/regex/examples/RegexDatabase2.java": [ | ||
| 457 | ||
| ], | ||
| "org.regex-examples:regex-examples:src/main/java/org/regex/examples/RegexDatabase8.java": [ | ||
| 1129 | ||
| ] | ||
| } |
43 changes: 43 additions & 0 deletions
43
java-checks-test-sources/default/src/main/java/checks/BareDotRegexpCheckSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| package checks; | ||
|
|
||
| import java.util.regex.Pattern; | ||
|
|
||
| class BareDotRegexpCheckSample { | ||
|
|
||
| private static final String DOT = "."; | ||
| private static final String ESCAPED_DOT = "\\."; | ||
|
|
||
| void noncompliant(String filename) { | ||
| filename.split("."); // Noncompliant {{This regex "." matches any character, not a literal dot; escape it as "\\." if a period was intended.}} | ||
| // ^^^ | ||
| filename.split(".", 2); // Noncompliant | ||
| filename.split(DOT); // Noncompliant | ||
| filename.replaceAll(".", "_"); // Noncompliant | ||
| filename.replaceFirst(".", "_"); // Noncompliant | ||
| filename.matches("."); // Noncompliant | ||
| Pattern.compile("."); // Noncompliant | ||
| Pattern.compile(DOT); // Noncompliant | ||
| Pattern.compile(".", Pattern.DOTALL); // Noncompliant | ||
| Pattern.matches(".", filename); // Noncompliant | ||
| } | ||
|
|
||
| void compliant(String filename, String regex, int flags) { | ||
| filename.split("\\."); | ||
| filename.split(ESCAPED_DOT); | ||
| filename.split(Pattern.quote(".")); | ||
| filename.split("[.]"); | ||
| filename.split(".*"); | ||
| filename.split(regex); | ||
| filename.replace(".", "_"); | ||
| filename.replaceAll("\\.", "_"); | ||
| filename.replaceFirst("\\.", "_"); | ||
| filename.matches("\\."); | ||
| Pattern.compile("\\."); | ||
| Pattern.compile(".", Pattern.LITERAL); | ||
| Pattern.compile(".", Pattern.LITERAL | Pattern.CASE_INSENSITIVE); | ||
| Pattern.compile(regex); | ||
| Pattern.compile(".", flags); | ||
| Pattern.matches("\\.", filename); | ||
| } | ||
|
|
||
| } |
92 changes: 92 additions & 0 deletions
92
java-checks/src/main/java/org/sonar/java/checks/BareDotRegexpCheck.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.regex.Pattern; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.java.checks.methods.AbstractMethodDetection; | ||
| import org.sonar.plugins.java.api.semantic.MethodMatchers; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MethodInvocationTree; | ||
|
|
||
| @Rule(key = "S9353") | ||
| public class BareDotRegexpCheck extends AbstractMethodDetection { | ||
|
|
||
| private static final String MESSAGE = "This regex \".\" matches any character, not a literal dot; escape it as \"\\\\.\" if a period was intended."; | ||
| private static final String JAVA_LANG_STRING = "java.lang.String"; | ||
| private static final String JAVA_UTIL_REGEX_PATTERN = "java.util.regex.Pattern"; | ||
| private static final String COMPILE_METHOD_NAME = "compile"; | ||
|
|
||
| private static final MethodMatchers REGEX_METHODS = MethodMatchers.or( | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_LANG_STRING) | ||
| .names("split", "matches") | ||
| .addParametersMatcher(JAVA_LANG_STRING) | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_LANG_STRING) | ||
| .names("split") | ||
| .addParametersMatcher(JAVA_LANG_STRING, "int") | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_LANG_STRING) | ||
| .names("replaceAll", "replaceFirst") | ||
| .addParametersMatcher(JAVA_LANG_STRING, JAVA_LANG_STRING) | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_UTIL_REGEX_PATTERN) | ||
| .names("matches") | ||
| .addParametersMatcher(JAVA_LANG_STRING, "java.lang.CharSequence") | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_UTIL_REGEX_PATTERN) | ||
| .names(COMPILE_METHOD_NAME) | ||
| .addParametersMatcher(JAVA_LANG_STRING) | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes(JAVA_UTIL_REGEX_PATTERN) | ||
| .names(COMPILE_METHOD_NAME) | ||
| .addParametersMatcher(JAVA_LANG_STRING, "int") | ||
| .build()); | ||
|
|
||
| @Override | ||
| protected MethodMatchers getMethodInvocationMatchers() { | ||
| return REGEX_METHODS; | ||
| } | ||
|
|
||
| @Override | ||
| protected void onMethodInvocationFound(MethodInvocationTree mit) { | ||
| ExpressionTree regexArgument = mit.arguments().get(0); | ||
| if (isBareDot(regexArgument) && !isLiteralPattern(mit)) { | ||
| reportIssue(regexArgument, MESSAGE); | ||
| } | ||
| } | ||
|
|
||
| private static boolean isBareDot(ExpressionTree regexArgument) { | ||
| return regexArgument.asConstant(String.class).filter("."::equals).isPresent(); | ||
| } | ||
|
|
||
| private static boolean isLiteralPattern(MethodInvocationTree mit) { | ||
| if (mit.arguments().size() < 2 || !COMPILE_METHOD_NAME.equals(mit.methodSymbol().name())) { | ||
| return false; | ||
| } | ||
| return mit.arguments().get(1).asConstant(Integer.class) | ||
| .map(flags -> (flags & Pattern.LITERAL) != 0) | ||
| .orElse(true); | ||
| } | ||
|
|
||
| } |
43 changes: 43 additions & 0 deletions
43
java-checks/src/test/java/org/sonar/java/checks/BareDotRegexpCheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class BareDotRegexpCheckTest { | ||
|
|
||
| @Test | ||
| void test() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/BareDotRegexpCheckSample.java")) | ||
| .withCheck(new BareDotRegexpCheck()) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void test_without_semantic() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/BareDotRegexpCheckSample.java")) | ||
| .withCheck(new BareDotRegexpCheck()) | ||
| .withoutSemantic() | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| } | ||
79 changes: 79 additions & 0 deletions
79
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9353.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| <p>In Java regular expressions, <code>.</code> is a metacharacter that matches any single character, not a literal period.</p> | ||
| <p>Passing <code>"."</code> to regex APIs such as <code>String.split</code>, <code>String.replaceAll</code>, <code>String.replaceFirst</code>, | ||
| <code>String.matches</code>, <code>Pattern.compile</code>, or <code>Pattern.matches</code> therefore does not treat the argument as a dot separator. | ||
| Developers almost always intended a literal <code>'.'</code>.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p><code>String.split</code> and <code>Pattern.compile</code> interpret their pattern argument as a regular expression. A pattern that is exactly | ||
| <code>"."</code> matches every character.</p> | ||
| <p>This is especially surprising with <code>String.split</code>: <code>"archive.tar.gz".split(".")</code> matches each character as a delimiter. | ||
| Trailing empty strings are discarded, so the result is an empty array rather than <code>["archive", "tar", "gz"]</code>.</p> | ||
| <p>The same pattern is just as wrong with replacement APIs. <code>"report.2026.pdf".replaceAll(".", "x")</code> replaces every character with | ||
| <code>x</code>, instead of replacing only the dots.</p> | ||
| <p>To match a literal period, escape the metacharacter (<code>"\\."</code>), quote it (<code>Pattern.quote(".")</code>), or use a non-regex API such | ||
| as <code>String.replace</code>.</p> | ||
| <h3>Exceptions</h3> | ||
| <p>This rule does not raise an issue when <code>Pattern.compile</code> is called with the <code>Pattern.LITERAL</code> flag, because that flag treats | ||
| the pattern as a literal string.</p> | ||
| <p>If matching any character is intentional, add an inline <code>// NOSONAR: "." intentionally matches any character</code> comment so the intent is | ||
| explicit.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| String filename = "archive.tar.gz"; | ||
| String[] parts = filename.split("."); // Noncompliant: matches every character instead of a literal '.' | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| String filename = "archive.tar.gz"; | ||
| String[] parts = filename.split("\\."); | ||
| </pre> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="2" data-diff-type="noncompliant"> | ||
| String filename = "report.2026.pdf"; | ||
| String sanitized = filename.replaceAll(".", "_"); // Noncompliant: replaces every character | ||
| String first = filename.replaceFirst(".", "_"); // Noncompliant | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="2" data-diff-type="compliant"> | ||
| String filename = "report.2026.pdf"; | ||
| String sanitized = filename.replace(".", "_"); | ||
| String first = filename.replaceFirst("\\.", "_"); | ||
| </pre> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="3" data-diff-type="noncompliant"> | ||
| Pattern dots = Pattern.compile("."); // Noncompliant: compiles a match-any-character pattern | ||
| boolean dotted = Pattern.matches(".", "a"); // Noncompliant | ||
| boolean oneChar = "a".matches("."); // Noncompliant | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="3" data-diff-type="compliant"> | ||
| Pattern dots = Pattern.compile("\\."); | ||
| boolean dotted = Pattern.matches("\\.", "a"); | ||
| boolean oneChar = "a".matches("\\."); | ||
| </pre> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="4" data-diff-type="noncompliant"> | ||
| Pattern anyChar = Pattern.compile("."); // Noncompliant | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="4" data-diff-type="compliant"> | ||
| Pattern anyChar = Pattern.compile("."); // NOSONAR: "." intentionally matches any character | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li>Java Documentation - <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#sum">Summary of | ||
| regular-expression constructs</a></li> | ||
| <li>Java Documentation - <a | ||
| href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html#split(java.lang.String)"><code>String.split</code> | ||
| method</a></li> | ||
| <li>Java Documentation - <a | ||
| href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)"><code>Pattern.quote</code> | ||
| method</a></li> | ||
| </ul> | ||
| <h3>Related rules</h3> | ||
| <ul> | ||
| <li>{rule:java:S2639} - Inappropriate regular expressions should not be used</li> | ||
| <li>{rule:java:S5361} - "String#replace" should be preferred to "String#replaceAll"</li> | ||
| </ul> | ||
|
|
23 changes: 23 additions & 0 deletions
23
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9353.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| { | ||
| "title": "A bare \".\" should not be used as a regular expression", | ||
| "type": "BUG", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "5min" | ||
| }, | ||
| "tags": [ | ||
| "regex" | ||
| ], | ||
| "defaultSeverity": "Major", | ||
| "ruleSpecification": "RSPEC-9353", | ||
| "sqKey": "S9353", | ||
| "scope": "All", | ||
| "quickfix": "targeted", | ||
|
gitar-bot[bot] marked this conversation as resolved.
|
||
| "code": { | ||
| "impacts": { | ||
| "RELIABILITY": "MEDIUM" | ||
| }, | ||
| "attribute": "LOGICAL" | ||
| } | ||
| } | ||
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.