Repository navigation
Expand file tree
/
Copy pathrequest_verification.py
More file actions
77 lines (62 loc) · 2.8 KB
/
Copy pathrequest_verification.py
File metadata and controls
77 lines (62 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from logging import Logger
from typing import Any, Callable, Dict, Optional
from slack_sdk.signature import SignatureVerifier
from slack_bolt.logger import get_bolt_logger
from slack_bolt.middleware.middleware import Middleware
from slack_bolt.request import BoltRequest
from slack_bolt.response import BoltResponse
class RequestVerification(Middleware):
def __init__(self, signing_secret: str, base_logger: Optional[Logger] = None):
"""Verifies an incoming request from Slack.
Checks the validity of `x-slack-signature`, `x-slack-request-timestamp`, and the request body data.
Refer to https://docs.slack.dev/authentication/verifying-requests-from-slack/ for details.
Args:
signing_secret: The signing secret
base_logger: The base logger
"""
self._signing_secret = signing_secret
self._verifier: Optional[SignatureVerifier] = None
self.logger = get_bolt_logger(RequestVerification, base_logger=base_logger)
@property
def verifier(self) -> SignatureVerifier:
# Defer initialization to avoid errors during start up
if self._verifier is None:
self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
return self._verifier
def process(
self,
*,
req: BoltRequest,
resp: BoltResponse,
# As this method is not supposed to be invoked by bolt-python users,
# the naming conflict with the built-in one affects
# only the internals of this method
next: Callable[[], BoltResponse],
) -> BoltResponse:
if self._can_skip(req.mode, req.body):
return next()
body = req.raw_body
timestamp = req.headers.get("x-slack-request-timestamp", ["0"])[0]
signature = req.headers.get("x-slack-signature", [""])[0]
if self._is_valid_signature(body, timestamp, signature):
return next()
else:
self._debug_log_error(signature, timestamp, body)
return self._build_error_response()
# -----------------------------------------
def _is_valid_signature(self, body: str, timestamp: str, signature: str) -> bool:
verifier = self.verifier
try:
return verifier.is_valid(body, timestamp, signature)
except (TypeError, ValueError):
return False
@staticmethod
def _can_skip(mode: str, body: Dict[str, Any]) -> bool:
return mode == "socket_mode"
@staticmethod
def _build_error_response() -> BoltResponse:
return BoltResponse(status=401, body={"error": "invalid request"})
def _debug_log_error(self, signature, timestamp, body) -> None:
self.logger.info(
f"Invalid request signature detected (signature: {signature}, timestamp: {timestamp}, body: {body})"
)