-
Notifications
You must be signed in to change notification settings - Fork 724
SONARJAVA-6786 Implement new rule S9346: Integer values should not be cast to long for use as timestamps #5957
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
5badf2e
Implement new rule S9346
romainbrenguier 9e22591
Update ruling results for PR #5957 (#5958)
github-actions[bot] 2a1c3d1
Fix S9346 test assertion, exclude int literals, and update docs
romainbrenguier 79b5cb1
Update ruling results for S9346 after excluding int literals
romainbrenguier d5afe57
Address S9346 review findings: preserve narrowing casts, handle signe…
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
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 @@ | ||
| {} |
125 changes: 125 additions & 0 deletions
125
...ecks-test-sources/default/src/main/java/checks/IntegerToLongTimestampCastCheckSample.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,125 @@ | ||
| package checks; | ||
|
|
||
| import java.sql.Timestamp; | ||
| import java.time.Instant; | ||
| import java.util.Calendar; | ||
| import java.util.Date; | ||
| import java.util.GregorianCalendar; | ||
|
|
||
| class IntegerToLongTimestampCastCheckSample { | ||
|
|
||
| static final int INT_CONSTANT = 1234567890; | ||
|
|
||
| void noncompliantImplicitWidening() { | ||
| int intVar = 1000; | ||
| new Date(intVar); // Noncompliant {{Use a "long" value to represent this timestamp.}} | ||
| // ^^^^^^ | ||
| Instant.ofEpochSecond(intVar); // Noncompliant | ||
| Instant.ofEpochMilli(intVar); // Noncompliant | ||
| new Timestamp(intVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantExplicitCast() { | ||
| int intVar = 1000; | ||
| new Date((long) intVar); // Noncompliant | ||
| Instant.ofEpochSecond((long) intVar); // Noncompliant | ||
| Instant.ofEpochMilli((long) intVar); // Noncompliant | ||
| new Timestamp((long) intVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantArithmeticOverflow() { | ||
| int days = 365; | ||
| new Date((long) (days * 24 * 60 * 60 * 1000)); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantCalendar() { | ||
| int intVar = 1000; | ||
| Calendar cal = Calendar.getInstance(); | ||
| cal.setTimeInMillis(intVar); // Noncompliant | ||
| cal.setTimeInMillis((long) intVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantGregorianCalendar() { | ||
| int intVar = 1000; | ||
| GregorianCalendar cal = new GregorianCalendar(); | ||
| cal.setTimeInMillis(intVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantNarrowingCast() { | ||
| long longVar = 1234567890L; | ||
| new Date((int) longVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantOtherNarrowTypes() { | ||
| short shortVar = 100; | ||
| byte byteVar = 10; | ||
| char charVar = 'A'; | ||
| new Date((long) shortVar); // Noncompliant | ||
| new Date((long) byteVar); // Noncompliant | ||
| new Date((long) charVar); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantMethodReturn() { | ||
| new Date(getSeconds()); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantIntConstant() { | ||
| Instant.ofEpochSecond(INT_CONSTANT); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantOfEpochSecondTwoArgs() { | ||
| int intVar = 1000; | ||
| Instant.ofEpochSecond(intVar, 0L); // Noncompliant | ||
| } | ||
|
|
||
| void noncompliantParenthesized() { | ||
| int intVar = 1000; | ||
| new Date((intVar)); // Noncompliant | ||
| } | ||
|
|
||
| void compliantIntLiteral() { | ||
| new Date(0); | ||
| new Date(-1); | ||
| new Date(+1); | ||
| new Date((long) (0)); | ||
| } | ||
|
|
||
| void compliantLongVariable() { | ||
| long longVar = 1234567890L; | ||
| new Date(longVar); | ||
| Instant.ofEpochSecond(longVar); | ||
| Instant.ofEpochMilli(longVar); | ||
| new Timestamp(longVar); | ||
| } | ||
|
|
||
| void compliantCurrentTimeMillis() { | ||
| new Date(System.currentTimeMillis()); | ||
| } | ||
|
|
||
| void compliantLongLiteral() { | ||
| new Date(1234567890L); | ||
| } | ||
|
|
||
| void compliantCalendar() { | ||
| long longVar = 1234567890L; | ||
| Calendar cal = Calendar.getInstance(); | ||
| cal.setTimeInMillis(longVar); | ||
| } | ||
|
|
||
| void compliantLongMethodReturn() { | ||
| new Date(getMillis()); | ||
| } | ||
|
|
||
| void compliantNonTimestampCast() { | ||
| int intVar = 1000; | ||
| long result = (long) intVar; | ||
| } | ||
|
|
||
| int getSeconds() { | ||
| return 1000; | ||
| } | ||
|
|
||
| long getMillis() { | ||
| return System.currentTimeMillis(); | ||
| } | ||
| } |
118 changes: 118 additions & 0 deletions
118
java-checks/src/main/java/org/sonar/java/checks/IntegerToLongTimestampCastCheck.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,118 @@ | ||
| /* | ||
| * 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.sonar.check.Rule; | ||
| import org.sonar.java.checks.methods.AbstractMethodDetection; | ||
| import org.sonar.java.model.ExpressionUtils; | ||
| import org.sonar.plugins.java.api.semantic.MethodMatchers; | ||
| import org.sonar.plugins.java.api.semantic.Type; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MethodInvocationTree; | ||
| import org.sonar.plugins.java.api.tree.NewClassTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
| import org.sonar.plugins.java.api.tree.TypeCastTree; | ||
| import org.sonar.plugins.java.api.tree.UnaryExpressionTree; | ||
|
|
||
| @Rule(key = "S9346") | ||
| public class IntegerToLongTimestampCastCheck extends AbstractMethodDetection { | ||
|
|
||
| private static final String MESSAGE = "Use a \"long\" value to represent this timestamp."; | ||
|
|
||
| private static final MethodMatchers CONSTRUCTOR_MATCHERS = MethodMatchers.or( | ||
| MethodMatchers.create() | ||
| .ofTypes("java.util.Date") | ||
| .constructor() | ||
| .addParametersMatcher("long") | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes("java.sql.Timestamp") | ||
| .constructor() | ||
| .addParametersMatcher("long") | ||
| .build()); | ||
|
|
||
| private static final MethodMatchers METHOD_MATCHERS = MethodMatchers.or( | ||
| MethodMatchers.create() | ||
| .ofTypes("java.time.Instant") | ||
| .names("ofEpochSecond") | ||
| .addParametersMatcher("long") | ||
| .addParametersMatcher("long", "long") | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofTypes("java.time.Instant") | ||
| .names("ofEpochMilli") | ||
| .addParametersMatcher("long") | ||
| .build(), | ||
| MethodMatchers.create() | ||
| .ofSubTypes("java.util.Calendar") | ||
| .names("setTimeInMillis") | ||
| .addParametersMatcher("long") | ||
| .build()); | ||
|
|
||
| @Override | ||
| protected MethodMatchers getMethodInvocationMatchers() { | ||
| return MethodMatchers.or(CONSTRUCTOR_MATCHERS, METHOD_MATCHERS); | ||
| } | ||
|
|
||
| @Override | ||
| protected void onMethodInvocationFound(MethodInvocationTree mit) { | ||
| checkArgument(mit.arguments().get(0)); | ||
| } | ||
|
|
||
| @Override | ||
| protected void onConstructorFound(NewClassTree nct) { | ||
| checkArgument(nct.arguments().get(0)); | ||
| } | ||
|
|
||
| private void checkArgument(ExpressionTree argument) { | ||
| ExpressionTree arg = ExpressionUtils.skipParentheses(argument); | ||
| if (arg.is(Tree.Kind.TYPE_CAST)) { | ||
| TypeCastTree cast = (TypeCastTree) arg; | ||
| Type castType = cast.type().symbolType(); | ||
| if (castType.isPrimitive(Type.Primitives.LONG)) { | ||
| arg = ExpressionUtils.skipParentheses(cast.expression()); | ||
| } | ||
| } | ||
| if (isIntegerLiteral(arg)) { | ||
| return; | ||
| } | ||
| Type type = arg.symbolType(); | ||
| if (type.isUnknown()) { | ||
| return; | ||
| } | ||
| if (isNarrowIntegerType(type)) { | ||
| reportIssue(argument, MESSAGE); | ||
| } | ||
| } | ||
|
gitar-bot[bot] marked this conversation as resolved.
|
||
|
|
||
| private static boolean isIntegerLiteral(ExpressionTree expression) { | ||
| if (expression.is(Tree.Kind.INT_LITERAL)) { | ||
| return true; | ||
| } | ||
| if (expression.is(Tree.Kind.UNARY_MINUS, Tree.Kind.UNARY_PLUS)) { | ||
| return ((UnaryExpressionTree) expression).expression().is(Tree.Kind.INT_LITERAL); | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static boolean isNarrowIntegerType(Type type) { | ||
|
gitar-bot[bot] marked this conversation as resolved.
|
||
| return type.isPrimitive(Type.Primitives.INT) | ||
| || type.isPrimitive(Type.Primitives.SHORT) | ||
| || type.isPrimitive(Type.Primitives.BYTE) | ||
| || type.isPrimitive(Type.Primitives.CHAR); | ||
| } | ||
| } | ||
33 changes: 33 additions & 0 deletions
33
java-checks/src/test/java/org/sonar/java/checks/IntegerToLongTimestampCastCheckTest.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,33 @@ | ||
| /* | ||
| * 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 IntegerToLongTimestampCastCheckTest { | ||
|
|
||
| @Test | ||
| void test() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/IntegerToLongTimestampCastCheckSample.java")) | ||
| .withCheck(new IntegerToLongTimestampCastCheck()) | ||
| .verifyIssues(); | ||
| } | ||
| } |
33 changes: 33 additions & 0 deletions
33
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9346.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,33 @@ | ||
| <p>Using 32-bit signed integer types for timestamps can lead to serious reliability issues such as incorrect time representation, | ||
| system failures, and the Year 2038 problem.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p>A 32-bit signed integer can hold values from -2,147,483,648 to 2,147,483,647. While this might seem like a large range, it's insufficient for | ||
| representing timestamps:</p> | ||
| <ul> | ||
| <li><strong>Milliseconds since epoch</strong>: A 32-bit integer can only represent approximately 24.8 days of milliseconds. Any timestamp beyond | ||
| this range will overflow.</li> | ||
| <li><strong>Seconds since epoch</strong>: A 32-bit integer can represent about 68 years, covering dates from 1970 to 2038.</li> | ||
| </ul> | ||
| <p>When you cast a 32-bit integer to a 64-bit integer for use as a timestamp, you're not fixing the underlying problem — the value is already | ||
| corrupted or limited by the 32-bit constraint before the cast happens.</p> | ||
| <h3>Noncompliant code example</h3> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| int timestamp = 1234567890; | ||
| Date date = new Date(timestamp); // Noncompliant — int implicitly widened | ||
| Date date2 = new Date((long) timestamp); // Noncompliant — cast doesn't fix overflow | ||
| </pre> | ||
| <h3>Compliant solution</h3> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| long timestamp = 1234567890L; | ||
| Date date = new Date(timestamp); | ||
| Date date2 = new Date(timestamp); | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">Oracle Java Documentation - Primitive Data Types</a></li> | ||
| <li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/System.html#currentTimeMillis()">Oracle Java Documentation - | ||
| System.currentTimeMillis()</a></li> | ||
| <li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Instant.html">Oracle Java Documentation - Class Instant</a> | ||
| </li> | ||
| </ul> |
21 changes: 21 additions & 0 deletions
21
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9346.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,21 @@ | ||
| { | ||
| "title": "Integer values should not be cast to long for use as timestamps", | ||
| "type": "BUG", | ||
| "code": { | ||
| "impacts": { | ||
| "RELIABILITY": "HIGH" | ||
| }, | ||
| "attribute": "LOGICAL" | ||
| }, | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "5min" | ||
| }, | ||
| "tags": ["pitfall", "datetime"], | ||
| "defaultSeverity": "Critical", | ||
| "ruleSpecification": "RSPEC-9346", | ||
| "sqKey": "S9346", | ||
| "scope": "All", | ||
| "quickfix": "unknown" | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] Preserve narrowing casts. This unwraps every TYPE_CAST, so new Date((int) millis) inspects millis as long and reports nothing, even though the argument has been truncated to int and then implicitly widened back to long. Only unwrap casts to long; otherwise inspect the cast expression type. Please add this case to the sample.