"""VK Callback API transport and request validation.""" from __future__ import annotations import json from dataclasses import dataclass from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any, Callable @dataclass(frozen=True) class CallbackResponse: """HTTP response returned by the pure callback processor.""" status: int body: str class CallbackRequestError(ValueError): """Raised when VK sends an invalid callback request.""" def process_callback( payload: dict[str, Any], *, secret: str, expected_secret: str, group_id: int, confirmation: str, claim_event: Callable[[str, str], bool] | None, release_event: Callable[[str], None] | None, handle_event: Callable[[dict[str, Any]], None], ) -> CallbackResponse: """Validate and dispatch one VK Callback API payload. The function returns a response before the caller writes it to the socket, which keeps HTTP transport concerns separate from bot event processing. """ if not isinstance(payload, dict): return CallbackResponse(400, "invalid payload") if int(payload.get("group_id", 0) or 0) != int(group_id): return CallbackResponse(400, "invalid group_id") event_type = str(payload.get("type", "")) if event_type == "confirmation": if not confirmation: return CallbackResponse(503, "confirmation is not configured") return CallbackResponse(200, confirmation) if len(secret) > 50: return CallbackResponse(403, "forbidden") 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): event_id = payload["object"].get("event_id") if event_id is not None and claim_event is not None: if not claim_event(str(event_id), event_type): return CallbackResponse(200, "ok") try: handle_event(payload) except Exception: if event_id is not None and release_event is not None: release_event(str(event_id)) raise return CallbackResponse(200, "ok") class CallbackHTTPServer(ThreadingHTTPServer): """Threaded HTTP server bound to a Belki callback processor.""" daemon_threads = True allow_reuse_address = True def __init__(self, address: tuple[str, int], processor: Callable[..., CallbackResponse], *, expected_secret: str, group_id: int, confirmation: str, claim_event: Callable[[str, str], bool] | None, release_event: Callable[[str], None] | None, handle_event: Callable[[dict[str, Any]], None]) -> None: super().__init__(address, CallbackRequestHandler) self.processor = processor self.expected_secret = expected_secret self.group_id = group_id self.confirmation = confirmation self.claim_event = claim_event self.release_event = release_event self.handle_event = handle_event class CallbackRequestHandler(BaseHTTPRequestHandler): """Minimal HTTP adapter for VK callback requests and health checks.""" server: CallbackHTTPServer max_body_bytes = 2 * 1024 * 1024 def do_GET(self) -> None: # noqa: N802 if self.path == "/health": self._write(200, "ok") return self._write(404, "not found") def do_POST(self) -> None: # noqa: N802 if self.path != "/api/vk/callback": self._write(404, "not found") return try: length = int(self.headers.get("Content-Length", "0")) if length <= 0 or length > self.max_body_bytes: raise CallbackRequestError("invalid body size") payload = json.loads(self.rfile.read(length)) if not isinstance(payload, dict): raise CallbackRequestError("payload must be an object") response = self.server.processor( payload, secret=str(payload.get("secret", "")), expected_secret=self.server.expected_secret, group_id=self.server.group_id, confirmation=self.server.confirmation, claim_event=self.server.claim_event, release_event=self.server.release_event, handle_event=self.server.handle_event, ) except (CallbackRequestError, TypeError, ValueError, json.JSONDecodeError): self._write(400, "invalid payload") return except Exception: self._write(500, "internal error") return self._write(response.status, response.body) def _write(self, status: int, body: str) -> None: encoded = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Content-Length", str(len(encoded))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(encoded) def log_message(self, format: str, *args: object) -> None: return