From 2b113de5a15326d42e3058e2bf0337f8717ae63b Mon Sep 17 00:00:00 2001 From: evgeny Date: Wed, 28 Oct 2026 10:51:10 +0100 Subject: [PATCH] Validate poll drafts and reject malformed feedback snapshots --- .../main/java/com/utun/chat/data/Feedback.kt | 61 +++++++++++++++---- .../java/com/utun/chat/data/FeedbackTest.kt | 60 ++++++++++++++++++ 2 files changed, 110 insertions(+), 11 deletions(-) create mode 100644 tools/chatgui-android/app/src/test/java/com/utun/chat/data/FeedbackTest.kt diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/Feedback.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/Feedback.kt index 9a977b225..9d823bbae 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/Feedback.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/Feedback.kt @@ -3,39 +3,76 @@ package com.utun.chat.data import org.json.JSONArray import org.json.JSONObject +/** Элемент каталога/снимка реакций: id=0..15 общего каталога, count — участники, mine — выбор текущего узла. + * Участник хранит одну реакцию; нулевой count/mine=false также используются элементами каталога UI. */ data class ReactionState(val id: Int, val emoji: String, val count: Int = 0, val mine: Boolean = false) +/** Пункт опроса: id — индекс с нуля; percent=count/voters*100, в multiple сумма процентов может превышать 100. */ data class PollOption(val id: Int, val text: String, val count: Int, val percent: Double) +/** Последний допустимый непустой ответ участника. Feedback ограничивает nodeId диапазоном 1..Long.MAX_VALUE. */ data class PollResponse(val nodeId: Long, val choices: List, val custom: String) +/** Готовый снимок core: multiple допускает пункты вместе со своим текстом, single — один пункт либо текст. + * voters включает и участников, выбравших только свой текст; ver — версия ответа текущего узла, не версия опроса. + * myChoices/myCustom — сохранённый выбор текущего узла; answers не содержит отменённых/недопущенных ответов. */ data class PollState(val question: String, val multiple: Boolean, val allowCustom: Boolean, val options: List, val voters: Int, val ver: Long, val myChoices: List, val myCustom: String, val answers: List) +/** messageId — 64 lowercase hex; pending означает отсутствие исходного сообщения у core, не ожидающую команду UI. + * poll=null допустимо для обычного сообщения или ещё отсутствующего исходного опроса. */ data class FeedbackState(val messageId: String, val pending: Boolean, val reactions: List, val poll: PollState?) +/** Нормализованный ответ формы: отправляются только активные поля; пустой выбор/текст отменяет голос. */ data class PollVoteDraft(val choices: List, val custom: String) -fun validPollCreation(question: String, options: List): Boolean { - val bytes = 6 + question.toByteArray().size + options.sumOf { 2 + it.toByteArray().size } - return question.isNotBlank() && question.toByteArray().size <= 512 && options.size in 2..32 && - options.distinct().size == options.size && options.all { it.toByteArray().size <= 256 } && bytes <= 2048 +/** Число байтов строгого UTF-8 как в chat_poll_codec: C0 разрешены только TAB/LF/CR, NUL/непарные surrogate запрещены. */ +private fun pollTextSize(text: String, limit: Int): Int? { + if (text.length > limit || text.any { it.code < 32 && it !in "\t\n\r" }) return null + val bytes = text.toByteArray(Charsets.UTF_8) + return bytes.size.takeIf { it <= limit && String(bytes, Charsets.UTF_8) == text } } +/** Проверить готовые после trim тексты формы по лимитам core: вопрос 512, пункт 256, весь poll 2048 байт. + * 2..32 различных непустых пункта; false — обычное невалидное состояние редактируемой формы, без лог-спама. */ +fun validPollCreation(question: String, options: List): Boolean { + if (question.isEmpty() || options.size !in 2..32 || options.distinct().size != options.size) return false + var bytes = 6 + (pollTextSize(question, 512) ?: return false) + for (option in options) { + if (option.isEmpty()) return false + bytes += 2 + (pollTextSize(option, 256) ?: return false) + } + return bytes <= 2048 +} + +/** Подготовить публикуемый голос: single со своим ответом игнорирует неактивные пункты, стандартный выбор — неактивный текст. + * Trim выполняется до проверки лимита custom=1024 UTF-8 байта; пункты должны существовать и не повторяться. + * null — форму нельзя отправить, пустой PollVoteDraft — допустимое снятие голоса. Отказ core обрабатывается отдельно. */ fun preparePollVote(poll: PollState, selected: List, custom: String, customSelected: Boolean): PollVoteDraft? { - if (custom.toByteArray().size > 1024 || customSelected && custom.isBlank()) return null - return PollVoteDraft(selected, if (poll.allowCustom && (poll.multiple || customSelected)) custom.trim() else "") + val own = poll.allowCustom && (poll.multiple || customSelected) + val text = if (own) custom.trim() else "" + val choices = if (own && !poll.multiple) emptyList() else selected.toList() + if (pollTextSize(text, 1024) == null || own && !poll.multiple && text.isEmpty()) return null + if (choices.size > 32 || choices.distinct().size != choices.size || choices.any { id -> + id !in 0..31 || poll.options.none { it.id == id } + }) return null + if (!poll.multiple && choices.size > 1) return null + return PollVoteDraft(choices, text) } private fun JSONArray?.choices(): List = if (this == null) emptyList() else (0 until length()).map { getInt(it) } -/** Формат и правила задаёт ядро; интерфейс разбирает готовый снимок. */ +/** Разобрать JSON chat_feedback_snapshot, не изменяя его: семантику подсчёта и допуск авторов задаёт core. + * Ошибка формата бросает исключение; ChatViewModel логирует контекст и выставляет ошибку взаимодействия. + * Отсутствующие choices/custom трактуются как пустые; это снимок, не результат команды с snapshot_pending. */ fun parseFeedback(json: JSONObject): FeedbackState { val id = json.getString("message_id") - require(id.length == 64) { "Invalid message ID" } + require(id.length == 64 && id.all { it in '0'..'9' || it in 'a'..'f' }) { "Invalid message ID" } val reactions = json.getJSONArray("reactions").let { values -> (0 until values.length()).map { i -> values.getJSONObject(i).let { ReactionState(it.getInt("id"), it.getString("emoji"), it.getInt("count"), it.getBoolean("mine")) } } } - val poll = json.optJSONObject("poll")?.let { value -> + val poll = if (json.isNull("poll")) null else json.getJSONObject("poll").let { value -> + val mode = value.getString("mode") + require(mode == "single" || mode == "multiple") { "Invalid poll mode=$mode" } val options = value.getJSONArray("options").let { values -> (0 until values.length()).map { i -> values.getJSONObject(i).let { PollOption(it.getInt("id"), it.getString("text"), it.getInt("count"), it.getDouble("percent")) @@ -45,11 +82,13 @@ fun parseFeedback(json: JSONObject): FeedbackState { val answers = value.getJSONArray("answers").let { values -> (0 until values.length()).map { i -> values.getJSONObject(i).let { row -> val answer = row.getJSONObject("answer") - PollResponse(row.getString("node_id").removePrefix("0x").toLong(16), + val node = row.getString("node_id").removePrefix("0x").toLong(16) + require(node > 0) { "Invalid feedback node ID" } + PollResponse(node, answer.optJSONArray("choices").choices(), answer.optString("custom")) } } } - PollState(value.getString("question"), value.getString("mode") == "multiple", value.getBoolean("allow_custom_answer"), + PollState(value.getString("question"), mode == "multiple", value.getBoolean("allow_custom_answer"), options, value.getInt("voters"), value.getLong("ver"), mine.optJSONArray("choices").choices(), mine.optString("custom"), answers) } return FeedbackState(id, json.optBoolean("pending"), reactions, poll) diff --git a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/FeedbackTest.kt b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/FeedbackTest.kt new file mode 100644 index 000000000..857154c40 --- /dev/null +++ b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/FeedbackTest.kt @@ -0,0 +1,60 @@ +package com.utun.chat.data + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test + +/** Схема настоящего JSON chat_feedback_snapshot; core ограничивает ID авторов положительным signed 64-bit. */ +class FeedbackTest { + private fun snapshot() = JSONObject().put("message_id", "ab".repeat(32)).put("pending", false) + .put("reactions", JSONArray()).put("poll", JSONObject.NULL) + private fun poll() = JSONObject("""{ + "mode":"multiple","allow_custom_answer":true,"question":"Q", + "options":[{"id":0,"text":"A","count":2,"percent":100.0},{"id":1,"text":"B","count":1,"percent":50.0}], + "voters":2,"custom_count":1,"ver":17,"mine":{"choices":[0,1],"custom":""}, + "answers":[{"node_id":"0x0000000000000001","ver":17,"answer":{"choices":[0,1],"custom":""}}, + {"node_id":"0x7fffffffffffffff","ver":3,"answer":{"choices":[0],"custom":"extra"}}] + }""") + + @Test fun pendingMeansTheOriginalMessageIsMissing() { + val parsed = parseFeedback(snapshot().put("pending", true)) + assertTrue(parsed.pending); assertNull(parsed.poll); assertTrue(parsed.reactions.isEmpty()) + } + + @Test fun reactionAndMultiplePollPreserveCoreCountsAndOwnAnswerVersion() { + val json = snapshot().put("poll", poll()).put("reactions", JSONArray().put(JSONObject() + .put("id", 2).put("emoji", "❤️").put("count", 7).put("mine", true))) + val parsed = parseFeedback(json) + assertEquals(ReactionState(2, "❤️", 7, true), parsed.reactions.single()) + val state = requireNotNull(parsed.poll) + assertTrue(state.multiple); assertTrue(state.allowCustom); assertEquals(17L, state.ver) + assertEquals(listOf(0, 1), state.myChoices); assertEquals(2, state.voters) + assertEquals(Long.MAX_VALUE, state.answers[1].nodeId); assertEquals("extra", state.answers[1].custom) + assertEquals(150.0, state.options.sumOf { it.percent }, 0.0) + } + + @Test fun optionalChoiceAndCustomFieldsDefaultToAnEmptyAnswer() { + val value = poll().put("mine", JSONObject()) + value.getJSONArray("answers").getJSONObject(0).put("answer", JSONObject()) + val parsed = requireNotNull(parseFeedback(snapshot().put("poll", value)).poll) + assertTrue(parsed.myChoices.isEmpty()); assertEquals("", parsed.myCustom) + assertTrue(parsed.answers[0].choices.isEmpty()); assertEquals("", parsed.answers[0].custom) + } + + @Test fun malformedSnapshotDoesNotBecomeAnEmptySuccessfulPoll() { + assertThrows(Exception::class.java) { parseFeedback(snapshot().put("poll", "invalid")) } + for (id in listOf("a".repeat(63), "G".repeat(64), "../" + "a".repeat(61))) { + assertThrows(IllegalArgumentException::class.java) { parseFeedback(snapshot().put("message_id", id)) } + } + } + + @Test fun unknownModeAndInvalidNodeIdsFailForTheCallerToReport() { + assertThrows(IllegalArgumentException::class.java) { parseFeedback(snapshot().put("poll", poll().put("mode", "other"))) } + for (node in listOf("0x0000000000000000", "-1", "0x8000000000000000", "invalid")) { + val value = poll() + value.getJSONArray("answers").getJSONObject(0).put("node_id", node) + assertThrows(IllegalArgumentException::class.java) { parseFeedback(snapshot().put("poll", value)) } + } + } +}