fix: enforce VK callback secret limit

This commit is contained in:
nyan404 committed 2026-10-10 21:35:28 +03:00
1 parent e0e1e4f6bd
commit 7ed89d2a55
6 files changed
+17 -1

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
## Working Rules ## Working Rules
- Keep the calculation domain independent from HTTP, VK, and Kubernetes. - Keep the calculation domain independent from HTTP, VK, and Kubernetes.
- Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets. - Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets.
- Keep `VK_CALLBACK_SECRET` private as well: VK sends it in the top-level `secret` field, it is at most 50 characters, and it must never appear in URLs, logs, responses, or committed documentation.
- Production manifests are already applied in namespace `belki`; CI deploys them from `main` using the namespace-scoped RBAC in [`deploy/k8s/rbac.yaml`](./deploy/k8s/rbac.yaml). - Production manifests are already applied in namespace `belki`; CI deploys them from `main` using the namespace-scoped RBAC in [`deploy/k8s/rbac.yaml`](./deploy/k8s/rbac.yaml).
- The production build uses the GitLab runner tag `fast`, a privileged Docker executor, and an explicit `docker:29.6.1-dind` service alias over TCP. - The production build uses the GitLab runner tag `fast`, a privileged Docker executor, and an explicit `docker:29.6.1-dind` service alias over TCP.
- Production images and Kubernetes workloads are amd64-only. Preserve `linux/amd64` in Dockerfiles, CI build commands, and workload node selectors; do not reintroduce the arm64-only Python base tag. - Production images and Kubernetes workloads are amd64-only. Preserve `linux/amd64` in Dockerfiles, CI build commands, and workload node selectors; do not reintroduce the arm64-only Python base tag.
+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 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. `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`. VK sends the secret in top-level `secret`, with a maximum length of 50 characters; the code validates that limit without logging or returning the value. `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
View File
@@ -973,6 +973,8 @@ class BelkiBot:
"""Run the Callback API listener, notifications and scheduler.""" """Run the Callback API listener, notifications and scheduler."""
if not callback_secret: if not callback_secret:
raise RuntimeError("VK_CALLBACK_SECRET is required") raise RuntimeError("VK_CALLBACK_SECRET is required")
if len(callback_secret) > 50:
raise RuntimeError("VK_CALLBACK_SECRET must be at most 50 characters")
if not callback_confirmation: if not callback_confirmation:
raise RuntimeError("VK_CALLBACK_CONFIRMATION is required") raise RuntimeError("VK_CALLBACK_CONFIRMATION is required")
+2
View File
@@ -45,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 len(secret) > 50:
return CallbackResponse(403, "forbidden")
if expected_secret and secret != expected_secret: if expected_secret and secret != expected_secret:
return CallbackResponse(403, "forbidden") return CallbackResponse(403, "forbidden")
+2
View File
@@ -38,6 +38,8 @@ Callback API передаёт на HTTP endpoint JSON-события сообщ
- тип события `type`; - тип события `type`;
- структуру `object`. - структуру `object`.
VK передаёт секрет отдельным top-level полем `secret`. Это произвольная строка длиной до 50 символов. Секрет хранится только в закрытой настройке сообщества и GitLab CI/CD variable; его нельзя включать в публичный URL, логи, ответы endpoint или документацию с реальным значением.
Для сообщений текущий обработчик уже ожидает событие с: Для сообщений текущий обработчик уже ожидает событие с:
- `type: "message_new"`; - `type: "message_new"`;
+9
View File
@@ -51,6 +51,15 @@ class VkBotTests(unittest.TestCase):
self.assertEqual(process_callback(payload, **kwargs).body, "ok") self.assertEqual(process_callback(payload, **kwargs).body, "ok")
self.assertEqual(handled, [payload]) self.assertEqual(handled, [payload])
def test_callback_rejects_secret_longer_than_vk_limit(self):
response = process_callback(
{"type": "message_new", "group_id": 1},
secret="x" * 51, expected_secret="x" * 51, group_id=1,
confirmation="confirm-me", claim_event=None, release_event=None,
handle_event=lambda event: None,
)
self.assertEqual(response.status, 403)
def test_message_event_callback_is_normalized_to_button_message(self): def test_message_event_callback_is_normalized_to_button_message(self):
class Client: class Client:
def __init__(self): self.sent = [] def __init__(self): self.sent = []