Validate complete channel event frames before publishing state

This commit is contained in:
evgeny committed 2026-10-29 13:49:00 +01:00
1 parent 9aa645e2f1
commit 07a554c888
2 files changed
+74

No files matched your search

@@ -0,0 +1,38 @@
package com.utun.chat.data
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Полные бинарные снимки событий 27/29/30 из chat_event.h. Некорректный кадр бросает
* IllegalArgumentException до изменения UI; вызывающий обработчик логирует тип события и причину. */
object ChannelEventFrames {
data class Nodes(val channel: String, val ids: List<Long>, val automatic: Long = 0)
data class Invite(val channel: String, val request: Long, val link: String?)
private fun header(data: ByteArray?, tail: Int): Pair<String, ByteBuffer> {
require(data != null && data.isNotEmpty()) { "Missing channel frame" }
val length = data[0].toInt() and 255
require(length > 0 && data.size >= 1 + length + tail) { "Invalid channel frame bytes=${data.size} channelBytes=$length" }
val channel = String(data, 1, length, Charsets.UTF_8)
return channel to ByteBuffer.wrap(data, 1 + length, data.size - 1 - length).order(ByteOrder.LITTLE_ENDIAN)
}
/** candidates=false: CONNECTING_NODES; true: INVITE_CANDIDATES с auto_node_id перед count. */
fun nodes(data: ByteArray?, candidates: Boolean = false): Nodes {
val (channel, buffer) = header(data, if (candidates) 10 else 2)
val automatic = if (candidates) buffer.long else 0L
val count = buffer.short.toInt() and 65535
require(buffer.remaining() == count * 8) { "Invalid node list channel=$channel count=$count bytes=${buffer.remaining()}" }
return Nodes(channel, List(count) { buffer.long }, automatic)
}
/** Пустой link — подтверждённая ошибка C; усечённый/дополненный кадр не завершает запрос. */
fun invite(data: ByteArray?): Invite {
val (channel, buffer) = header(data, 10)
val request = buffer.long
val length = buffer.short.toInt() and 65535
require(buffer.remaining() == length) { "Invalid invite link channel=$channel length=$length bytes=${buffer.remaining()}" }
val bytes = ByteArray(length); buffer.get(bytes)
return Invite(channel, request, if (length == 0) null else String(bytes, Charsets.UTF_8))
}
}
@@ -0,0 +1,36 @@
package com.utun.chat.data
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.*
import org.junit.Test
class ChannelEventFramesTest {
private fun frame(tail: Int, fill: ByteBuffer.() -> Unit): ByteArray =
ByteBuffer.allocate(3 + tail).order(ByteOrder.LITTLE_ENDIAN).put(2).put("42".toByteArray()).apply(fill).array()
private fun rejected(data: ByteArray?, parse: (ByteArray?) -> Unit) {
try { parse(data); fail("Malformed frame accepted") } catch (_: IllegalArgumentException) { }
}
@Test fun connectingRequiresCompleteCountAndPreservesIdBits() {
val bytes = frame(18) { putShort(2); putLong(123); putLong(Long.MIN_VALUE) }
assertEquals(ChannelEventFrames.Nodes("42", listOf(123, Long.MIN_VALUE)), ChannelEventFrames.nodes(bytes))
for (end in bytes.indices) rejected(bytes.copyOf(end)) { ChannelEventFrames.nodes(it) }
rejected(bytes + 0) { ChannelEventFrames.nodes(it) }
rejected(null) { ChannelEventFrames.nodes(it) }
}
@Test fun candidatesValidateWholeListBeforeReturningAutomaticNode() {
val bytes = frame(18) { putLong(7); putShort(1); putLong(9) }
assertEquals(ChannelEventFrames.Nodes("42", listOf(9), 7), ChannelEventFrames.nodes(bytes, true))
for (end in bytes.indices) rejected(bytes.copyOf(end)) { ChannelEventFrames.nodes(it, true) }
rejected(bytes + 0) { ChannelEventFrames.nodes(it, true) }
assertTrue(ChannelEventFrames.nodes(frame(10) { putLong(7); putShort(0) }, true).ids.isEmpty())
}
@Test fun inviteDistinguishesExplicitFailureFromTruncatedSuccess() {
val text = "utun://😀".toByteArray()
val bytes = frame(10 + text.size) { putLong(991); putShort(text.size.toShort()); put(text) }
assertEquals(ChannelEventFrames.Invite("42", 991, "utun://😀"), ChannelEventFrames.invite(bytes))
for (end in bytes.indices) rejected(bytes.copyOf(end)) { ChannelEventFrames.invite(it) }
rejected(bytes + 0) { ChannelEventFrames.invite(it) }
assertEquals(ChannelEventFrames.Invite("42", 991, null), ChannelEventFrames.invite(frame(10) { putLong(991); putShort(0) }))
}
}