Skip to content

Commit 4721655

Browse files
authored
fix: add overflow check in TimeBounds.expiresAfter() to prevent integer overflow when timeout is too large. (#753)
1 parent e1399af commit 4721655

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
### Update
66
- fix: add stricter validation for Ed25519 Signed Payload.
77
- fix: replace assert statements with explicit null checks in `Federation` class to ensure validation is not bypassed when assertions are disabled.
8+
- fix: add overflow check in `TimeBounds.expiresAfter()` to prevent integer overflow when timeout is too large.
89

910
## 2.2.1
1011

‎src/main/java/org/stellar/sdk/TimeBounds.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,16 @@ public TimeBounds(long minTime, long maxTime) {
6363
*
6464
* @param timeout Timeout in seconds.
6565
* @return TimeBounds
66+
* @throws IllegalArgumentException if timeout is negative or would cause overflow
6667
*/
6768
public static TimeBounds expiresAfter(long timeout) {
69+
if (timeout < 0) {
70+
throw new IllegalArgumentException("timeout cannot be negative");
71+
}
6872
long now = System.currentTimeMillis() / 1000L;
73+
if (timeout > Long.MAX_VALUE - now) {
74+
throw new IllegalArgumentException("timeout is too large, would cause overflow");
75+
}
6976
long endTime = now + timeout;
7077
return new TimeBounds(0, endTime);
7178
}

‎src/test/kotlin/org/stellar/sdk/TimeBoundsTest.kt‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,28 @@ class TimeBoundsTest :
6060
actualMaxTime shouldBeInRange (now + timeout - 1)..(now + timeout + 1)
6161
}
6262

63+
test("expiresAfter should throw IllegalArgumentException for negative timeout") {
64+
val exception = shouldThrow<IllegalArgumentException> { TimeBounds.expiresAfter(-1) }
65+
exception.message shouldBe "timeout cannot be negative"
66+
}
67+
68+
test("expiresAfter should throw IllegalArgumentException for overflow") {
69+
val exception =
70+
shouldThrow<IllegalArgumentException> { TimeBounds.expiresAfter(Long.MAX_VALUE) }
71+
exception.message shouldBe "timeout is too large, would cause overflow"
72+
}
73+
74+
test("expiresAfter should handle large valid timeout") {
75+
// 100 years in seconds
76+
val hundredYearsInSeconds = 100L * 365 * 24 * 60 * 60
77+
val timeBounds = TimeBounds.expiresAfter(hundredYearsInSeconds)
78+
val now = System.currentTimeMillis() / 1000L
79+
80+
timeBounds.minTime.toLong() shouldBe 0
81+
timeBounds.maxTime.toLong() shouldBeInRange
82+
(now + hundredYearsInSeconds - 1)..(now + hundredYearsInSeconds + 1)
83+
}
84+
6385
test("should handle large time values") {
6486
val largeTime = Long.MAX_VALUE - 1
6587
val timeBounds = TimeBounds(0, largeTime)

0 commit comments

Comments
 (0)