Prevent integer overflow in body-range for mention rendering.

This commit is contained in:
Cody Henthorne
2026-07-30 16:18:17 -04:00
committed by Alex Hart
parent 36fb8d8aac
commit 6f5a0d0e90
3 changed files with 17 additions and 3 deletions
@@ -131,7 +131,7 @@ public final class MentionUtil {
int start = mention.getStart();
int length = mention.getLength();
return start < 0 || length < 0 || (start + length) > body.length();
return start < 0 || length < 0 || ((long) start + length) > body.length();
}
public static class UpdatedBodyAndMentions {
@@ -193,9 +193,14 @@ sealed class NotificationItem(val threadRecipient: Recipient, protected val reco
if (spoilerRanges?.isNotEmpty() == true) {
for (spoiler in spoilerRanges) {
val startIndex = spoiler.start.coerceAtMost(updatedText.length - 1).coerceAtLeast(0)
val endIndex = (spoiler.start.toLong() + spoiler.length)
.coerceIn(0L, updatedText.length.toLong())
.toInt()
.coerceAtLeast(startIndex)
updatedText = updatedText.replaceRange(
startIndex = spoiler.start.coerceAtMost(updatedText.length - 1).coerceAtLeast(0),
endIndex = (spoiler.start + spoiler.length).coerceAtMost(updatedText.length).coerceAtLeast(0),
startIndex = startIndex,
endIndex = endIndex,
replacement = "■■■■"
)
}
@@ -45,4 +45,13 @@ class MentionUtilTest {
assertThat(update.body.toString()).isEqualTo("RecipientId::1est")
}
@Test
fun overflowingRangeIsIgnored() {
val mentions = listOf(Mention(RecipientId.from(1L), 1, Int.MAX_VALUE))
val update: MentionUtil.UpdatedBodyAndMentions = MentionUtil.update("hi there", mentions) { it.recipientId.toString() }
assertThat(update.body.toString()).isEqualTo("hi there")
}
}