fix: accept VK confirmation callback without secret

This commit is contained in:
nyan404 committed 2026-10-10 21:34:58 +03:00
1 parent 835be75049
commit e0e1e4f6bd
5 files changed
+9 -9

No files matched your search

+1 -1
View File
@@ -99,7 +99,7 @@ Inspection results persist the base score for the number of inspections and each
# 2026-10-10: VK Callback API migration # 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 # 2026-10-07: entered report state
+2 -2
View File
@@ -35,8 +35,6 @@ def process_callback(
The function returns a response before the caller writes it to the socket, The function returns a response before the caller writes it to the socket,
which keeps HTTP transport concerns separate from bot event processing. 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): if not isinstance(payload, dict):
return CallbackResponse(400, "invalid payload") return CallbackResponse(400, "invalid payload")
if int(payload.get("group_id", 0) or 0) != int(group_id): if int(payload.get("group_id", 0) or 0) != int(group_id):
@@ -47,6 +45,8 @@ def process_callback(
if not confirmation: if not confirmation:
return CallbackResponse(503, "confirmation is not configured") return CallbackResponse(503, "confirmation is not configured")
return CallbackResponse(200, confirmation) return CallbackResponse(200, confirmation)
if expected_secret and secret != expected_secret:
return CallbackResponse(403, "forbidden")
event_id = payload.get("event_id") event_id = payload.get("event_id")
if event_id is None and isinstance(payload.get("object"), dict): if event_id is None and isinstance(payload.get("object"), dict):
+2 -2
View File
@@ -33,7 +33,7 @@ Callback API передаёт на HTTP endpoint JSON-события сообщ
Обработчик должен разобрать JSON и проверить: Обработчик должен разобрать JSON и проверить:
- секрет callback-запроса; - секрет callback-запроса для обычных событий;
- `group_id`; - `group_id`;
- тип события `type`; - тип события `type`;
- структуру `object`. - структуру `object`.
@@ -60,7 +60,7 @@ Endpoint должен отвечать быстро и не оставлять V
4. для обычного события зафиксировать его ID и вернуть успешный ответ; 4. для обычного события зафиксировать его ID и вернуть успешный ответ;
5. обработать сообщение через общий обработчик Belki. 5. обработать сообщение через общий обработчик Belki.
Точный текст ответа для confirmation и успешного события нужно сверить с актуальной панелью VK перед включением сервера; не зашивать его в документацию как подтверждённый факт без тестового запроса от VK. Для `type: "confirmation"` VK может прислать только `type` и `group_id`, без поля `secret`. Сервер проверяет `group_id` и возвращает значение `VK_CALLBACK_CONFIRMATION` как plain-text строку. Для обычных событий проверяется `secret`.
## Архитектура в этом репозитории ## Архитектура в этом репозитории
+3 -3
View File
@@ -17,15 +17,15 @@ class VkBotTests(unittest.TestCase):
def test_callback_confirmation_requires_valid_secret_and_group(self): def test_callback_confirmation_requires_valid_secret_and_group(self):
handler = lambda event: None handler = lambda event: None
response = process_callback( response = process_callback(
{"type": "confirmation", "group_id": 1, "secret": "secret"}, {"type": "confirmation", "group_id": 1},
secret="secret", expected_secret="secret", group_id=1, secret="", expected_secret="secret", group_id=1,
confirmation="confirm-me", claim_event=None, release_event=None, confirmation="confirm-me", claim_event=None, release_event=None,
handle_event=handler, handle_event=handler,
) )
self.assertEqual((response.status, response.body), (200, "confirm-me")) self.assertEqual((response.status, response.body), (200, "confirm-me"))
self.assertEqual( self.assertEqual(
process_callback( 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, secret="wrong", expected_secret="secret", group_id=1,
confirmation="confirm-me", claim_event=None, release_event=None, confirmation="confirm-me", claim_event=None, release_event=None,
handle_event=handler, handle_event=handler,
+1 -1
View File
@@ -27,7 +27,7 @@ class VkCallbackHTTPTests(unittest.TestCase):
thread.start() thread.start()
try: try:
connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2) 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"}) connection.request("POST", "/api/vk/callback", body, {"Content-Type": "application/json"})
response = connection.getresponse() response = connection.getresponse()
self.assertEqual((response.status, response.read().decode()), (200, "confirm")) self.assertEqual((response.status, response.read().decode()), (200, "confirm"))