-
Notifications
You must be signed in to change notification settings - Fork 724
SONARJAVA-6613 Implement new rule S9021 #5784
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
Open
romainbrenguier
wants to merge
5
commits into
master
Choose a base branch
from
new-rule/SONARJAVA-6613-S9021
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
26003e4
Implement new rule S9021
romainbrenguier 1addd80
Fix CI: Fixed compilation error in ConfigurationClassShouldNotBeFinal…
romainbrenguier c0a0f2e
Fix CI failures
romainbrenguier 0e784c5
Fix CI: Removed incorrect column marker '// ^^^^^' from Configura…
romainbrenguier 36ee107
Document intentional limitation to direct @Configuration annotations
romainbrenguier 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
130 changes: 130 additions & 0 deletions
130
...es/default/src/main/java/checks/spring/ConfigurationClassShouldNotBeFinalCheckSample.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,130 @@ | ||
| package checks.spring; | ||
|
|
||
| import org.springframework.boot.autoconfigure.SpringBootApplication; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.scheduling.annotation.EnableScheduling; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Configuration | ||
| final class BasicFinalConfig { // Noncompliant {{Remove the "final" modifier from this "@Configuration" class.}} | ||
|
|
||
| @Bean | ||
| public String dataSource() { | ||
| return "dataSource"; | ||
| } | ||
| } | ||
|
|
||
| @Configuration | ||
| final class FinalConfigMultipleBeans { // Noncompliant | ||
|
|
||
| @Bean | ||
| public String foo() { | ||
| return "foo"; | ||
| } | ||
|
|
||
| @Bean | ||
| public String bar() { | ||
| return foo(); | ||
| } | ||
| } | ||
|
|
||
| @Configuration | ||
| @EnableScheduling | ||
| final class FinalConfigOtherAnnotations { // Noncompliant | ||
|
|
||
| @Bean | ||
| public String scheduler() { | ||
| return "scheduler"; | ||
| } | ||
| } | ||
|
|
||
| class OuterClass { | ||
| @Configuration | ||
| public static final class NestedFinalConfig { // Noncompliant | ||
|
|
||
| @Bean | ||
| public String taskScheduler() { | ||
| return "taskScheduler"; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Configuration(proxyBeanMethods = true) | ||
| final class FinalConfigProxyEnabled { // Noncompliant | ||
|
|
||
| @Bean | ||
| public String dataSource() { | ||
| return "dataSource"; | ||
| } | ||
| } | ||
|
|
||
| @Configuration | ||
| class NonFinalConfig { | ||
|
|
||
| @Bean | ||
| public String dataSource() { | ||
| return "dataSource"; | ||
| } | ||
|
|
||
| @Bean | ||
| public String jdbcTemplate() { | ||
| return dataSource(); | ||
| } | ||
| } | ||
|
|
||
| @Configuration(proxyBeanMethods = false) | ||
| final class FinalConfigProxyDisabled { | ||
|
|
||
| @Bean | ||
| public String dataSource() { | ||
| return "dataSource"; | ||
| } | ||
| } | ||
|
|
||
| @Component | ||
| final class FinalComponentNotConfiguration { | ||
|
|
||
| public String createDataSource() { | ||
| return "dataSource"; | ||
| } | ||
| } | ||
|
|
||
| @Configuration | ||
| abstract class AbstractConfig { | ||
|
|
||
| @Bean | ||
| public String dataSource() { | ||
| return "dataSource"; | ||
| } | ||
| } | ||
|
|
||
| class NoAnnotation { | ||
| public final class NotAConfigurationClass { | ||
| public String method() { | ||
| return "value"; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| class OuterClassCompliant { | ||
| @Configuration | ||
| public static class NestedNonFinalConfig { | ||
|
|
||
| @Bean | ||
| public String taskScheduler() { | ||
| return "taskScheduler"; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Meta-annotations like @SpringBootApplication are intentionally not detected by this rule | ||
| // to avoid complexity with determining proxyBeanMethods for composed annotations | ||
| @SpringBootApplication | ||
| final class FinalSpringBootApplication { // Compliant - meta-annotations not detected | ||
|
|
||
| @Bean | ||
| public String appBean() { | ||
| return "appBean"; | ||
| } | ||
| } |
87 changes: 87 additions & 0 deletions
87
...s/src/main/java/org/sonar/java/checks/spring/ConfigurationClassShouldNotBeFinalCheck.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,87 @@ | ||
| /* | ||
| * 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.spring; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Optional; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.java.checks.helpers.ExpressionsHelper; | ||
| import org.sonar.java.checks.helpers.SpringUtils; | ||
| import org.sonar.java.model.ModifiersUtils; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.tree.AnnotationTree; | ||
| import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.ClassTree; | ||
| import org.sonar.plugins.java.api.tree.IdentifierTree; | ||
| import org.sonar.plugins.java.api.tree.Modifier; | ||
| import org.sonar.plugins.java.api.tree.ModifierKeywordTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
|
|
||
| @Rule(key = "S9021") | ||
| public class ConfigurationClassShouldNotBeFinalCheck extends IssuableSubscriptionVisitor { | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return List.of(Tree.Kind.CLASS); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| ClassTree classTree = (ClassTree) tree; | ||
|
|
||
| // Note: This check only detects direct @Configuration annotations, not meta-annotations | ||
| // like @SpringBootApplication. This is intentional to avoid complexity with proxyBeanMethods. | ||
| Optional<AnnotationTree> configurationAnnotation = getConfigurationAnnotation(classTree); | ||
| if (configurationAnnotation.isEmpty()) { | ||
| return; | ||
| } | ||
|
|
||
| Optional<ModifierKeywordTree> finalModifier = getFinalModifier(classTree); | ||
| if (finalModifier.isEmpty()) { | ||
| return; | ||
| } | ||
|
|
||
| if (hasProxyBeanMethodsDisabled(configurationAnnotation.get())) { | ||
| return; | ||
| } | ||
|
|
||
| reportIssue(finalModifier.get(), "Remove the \"final\" modifier from this \"@Configuration\" class."); | ||
| } | ||
|
|
||
| private static Optional<AnnotationTree> getConfigurationAnnotation(ClassTree tree) { | ||
| return tree.modifiers().annotations().stream() | ||
| .filter(annotation -> annotation.symbolType().is(SpringUtils.CONFIGURATION_ANNOTATION)) | ||
| .findFirst(); | ||
| } | ||
|
|
||
| private static Optional<ModifierKeywordTree> getFinalModifier(ClassTree tree) { | ||
| return ModifiersUtils.findModifier(tree.modifiers(), Modifier.FINAL); | ||
| } | ||
|
|
||
| private static boolean hasProxyBeanMethodsDisabled(AnnotationTree annotation) { | ||
| return annotation.arguments().stream() | ||
| .filter(argument -> argument.is(Tree.Kind.ASSIGNMENT)) | ||
| .map(AssignmentExpressionTree.class::cast) | ||
| .anyMatch(ConfigurationClassShouldNotBeFinalCheck::setsProxyBeanMethodsToFalse); | ||
| } | ||
|
|
||
| private static boolean setsProxyBeanMethodsToFalse(AssignmentExpressionTree assignment) { | ||
| return "proxyBeanMethods".equals(((IdentifierTree) assignment.variable()).name()) && | ||
| Boolean.FALSE.equals(ExpressionsHelper.getConstantValueAsBoolean(assignment.expression()).value()); | ||
| } | ||
|
|
||
| } | ||
34 changes: 34 additions & 0 deletions
34
...c/test/java/org/sonar/java/checks/spring/ConfigurationClassShouldNotBeFinalCheckTest.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,34 @@ | ||
| /* | ||
| * 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.spring; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class ConfigurationClassShouldNotBeFinalCheckTest { | ||
|
|
||
| @Test | ||
| void test() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/spring/ConfigurationClassShouldNotBeFinalCheckSample.java")) | ||
| .withCheck(new ConfigurationClassShouldNotBeFinalCheck()) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| } |
97 changes: 97 additions & 0 deletions
97
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9021.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,97 @@ | ||
| <h2>Why is this an issue?</h2> | ||
| <p>Spring Framework uses CGLIB proxies to enforce singleton semantics for beans defined in <code>@Configuration</code> classes. When you call a | ||
| <code>@Bean</code> method from within another <code>@Bean</code> method, Spring intercepts the call through a proxy to return the singleton instance | ||
| rather than creating a new object.</p> | ||
| <p>The Java <code>final</code> keyword prevents class inheritance, which blocks CGLIB from creating the necessary subclass proxy. Without this proxy, | ||
| inter-bean method calls create new instances instead of retrieving the singleton, breaking Spring's container management.</p> | ||
| <p>This typically manifests as a <code>ConfigurationClassPostProcessor</code> exception during application startup, preventing the Spring context from | ||
| initializing.</p> | ||
| <h2>What is the potential impact?</h2> | ||
| <p>When Spring <code>@Configuration</code> classes are marked <code>final</code>, the application fails to start. The | ||
| <code>ConfigurationClassPostProcessor</code> throws an exception because CGLIB cannot create the required proxy subclass.</p> | ||
| <p>If this check were bypassed, the impact would be more subtle: inter-bean method calls would create duplicate instances instead of using singletons, | ||
| leading to:</p> | ||
| <ul> | ||
| <li><strong>Resource leaks</strong>: Multiple database connection pools or file handles</li> | ||
| <li><strong>Inconsistent state</strong>: Different parts of the application working with different object instances</li> | ||
| <li><strong>Configuration drift</strong>: Bean initialization logic executing multiple times with potentially different results</li> | ||
| </ul> | ||
| <h2>How to fix it</h2> | ||
| <p>Remove the <code>final</code> modifier from the <code>@Configuration</code> class. This allows Spring to create the CGLIB proxy needed to enforce | ||
| singleton semantics for inter-bean method calls.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| @Configuration | ||
| public final class DatabaseConfig { // Noncompliant | ||
|
|
||
| @Bean | ||
| public DataSource dataSource() { | ||
| return new HikariDataSource(); | ||
| } | ||
|
|
||
| @Bean | ||
| public JdbcTemplate jdbcTemplate() { | ||
| return new JdbcTemplate(dataSource()); // May create duplicate DataSource | ||
| } | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| @Configuration | ||
| public class DatabaseConfig { | ||
|
|
||
| @Bean | ||
| public DataSource dataSource() { | ||
| return new HikariDataSource(); | ||
| } | ||
|
|
||
| @Bean | ||
| public JdbcTemplate jdbcTemplate() { | ||
| return new JdbcTemplate(dataSource()); // Uses singleton DataSource | ||
| } | ||
| } | ||
| </pre> | ||
| <p>If you don't need inter-bean method calls and want to optimize startup performance, use <code>@Configuration(proxyBeanMethods = false)</code>. This | ||
| disables CGLIB proxying, allowing the class to be <code>final</code>. However, you must use dependency injection instead of calling <code>@Bean</code> | ||
| methods directly.</p> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="2" data-diff-type="noncompliant"> | ||
| @Configuration | ||
| public final class DatabaseConfig { // Noncompliant | ||
|
|
||
| @Bean | ||
| public DataSource dataSource() { | ||
| return new HikariDataSource(); | ||
| } | ||
|
|
||
| @Bean | ||
| public JdbcTemplate jdbcTemplate() { | ||
| return new JdbcTemplate(dataSource()); // Direct method call | ||
| } | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="2" data-diff-type="compliant"> | ||
| @Configuration(proxyBeanMethods = false) | ||
| public final class DatabaseConfig { | ||
|
|
||
| @Bean | ||
| public DataSource dataSource() { | ||
| return new HikariDataSource(); | ||
| } | ||
|
|
||
| @Bean | ||
| public JdbcTemplate jdbcTemplate(DataSource dataSource) { // Injected parameter | ||
| return new JdbcTemplate(dataSource); | ||
| } | ||
| } | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li><a href="https://docs.spring.io/spring-framework/reference/core/beans/java/configuration-annotation.html">Spring Framework - @Configuration | ||
| Annotation</a></li> | ||
| <li><a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html">Spring Framework - Proxying Mechanisms</a></li> | ||
| <li><a href="https://docs.spring.io/spring-boot/reference/using/configuration-classes.html">Spring Boot - Configuration Classes</a></li> | ||
| </ul> |
22 changes: 22 additions & 0 deletions
22
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9021.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,22 @@ | ||
| { | ||
| "title": "\"@Configuration\" classes should not be final", | ||
| "type": "BUG", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant/Issue", | ||
| "constantCost": "5min" | ||
| }, | ||
| "tags": [ | ||
| "spring" | ||
| ], | ||
| "defaultSeverity": "Critical", | ||
| "ruleSpecification": "RSPEC-9021", | ||
| "sqKey": "S9021", | ||
| "scope": "Main", | ||
| "code": { | ||
| "impacts": { | ||
| "RELIABILITY": "HIGH" | ||
| }, | ||
| "attribute": "LOGICAL" | ||
| } | ||
| } |
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.