Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
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 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);
}

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();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* 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;

@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)) {
arg = ((TypeCastTree) arg).expression();
}
if (arg.is(Tree.Kind.INT_LITERAL)) {
return;
}
Type type = arg.symbolType();
if (type.isUnknown()) {
return;
}
if (isNarrowIntegerType(type)) {
reportIssue(argument, MESSAGE);
}
}
Comment on lines +80 to +95

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bug: Rule misses documented case: int cast stored in long variable

The canonical Noncompliant example in S9346.html stores (long) timestamp in a long variable and then passes that variable to new Date(epochMillis). The implementation's checkArgument only inspects the direct argument at the call site (skipping parentheses and unwrapping a single TypeCast), so a long-typed variable argument yields a non-narrow type and is never reported. The primary documented pattern is therefore a false negative and is not covered by the sample test file. Either narrow the documentation example to match what the check detects (cast/int directly in the call), or extend the check to trace the argument's initializer when it is a local variable assigned from a narrow-int cast, and add a corresponding test case.

Was this helpful? React with 👍 / 👎


private static boolean isNarrowIntegerType(Type type) {
Comment thread
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);
}
}
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();
}
}
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 &mdash; 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>
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": "COMPLETE"
},
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [],
"defaultSeverity": "Critical",
"ruleSpecification": "RSPEC-9346",
"sqKey": "S9346",
"scope": "All",
"quickfix": "unknown"
}
Empty file.
Loading