Compare commits

...

2 Commits

Author SHA1 Message Date
Claude
ddd192af6a test: add regression tests for relay message size guard and kind:3 parsing
Covers the OOM crash from wss://user.kindpag.es/ where a kind:3 contact
list with ~2000 follows was dropped by the size guard incorrectly (it was
not; the fix confirms messages under 512 KB still reach the listener), and
that genuinely oversized messages are silently dropped before parsing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BZJd5XPinSEEYEfDL9uS5i
2026-06-24 17:03:18 +00:00
Claude
17c7ea122f fix: drop oversized relay messages before parsing to prevent OOM
A kind:3 event with tens of thousands of ["p",...] tags arriving from
wss://user.kindpag.es/ caused repeated GC storms and OOM kills on
Android (512 MB heap, SIG:9). The client had no size guard before
calling OptimizedJsonMapper.fromJsonToMessage(), unlike the server-side
RelaySession which already gates on policy.acceptMessage().

- Reject any message longer than 512 KB (524 288 chars) before touching
  the parser; log a one-line warning with byte count instead.
- Truncate the payload logged on parse errors to 200 chars so a
  monster event can never flood logcat again.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BZJd5XPinSEEYEfDL9uS5i
2026-06-24 15:58:43 +00:00
2 changed files with 131 additions and 1 deletions

View File

@@ -71,6 +71,12 @@ open class BasicRelayClient(
// immediately drop the socket would otherwise reset the backoff on
// every onOpen and reconnect in a tight ~3s loop forever.
const val STABLE_CONNECTION_IN_SECS = TimeUtils.ONE_MINUTE
// Reject messages larger than this before attempting to parse them.
// Parsing a monster kind:3 with tens of thousands of tags allocates
// gigabytes of intermediate objects and triggers OOM on constrained
// Android devices. 512 KB is well above any legitimate Nostr event.
const val MAX_MESSAGE_BYTES = 524_288
}
private var socket: WebSocket? = null
@@ -147,13 +153,17 @@ open class BasicRelayClient(
}
override fun onMessage(text: String) {
if (text.length > MAX_MESSAGE_BYTES) {
Log.w("BasicRelayClient", "Dropping oversized message from ${url.url} (${text.length} chars > $MAX_MESSAGE_BYTES)")
return
}
try {
val msg = OptimizedJsonMapper.fromJsonToMessage(text)
listener.onIncomingMessage(this@BasicRelayClient, text, msg)
} catch (e: Throwable) {
if (e is CancellationException) throw e
// doesn't expose parsing errors to lib users as errors
Log.e("BasicRelayClient", "Failure to parse message from ${url.url}: $text", e)
Log.e("BasicRelayClient", "Failure to parse message from ${url.url}: ${text.take(200)}", e)
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.quartz.nip01Core.relay.client.single.basic
import com.vitorpamplona.quartz.nip01Core.relay.client.listeners.RelayConnectionListener
import com.vitorpamplona.quartz.nip01Core.relay.client.single.IRelayClient
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.EventMessage
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.Message
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.sockets.WebSocketListener
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertTrue
class BasicRelayClientMessageSizeTest {
private class RecordingListener : RelayConnectionListener {
val messages = mutableListOf<Message>()
override fun onIncomingMessage(
relay: IRelayClient,
msgStr: String,
msg: Message,
) {
messages.add(msg)
}
}
private data class Harness(
val socketListener: WebSocketListener,
val recordingListener: RecordingListener,
)
private fun connect(): Harness {
val builder = FakeWebsocketBuilder()
val listener = RecordingListener()
val client =
BasicRelayClient(
NormalizedRelayUrl("wss://user.kindpag.es/"),
builder,
listener,
)
client.connect()
return Harness(builder.lastListener, listener)
}
@Test
fun oversizedMessageIsDropped() {
val (socket, listener) = connect()
val oversized = "x".repeat(BasicRelayClient.MAX_MESSAGE_BYTES + 1)
socket.onMessage(oversized)
assertEquals(0, listener.messages.size)
}
@Test
fun messageBelowLimitIsNotDropped() {
val (socket, listener) = connect()
// Minimal valid EVENT message
val json =
"""["EVENT","sub1",{"id":"0000000000000000000000000000000000000000000000000000000000000001","pubkey":"0000000000000000000000000000000000000000000000000000000000000002","created_at":1000000000,"kind":1,"tags":[],"content":"hi","sig":"${"00".repeat(64)}"}]"""
assertTrue(json.length < BasicRelayClient.MAX_MESSAGE_BYTES)
socket.onMessage(json)
assertEquals(1, listener.messages.size)
}
/**
* Regression test for the OOM crash reported against wss://user.kindpag.es/:
* a kind:3 contact list with ~2000 "p" tags (~146 KB wire JSON) must parse
* successfully and must not be rejected by the MAX_MESSAGE_BYTES guard.
*/
@Test
fun kind3With2000FollowsParsesSuccessfully() {
val (socket, listener) = connect()
// Build a wire message that matches the shape of the real event reported:
// same id / pubkey / sig, ~2000 sequential dummy p-tags.
val tags =
(1..2000).joinToString(",") { i ->
val hex = i.toString(16).padStart(64, '0')
"""["p","$hex"]"""
}
val json =
"""["EVENT","test_sub",{"id":"d424a8e70ff23b7ac1712a79b2ad1653eefae43e194fb33140539039b50bdd66","pubkey":"106239448252d78fdda07a145bf797556dbdf65e1fa9807e58171a638872fe04","created_at":1782271624,"kind":3,"tags":[$tags],"content":"","sig":"1db13653a51384a3bc1aa0152768b05ab7833bc56f18d0d829e6151aac028c09633d8684be834204ef0b2415515772cc0c2ad71ebaa8a6ed2f19ef7cfd57cd16"}]"""
// Confirm the event is within the allowed size (it should be ~146 KB)
assertTrue(json.length < BasicRelayClient.MAX_MESSAGE_BYTES, "Event should be under size limit but was ${json.length} chars")
socket.onMessage(json)
assertEquals(1, listener.messages.size)
val msg = assertIs<EventMessage>(listener.messages[0])
assertEquals("d424a8e70ff23b7ac1712a79b2ad1653eefae43e194fb33140539039b50bdd66", msg.event.id)
assertEquals("106239448252d78fdda07a145bf797556dbdf65e1fa9807e58171a638872fe04", msg.event.pubKey)
assertEquals(3, msg.event.kind)
assertEquals(2000, msg.event.tags.size)
}
}