From e0e1e4f6bdb4381b8c2054811a5b0ba4b7c209b5 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Sat, 10 Oct 2026 21:34:58 +0300 Subject: [PATCH] fix: accept VK confirmation callback without secret --- MEMORY.md | 2 +- app/belki/vk_callback.py | 4 ++-- docs/vk-callback-api.md | 4 ++-- tests/test_vk_bot.py | 6 +++--- tests/test_vk_callback.py | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/MEMORY.md b/MEMORY.md index 6501c2d..b393d22 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -99,7 +99,7 @@ Inspection results persist the base score for the number of inspections and each # 2026-10-10: VK Callback API migration -`app/belki/vk_bot.py` no longer runs VK Long Poll. It starts a threaded Callback API listener on `VK_CALLBACK_HOST:VK_CALLBACK_PORT` (defaults `0.0.0.0:8081`) and requires `VK_CALLBACK_SECRET` plus `VK_CALLBACK_CONFIRMATION`. `app/belki/vk_callback.py` validates secret/group, returns confirmation or `ok`, normalizes `message_event`, and retries failed handlers by releasing the event claim. `VkConversationStore` persists seven-day callback event claims in `vk_callback_events`. Production routing uses the existing public host path `/api/vk/callback`, an exact nginx route to the `belki-bot` ClusterIP Service, and callback health probes. Live VK server registration and confirmation remain deployment-stage actions. +`app/belki/vk_bot.py` no longer runs VK Long Poll. It starts a threaded Callback API listener on `VK_CALLBACK_HOST:VK_CALLBACK_PORT` (defaults `0.0.0.0:8081`) and requires `VK_CALLBACK_SECRET` plus `VK_CALLBACK_CONFIRMATION`. `app/belki/vk_callback.py` validates group ID for confirmation requests (which may omit `secret`), validates secret for ordinary events, returns confirmation or `ok`, normalizes `message_event`, and retries failed handlers by releasing the event claim. `VkConversationStore` persists seven-day callback event claims in `vk_callback_events`. Production routing uses the existing public host path `/api/vk/callback`, an exact nginx route to the `belki-bot` ClusterIP Service, and callback health probes. Live VK server registration and confirmation remain deployment-stage actions. # 2026-10-07: entered report state diff --git a/app/belki/vk_callback.py b/app/belki/vk_callback.py index af1b9d3..10cd848 100644 --- a/app/belki/vk_callback.py +++ b/app/belki/vk_callback.py @@ -35,8 +35,6 @@ def process_callback( The function returns a response before the caller writes it to the socket, which keeps HTTP transport concerns separate from bot event processing. """ - if expected_secret and secret != expected_secret: - return CallbackResponse(403, "forbidden") if not isinstance(payload, dict): return CallbackResponse(400, "invalid payload") if int(payload.get("group_id", 0) or 0) != int(group_id): @@ -47,6 +45,8 @@ def process_callback( if not confirmation: return CallbackResponse(503, "confirmation is not configured") return CallbackResponse(200, confirmation) + if expected_secret and secret != expected_secret: + return CallbackResponse(403, "forbidden") event_id = payload.get("event_id") if event_id is None and isinstance(payload.get("object"), dict): diff --git a/docs/vk-callback-api.md b/docs/vk-callback-api.md index b4bbb51..4024dc4 100644 --- a/docs/vk-callback-api.md +++ b/docs/vk-callback-api.md @@ -33,7 +33,7 @@ Callback API передаёт на HTTP endpoint JSON-события сообщ Обработчик должен разобрать JSON и проверить: -- секрет callback-запроса; +- секрет callback-запроса для обычных событий; - `group_id`; - тип события `type`; - структуру `object`. @@ -60,7 +60,7 @@ Endpoint должен отвечать быстро и не оставлять V 4. для обычного события зафиксировать его ID и вернуть успешный ответ; 5. обработать сообщение через общий обработчик Belki. -Точный текст ответа для confirmation и успешного события нужно сверить с актуальной панелью VK перед включением сервера; не зашивать его в документацию как подтверждённый факт без тестового запроса от VK. +Для `type: "confirmation"` VK может прислать только `type` и `group_id`, без поля `secret`. Сервер проверяет `group_id` и возвращает значение `VK_CALLBACK_CONFIRMATION` как plain-text строку. Для обычных событий проверяется `secret`. ## Архитектура в этом репозитории diff --git a/tests/test_vk_bot.py b/tests/test_vk_bot.py index e117616..3f54d56 100644 --- a/tests/test_vk_bot.py +++ b/tests/test_vk_bot.py @@ -17,15 +17,15 @@ class VkBotTests(unittest.TestCase): def test_callback_confirmation_requires_valid_secret_and_group(self): handler = lambda event: None response = process_callback( - {"type": "confirmation", "group_id": 1, "secret": "secret"}, - secret="secret", expected_secret="secret", group_id=1, + {"type": "confirmation", "group_id": 1}, + secret="", expected_secret="secret", group_id=1, confirmation="confirm-me", claim_event=None, release_event=None, handle_event=handler, ) self.assertEqual((response.status, response.body), (200, "confirm-me")) self.assertEqual( process_callback( - {"type": "confirmation", "group_id": 1, "secret": "wrong"}, + {"type": "message_new", "group_id": 1, "secret": "wrong"}, secret="wrong", expected_secret="secret", group_id=1, confirmation="confirm-me", claim_event=None, release_event=None, handle_event=handler, diff --git a/tests/test_vk_callback.py b/tests/test_vk_callback.py index 70e85e1..0b2b034 100644 --- a/tests/test_vk_callback.py +++ b/tests/test_vk_callback.py @@ -27,7 +27,7 @@ class VkCallbackHTTPTests(unittest.TestCase): thread.start() try: connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2) - body = json.dumps({"type": "confirmation", "group_id": 7, "secret": "secret"}) + body = json.dumps({"type": "confirmation", "group_id": 7}) connection.request("POST", "/api/vk/callback", body, {"Content-Type": "application/json"}) response = connection.getresponse() self.assertEqual((response.status, response.read().decode()), (200, "confirm"))