From 779746c250aa2cd537fbe1941dff13be9e7885de Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 10:46:30 -0500 Subject: [PATCH 01/10] test(aws_lambda): reject malformed unsigned requests before parsing Unsigned bodies that are invalid JSON, a JSON array, or oddly shaped crash BoltRequest construction before RequestVerification can return 401. Refs #1447 Co-Authored-By: Claude --- tests/adapter_tests/aws/test_aws_lambda.py | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/adapter_tests/aws/test_aws_lambda.py b/tests/adapter_tests/aws/test_aws_lambda.py index c3590938a..df64006c1 100644 --- a/tests/adapter_tests/aws/test_aws_lambda.py +++ b/tests/adapter_tests/aws/test_aws_lambda.py @@ -127,6 +127,29 @@ def test_missing_is_base64_encoded_and_null_body(self): event = {"requestContext": {"http": {"method": "POST"}}, "headers": {}, "body": None, "isBase64Encoded": True} assert SlackRequestHandler(app).handle(event, self.context)["statusCode"] == 401 + def test_malformed_unsigned_requests_are_rejected_before_parsing(self): + app = App(client=self.web_client, signing_secret=self.signing_secret) + app.event("member_joined_channel")(lambda: None) + malformed_bodies = [ + json.dumps( + { + "type": "event_callback", + "event": {"type": "member_joined_channel", "user": "U0123456789", "channel": "C0123456789"}, + } + ), + '{"type": "event_callback", "event": ', + "[1, 2, 3]", + json.dumps({"user": "U0123456789", "view": "V0123456789", "enterprise": 1}), + ] + for body in malformed_bodies: + event = { + "requestContext": {"http": {"method": "POST"}}, + "headers": {"content-type": "application/json"}, + "body": body, + "isBase64Encoded": False, + } + assert SlackRequestHandler(app).handle(event, self.context)["statusCode"] == 401 + def test_base64_encoded_body(self): app = App(client=self.web_client, signing_secret=self.signing_secret) From 08d277bca292d017fbc8e040b7abe2ef669c948c Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 10:54:46 -0500 Subject: [PATCH 02/10] refactor(ssl_check): read ssl_check params from the raw form body SslCheck runs before RequestVerification, so it should not depend on the fully parsed request body. ssl_check requests are form encoded, and parse_qsl never raises on untrusted input. Refs #1447 Co-Authored-By: Claude --- slack_bolt/middleware/ssl_check/async_ssl_check.py | 5 +++-- slack_bolt/middleware/ssl_check/ssl_check.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/slack_bolt/middleware/ssl_check/async_ssl_check.py b/slack_bolt/middleware/ssl_check/async_ssl_check.py index 5b806a4bc..fc60b9b90 100644 --- a/slack_bolt/middleware/ssl_check/async_ssl_check.py +++ b/slack_bolt/middleware/ssl_check/async_ssl_check.py @@ -17,8 +17,9 @@ async def async_process( # only the internals of this method next: Callable[[], Awaitable[BoltResponse]], ) -> BoltResponse: - if self._is_ssl_check_request(req.body): - if self._verify_token_if_needed(req.body): + form_params = self._parse_form_params(req.raw_body) + if self._is_ssl_check_request(form_params): + if self._verify_token_if_needed(form_params): return self._build_error_response() return self._build_success_response() else: diff --git a/slack_bolt/middleware/ssl_check/ssl_check.py b/slack_bolt/middleware/ssl_check/ssl_check.py index 5e5d9ad9c..0a7f8e603 100644 --- a/slack_bolt/middleware/ssl_check/ssl_check.py +++ b/slack_bolt/middleware/ssl_check/ssl_check.py @@ -1,5 +1,6 @@ from logging import Logger -from typing import Callable, Optional +from typing import Callable, Dict, Optional +from urllib.parse import parse_qsl from slack_bolt.logger import get_bolt_logger from slack_bolt.middleware.middleware import Middleware @@ -38,8 +39,9 @@ def process( # only the internals of this method next: Callable[[], BoltResponse], ) -> BoltResponse: - if self._is_ssl_check_request(req.body): - if self._verify_token_if_needed(req.body): + form_params = self._parse_form_params(req.raw_body) + if self._is_ssl_check_request(form_params): + if self._verify_token_if_needed(form_params): return self._build_error_response() return self._build_success_response() else: @@ -47,6 +49,10 @@ def process( # ----------------------------------------- + @staticmethod + def _parse_form_params(raw_body: str) -> Dict[str, str]: + return dict(parse_qsl(raw_body, keep_blank_values=True)) + @staticmethod def _is_ssl_check_request(body: dict): return "ssl_check" in body and body["ssl_check"] == "1" From 06b6a164898efff95c874f6e5fa615297d2d2755 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 11:07:12 -0500 Subject: [PATCH 03/10] feat: add defer_parsing to BoltRequest and a RequestParsing middleware A request created with defer_parsing=True keeps its raw body unparsed and its context unbuilt. The new built-in RequestParsing middleware completes both right after RequestVerification, so unsigned payloads are never parsed. Context values set after the request was created still win, and the per-request client gets the team_id it could not see earlier. The default stays eager, so code that builds a BoltRequest directly is unchanged. Refs #1447 Co-Authored-By: Claude --- slack_bolt/app/app.py | 2 + slack_bolt/app/async_app.py | 2 + slack_bolt/middleware/__init__.py | 3 + slack_bolt/middleware/async_builtins.py | 2 + .../middleware/request_parsing/__init__.py | 5 + .../request_parsing/async_request_parsing.py | 25 +++ .../request_parsing/request_parsing.py | 30 ++++ slack_bolt/request/async_request.py | 35 +++- slack_bolt/request/request.py | 35 +++- tests/scenario_tests/test_request_parsing.py | 153 ++++++++++++++++++ .../test_request_parsing.py | 105 ++++++++++++ 11 files changed, 381 insertions(+), 16 deletions(-) create mode 100644 slack_bolt/middleware/request_parsing/__init__.py create mode 100644 slack_bolt/middleware/request_parsing/async_request_parsing.py create mode 100644 slack_bolt/middleware/request_parsing/request_parsing.py create mode 100644 tests/scenario_tests/test_request_parsing.py create mode 100644 tests/scenario_tests_async/test_request_parsing.py diff --git a/slack_bolt/app/app.py b/slack_bolt/app/app.py index cbaa340f7..db48330fe 100644 --- a/slack_bolt/app/app.py +++ b/slack_bolt/app/app.py @@ -64,6 +64,7 @@ Middleware, SslCheck, RequestVerification, + RequestParsing, SingleTeamAuthorization, MultiTeamsAuthorization, IgnoringSelfEvents, @@ -411,6 +412,7 @@ def _init_middleware_list( ) if request_verification_enabled is True: self._middleware_list.append(RequestVerification(self._signing_secret, base_logger=self._base_logger)) + self._middleware_list.append(RequestParsing()) if self._before_authorize is not None: self._middleware_list.append(self._before_authorize) diff --git a/slack_bolt/app/async_app.py b/slack_bolt/app/async_app.py index 729d626c2..2656203dd 100644 --- a/slack_bolt/app/async_app.py +++ b/slack_bolt/app/async_app.py @@ -83,6 +83,7 @@ from slack_bolt.middleware.async_builtins import ( AsyncSslCheck, AsyncRequestVerification, + AsyncRequestParsing, AsyncIgnoringSelfEvents, AsyncUrlVerification, AsyncAttachingFunctionToken, @@ -418,6 +419,7 @@ def _init_async_middleware_list( ) if request_verification_enabled is True: self._async_middleware_list.append(AsyncRequestVerification(self._signing_secret, base_logger=self._base_logger)) + self._async_middleware_list.append(AsyncRequestParsing()) if self._async_before_authorize is not None: self._async_middleware_list.append(self._async_before_authorize) diff --git a/slack_bolt/middleware/__init__.py b/slack_bolt/middleware/__init__.py index c62cd6650..d5500ccee 100644 --- a/slack_bolt/middleware/__init__.py +++ b/slack_bolt/middleware/__init__.py @@ -15,6 +15,7 @@ from .ignoring_self_events import IgnoringSelfEvents from .middleware import Middleware from .request_verification import RequestVerification +from .request_parsing import RequestParsing from .ssl_check import SslCheck from .url_verification import UrlVerification from .attaching_function_token import AttachingFunctionToken @@ -23,6 +24,7 @@ builtin_middleware_classes = [ SslCheck, RequestVerification, + RequestParsing, SingleTeamAuthorization, MultiTeamsAuthorization, IgnoringSelfEvents, @@ -40,6 +42,7 @@ "IgnoringSelfEvents", "Middleware", "RequestVerification", + "RequestParsing", "SslCheck", "UrlVerification", "AttachingFunctionToken", diff --git a/slack_bolt/middleware/async_builtins.py b/slack_bolt/middleware/async_builtins.py index 8de07fb88..00b58a691 100644 --- a/slack_bolt/middleware/async_builtins.py +++ b/slack_bolt/middleware/async_builtins.py @@ -4,6 +4,7 @@ from .request_verification.async_request_verification import ( AsyncRequestVerification, ) +from .request_parsing.async_request_parsing import AsyncRequestParsing from .ssl_check.async_ssl_check import AsyncSslCheck from .url_verification.async_url_verification import AsyncUrlVerification from .message_listener_matches.async_message_listener_matches import ( @@ -15,6 +16,7 @@ __all__ = [ "AsyncIgnoringSelfEvents", "AsyncRequestVerification", + "AsyncRequestParsing", "AsyncSslCheck", "AsyncUrlVerification", "AsyncMessageListenerMatches", diff --git a/slack_bolt/middleware/request_parsing/__init__.py b/slack_bolt/middleware/request_parsing/__init__.py new file mode 100644 index 000000000..85eabc8ab --- /dev/null +++ b/slack_bolt/middleware/request_parsing/__init__.py @@ -0,0 +1,5 @@ +from .request_parsing import RequestParsing + +__all__ = [ + "RequestParsing", +] diff --git a/slack_bolt/middleware/request_parsing/async_request_parsing.py b/slack_bolt/middleware/request_parsing/async_request_parsing.py new file mode 100644 index 000000000..5f9a8ce49 --- /dev/null +++ b/slack_bolt/middleware/request_parsing/async_request_parsing.py @@ -0,0 +1,25 @@ +from typing import Awaitable, Callable + +from slack_bolt.middleware.async_middleware import AsyncMiddleware +from slack_bolt.middleware.request_parsing.request_parsing import attach_team_id_to_client +from slack_bolt.request.async_request import AsyncBoltRequest +from slack_bolt.response import BoltResponse + + +class AsyncRequestParsing(AsyncMiddleware): + """Parses the body and builds the context of a request created with `defer_parsing=True`. + + Runs right after `AsyncRequestVerification`, so unsigned payloads are never parsed. + """ + + async def async_process( + self, + *, + req: AsyncBoltRequest, + resp: BoltResponse, + next: Callable[[], Awaitable[BoltResponse]], + ) -> BoltResponse: + if req.defer_parsing: + req.complete_deferred_parsing() + attach_team_id_to_client(req.context) + return await next() diff --git a/slack_bolt/middleware/request_parsing/request_parsing.py b/slack_bolt/middleware/request_parsing/request_parsing.py new file mode 100644 index 000000000..0214edd83 --- /dev/null +++ b/slack_bolt/middleware/request_parsing/request_parsing.py @@ -0,0 +1,30 @@ +from typing import Callable + +from slack_bolt.context.base_context import BaseContext +from slack_bolt.middleware.middleware import Middleware +from slack_bolt.request import BoltRequest +from slack_bolt.response import BoltResponse + + +class RequestParsing(Middleware): + """Parses the body and builds the context of a request created with `defer_parsing=True`. + + Runs right after `RequestVerification`, so unsigned payloads are never parsed. + """ + + def process( + self, + *, + req: BoltRequest, + resp: BoltResponse, + next: Callable[[], BoltResponse], + ) -> BoltResponse: + if req.defer_parsing: + req.complete_deferred_parsing() + attach_team_id_to_client(req.context) + return next() + + +def attach_team_id_to_client(context: BaseContext) -> None: + if context.team_id is not None and context.get("client") is not None: + context["client"].default_params["team_id"] = context.team_id diff --git a/slack_bolt/request/async_request.py b/slack_bolt/request/async_request.py index c6a06f309..c6a477c90 100644 --- a/slack_bolt/request/async_request.py +++ b/slack_bolt/request/async_request.py @@ -22,6 +22,7 @@ class AsyncBoltRequest: lazy_only: bool lazy_function_name: Optional[str] mode: str # either "http" or "socket_mode" + defer_parsing: bool def __init__( self, @@ -31,6 +32,7 @@ def __init__( headers: Optional[Dict[str, Union[str, Sequence[str]]]] = None, context: Optional[Dict[str, Any]] = None, mode: str = "http", # either "http" or "socket_mode" + defer_parsing: bool = False, ): """Request to a Bolt app. @@ -40,6 +42,9 @@ def __init__( headers: The request headers. context: The context in this request. mode: The mode used for this request. (either "http" or "socket_mode") + defer_parsing: True to leave `body` empty and skip building `context` from it until + the built-in `RequestParsing` middleware runs after `RequestVerification`. + Adapters set this so unsigned payloads are never parsed. """ if mode == "http": # HTTP Mode @@ -59,18 +64,32 @@ def __init__( self.headers = build_normalized_headers(headers) self.content_type = extract_content_type(self.headers) - if isinstance(body, str): - self.body = parse_body(self.raw_body, self.content_type) - elif isinstance(body, dict): - self.body = body - else: - self.body = {} - - self.context = build_async_context(AsyncBoltContext(context if context else {}), self.body) + self.body = body if isinstance(body, dict) else {} + self.context = AsyncBoltContext(context if context else {}) + self.defer_parsing = defer_parsing + if not defer_parsing: + self._parse_body_and_build_context() self.lazy_only = bool(self.headers.get("x-slack-bolt-lazy-only", [False])[0]) self.lazy_function_name = self.headers.get("x-slack-bolt-lazy-function-name", [None])[0] self.mode = mode + def complete_deferred_parsing(self) -> None: + """Parses the body and builds the context of a request created with `defer_parsing=True`. + + Context values set after the request was created take precedence over the ones in the body. + """ + if not self.defer_parsing: + return + set_after_creation = dict(self.context) + self._parse_body_and_build_context() + self.context.update(set_after_creation) + self.defer_parsing = False + + def _parse_body_and_build_context(self) -> None: + if self.raw_body: + self.body = parse_body(self.raw_body, self.content_type) + build_async_context(self.context, self.body) + def to_copyable(self) -> "AsyncBoltRequest": body: Union[str, dict] = self.raw_body if self.mode == "http" else self.body return AsyncBoltRequest( diff --git a/slack_bolt/request/request.py b/slack_bolt/request/request.py index 2a418a33f..dcb49d8a4 100644 --- a/slack_bolt/request/request.py +++ b/slack_bolt/request/request.py @@ -22,6 +22,7 @@ class BoltRequest: lazy_only: bool lazy_function_name: Optional[str] mode: str # either "http" or "socket_mode" + defer_parsing: bool def __init__( self, @@ -31,6 +32,7 @@ def __init__( headers: Optional[Dict[str, Union[str, Sequence[str]]]] = None, context: Optional[Dict[str, Any]] = None, mode: str = "http", # either "http" or "socket_mode" + defer_parsing: bool = False, ): """Request to a Bolt app. @@ -40,6 +42,9 @@ def __init__( headers: The request headers. context: The context in this request. mode: The mode used for this request. (either "http" or "socket_mode") + defer_parsing: True to leave `body` empty and skip building `context` from it until + the built-in `RequestParsing` middleware runs after `RequestVerification`. + Adapters set this so unsigned payloads are never parsed. """ if mode == "http": # HTTP Mode @@ -59,18 +64,32 @@ def __init__( self.headers = build_normalized_headers(headers) self.content_type = extract_content_type(self.headers) - if isinstance(body, str): - self.body = parse_body(self.raw_body, self.content_type) - elif isinstance(body, dict): - self.body = body - else: - self.body = {} - - self.context = build_context(BoltContext(context if context else {}), self.body) + self.body = body if isinstance(body, dict) else {} + self.context = BoltContext(context if context else {}) + self.defer_parsing = defer_parsing + if not defer_parsing: + self._parse_body_and_build_context() self.lazy_only = bool(self.headers.get("x-slack-bolt-lazy-only", [False])[0]) self.lazy_function_name = self.headers.get("x-slack-bolt-lazy-function-name", [None])[0] self.mode = mode + def complete_deferred_parsing(self) -> None: + """Parses the body and builds the context of a request created with `defer_parsing=True`. + + Context values set after the request was created take precedence over the ones in the body. + """ + if not self.defer_parsing: + return + set_after_creation = dict(self.context) + self._parse_body_and_build_context() + self.context.update(set_after_creation) + self.defer_parsing = False + + def _parse_body_and_build_context(self) -> None: + if self.raw_body: + self.body = parse_body(self.raw_body, self.content_type) + build_context(self.context, self.body) + def to_copyable(self) -> "BoltRequest": body: Union[str, dict] = self.raw_body if self.mode == "http" else self.body return BoltRequest( diff --git a/tests/scenario_tests/test_request_parsing.py b/tests/scenario_tests/test_request_parsing.py new file mode 100644 index 000000000..b5998c6c1 --- /dev/null +++ b/tests/scenario_tests/test_request_parsing.py @@ -0,0 +1,153 @@ +import json +from time import time + +from slack_sdk.signature import SignatureVerifier +from slack_sdk.web import WebClient + +from slack_bolt import App, BoltRequest +from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server +from tests.scenario_tests import test_block_actions, test_shortcut, test_slash_command, test_view_submission +from tests.slack_bolt.request import test_internals +from tests.utils import remove_os_env_temporarily, restore_os_env + +form_bodies = [ + test_block_actions.raw_body, + test_shortcut.global_shortcut_raw_body, + test_shortcut.message_shortcut_raw_body, + test_slash_command.slash_command_body, + test_view_submission.raw_body, + test_view_submission.raw_response_url_body, + test_view_submission.connect_channel_body, +] +json_bodies = [ + json.dumps(payload) + for name, payloads in vars(test_internals.TestRequestInternals).items() + if name.endswith("requests") + for payload in payloads +] +signed_bodies = form_bodies + json_bodies + +malformed_unsigned_bodies = [ + json.dumps( + { + "type": "event_callback", + "event": {"type": "member_joined_channel", "user": "U0123456789", "channel": "C0123456789"}, + } + ), + '{"type": "event_callback", "event": ', + "[1, 2, 3]", + json.dumps({"user": "U0123456789", "view": "V0123456789", "enterprise": 1}), +] + + +def plain_values(context: dict) -> dict: + return { + key: value if isinstance(value, (str, bool, int, dict, list, type(None))) else type(value).__name__ + for key, value in context.items() + } + + +class TestRequestParsing: + signing_secret = "secret" + valid_token = "xoxb-valid" + mock_api_server_base_url = "http://localhost:8888" + signature_verifier = SignatureVerifier(signing_secret) + web_client = WebClient(token=valid_token, base_url=mock_api_server_base_url) + + def setup_method(self): + self.old_os_env = remove_os_env_temporarily() + setup_mock_web_api_server(self) + + def teardown_method(self): + cleanup_mock_web_api_server(self) + restore_os_env(self.old_os_env) + + def build_request(self, body: str, defer_parsing: bool) -> BoltRequest: + timestamp = str(int(time())) + content_type = "application/json" if body.startswith("{") else "application/x-www-form-urlencoded" + return BoltRequest( + body=body, + headers={ + "content-type": [content_type], + "x-slack-signature": [self.signature_verifier.generate_signature(body=body, timestamp=timestamp)], + "x-slack-request-timestamp": [timestamp], + }, + defer_parsing=defer_parsing, + ) + + def capture_after_dispatch(self, request: BoltRequest) -> dict: + app = App(client=self.web_client, signing_secret=self.signing_secret) + captured = {} + + @app.middleware + def capture(context, body, next): + captured["context"] = plain_values(context) + captured["body"] = body + captured["client_default_params"] = dict(context.client.default_params) + next() + + app.dispatch(request) + return captured + + def test_deferred_parsing_matches_eager_parsing(self): + for body in signed_bodies: + eager = self.capture_after_dispatch(self.build_request(body, defer_parsing=False)) + deferred = self.capture_after_dispatch(self.build_request(body, defer_parsing=True)) + assert eager != {} + assert deferred == eager, body + + def test_deferred_request_is_unparsed_until_dispatch(self): + request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + assert request.body == {} + assert request.context.team_id is None + request.complete_deferred_parsing() + assert request.body["team_id"] == "T111" + assert request.context.team_id == "T111" + + def test_context_set_after_creation_wins_over_body(self): + request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + request.context["team_id"] = "T_FROM_ADAPTER" + request.context["lambda_request"] = {"source": "adapter"} + request.complete_deferred_parsing() + assert request.context.team_id == "T_FROM_ADAPTER" + assert request.context["lambda_request"] == {"source": "adapter"} + assert request.context.user_id == "W111" + + def test_malformed_unsigned_deferred_requests_are_rejected(self): + app = App(client=self.web_client, signing_secret=self.signing_secret) + for body in malformed_unsigned_bodies: + request = BoltRequest(body=body, headers={"content-type": ["application/json"]}, defer_parsing=True) + assert app.dispatch(request).status == 401 + + def test_deferred_parsing_without_request_verification(self): + app = App(client=self.web_client, signing_secret=self.signing_secret, request_verification_enabled=False) + captured = {} + + @app.middleware + def capture(context, next): + captured["team_id"] = context.team_id + next() + + request = BoltRequest(body=test_slash_command.slash_command_body, defer_parsing=True) + app.dispatch(request) + assert captured["team_id"] == "T111" + + def test_signed_invalid_json_is_handled_by_the_error_handler(self): + app = App(client=self.web_client, signing_secret=self.signing_secret) + response = app.dispatch(self.build_request('{"type": "event_callback", ', defer_parsing=True)) + assert response.status == 500 + + def test_ssl_check_on_deferred_request(self): + app = App(client=self.web_client, signing_secret=self.signing_secret) + request = BoltRequest(body="token=random&ssl_check=1", defer_parsing=True) + response = app.dispatch(request) + assert response.status == 200 + assert response.body == "" + + def test_to_copyable_of_deferred_request_is_parsed(self): + request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + request.complete_deferred_parsing() + copied = request.to_copyable() + assert copied.defer_parsing is False + assert copied.body == request.body + assert copied.context.team_id == "T111" diff --git a/tests/scenario_tests_async/test_request_parsing.py b/tests/scenario_tests_async/test_request_parsing.py new file mode 100644 index 000000000..cd03ac7b6 --- /dev/null +++ b/tests/scenario_tests_async/test_request_parsing.py @@ -0,0 +1,105 @@ +from time import time + +import pytest +from slack_sdk.signature import SignatureVerifier +from slack_sdk.web.async_client import AsyncWebClient + +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.request.async_request import AsyncBoltRequest +from tests.mock_web_api_server import cleanup_mock_web_api_server_async, setup_mock_web_api_server_async +from tests.scenario_tests import test_slash_command +from tests.scenario_tests.test_request_parsing import malformed_unsigned_bodies, plain_values, signed_bodies +from tests.utils import remove_os_env_temporarily, restore_os_env + + +class TestAsyncRequestParsing: + signing_secret = "secret" + valid_token = "xoxb-valid" + mock_api_server_base_url = "http://localhost:8888" + signature_verifier = SignatureVerifier(signing_secret) + web_client = AsyncWebClient(token=valid_token, base_url=mock_api_server_base_url) + + @pytest.fixture(scope="function", autouse=True) + def setup_teardown(self): + old_os_env = remove_os_env_temporarily() + setup_mock_web_api_server_async(self) + try: + yield + finally: + cleanup_mock_web_api_server_async(self) + restore_os_env(old_os_env) + + def build_request(self, body: str, defer_parsing: bool) -> AsyncBoltRequest: + timestamp = str(int(time())) + content_type = "application/json" if body.startswith("{") else "application/x-www-form-urlencoded" + return AsyncBoltRequest( + body=body, + headers={ + "content-type": [content_type], + "x-slack-signature": [self.signature_verifier.generate_signature(body=body, timestamp=timestamp)], + "x-slack-request-timestamp": [timestamp], + }, + defer_parsing=defer_parsing, + ) + + async def capture_after_dispatch(self, request: AsyncBoltRequest) -> dict: + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) + captured = {} + + @app.middleware + async def capture(context, body, next): + captured["context"] = plain_values(context) + captured["body"] = body + captured["client_default_params"] = dict(context.client.default_params) + await next() + + await app.async_dispatch(request) + return captured + + @pytest.mark.asyncio + async def test_deferred_parsing_matches_eager_parsing(self): + for body in signed_bodies: + eager = await self.capture_after_dispatch(self.build_request(body, defer_parsing=False)) + deferred = await self.capture_after_dispatch(self.build_request(body, defer_parsing=True)) + assert eager != {} + assert deferred == eager, body + + @pytest.mark.asyncio + async def test_malformed_unsigned_deferred_requests_are_rejected(self): + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) + for body in malformed_unsigned_bodies: + request = AsyncBoltRequest(body=body, headers={"content-type": ["application/json"]}, defer_parsing=True) + assert (await app.async_dispatch(request)).status == 401 + + @pytest.mark.asyncio + async def test_context_set_after_creation_wins_over_body(self): + request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + request.context["team_id"] = "T_FROM_ADAPTER" + request.complete_deferred_parsing() + assert request.context.team_id == "T_FROM_ADAPTER" + assert request.context.user_id == "W111" + + @pytest.mark.asyncio + async def test_deferred_parsing_without_request_verification(self): + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret, request_verification_enabled=False) + captured = {} + + @app.middleware + async def capture(context, next): + captured["team_id"] = context.team_id + await next() + + await app.async_dispatch(AsyncBoltRequest(body=test_slash_command.slash_command_body, defer_parsing=True)) + assert captured["team_id"] == "T111" + + @pytest.mark.asyncio + async def test_signed_invalid_json_is_handled_by_the_error_handler(self): + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) + response = await app.async_dispatch(self.build_request('{"type": "event_callback", ', defer_parsing=True)) + assert response.status == 500 + + @pytest.mark.asyncio + async def test_ssl_check_on_deferred_request(self): + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) + response = await app.async_dispatch(AsyncBoltRequest(body="token=random&ssl_check=1", defer_parsing=True)) + assert response.status == 200 From e18f19bb6e570ee2100337e75a34ae18704272d5 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 11:07:12 -0500 Subject: [PATCH 04/10] feat(adapter): defer body parsing in adapters until after verification Every HTTP adapter and the built-in dev servers pass defer_parsing=True where they hand the request to dispatch. The public to_bolt_request helpers keep eager parsing by default, and OAuth and Socket Mode paths are unchanged. Fixes #1447 Co-Authored-By: Claude --- slack_bolt/adapter/aiohttp/__init__.py | 3 ++- slack_bolt/adapter/asgi/aiohttp/__init__.py | 7 ++++++- slack_bolt/adapter/asgi/builtin/__init__.py | 7 ++++++- slack_bolt/adapter/aws_lambda/chalice_handler.py | 7 ++++--- slack_bolt/adapter/aws_lambda/handler.py | 7 ++++--- slack_bolt/adapter/bottle/handler.py | 5 +++-- slack_bolt/adapter/cherrypy/handler.py | 5 +++-- slack_bolt/adapter/django/handler.py | 5 +++-- slack_bolt/adapter/falcon/async_resource.py | 5 +++-- slack_bolt/adapter/falcon/resource.py | 5 +++-- slack_bolt/adapter/flask/handler.py | 5 +++-- slack_bolt/adapter/google_cloud_functions/handler.py | 2 +- slack_bolt/adapter/pyramid/handler.py | 5 +++-- slack_bolt/adapter/sanic/async_handler.py | 11 +++++++++-- slack_bolt/adapter/starlette/async_handler.py | 6 +++++- slack_bolt/adapter/starlette/handler.py | 4 +++- slack_bolt/adapter/tornado/async_handler.py | 5 +++-- slack_bolt/adapter/tornado/handler.py | 5 +++-- slack_bolt/adapter/wsgi/handler.py | 7 ++++++- slack_bolt/app/app.py | 1 + slack_bolt/app/async_server.py | 2 +- 21 files changed, 75 insertions(+), 34 deletions(-) diff --git a/slack_bolt/adapter/aiohttp/__init__.py b/slack_bolt/adapter/aiohttp/__init__.py index 9267f2515..52d0f849c 100644 --- a/slack_bolt/adapter/aiohttp/__init__.py +++ b/slack_bolt/adapter/aiohttp/__init__.py @@ -6,11 +6,12 @@ from slack_bolt.response import BoltResponse -async def to_bolt_request(request: web.Request) -> AsyncBoltRequest: +async def to_bolt_request(request: web.Request, defer_parsing: bool = False) -> AsyncBoltRequest: return AsyncBoltRequest( body=await request.text(), query=request.query_string, headers=request.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/asgi/aiohttp/__init__.py b/slack_bolt/adapter/asgi/aiohttp/__init__.py index 796098537..a35aac76e 100644 --- a/slack_bolt/adapter/asgi/aiohttp/__init__.py +++ b/slack_bolt/adapter/asgi/aiohttp/__init__.py @@ -36,7 +36,12 @@ def __init__(self, app: AsyncApp, path: str = "/slack/events"): async def dispatch(self, request: AsgiHttpRequest) -> BoltResponse: return await self.app.async_dispatch( - AsyncBoltRequest(body=await request.get_raw_body(), query=request.query_string, headers=request.get_headers()) + AsyncBoltRequest( + body=await request.get_raw_body(), + query=request.query_string, + headers=request.get_headers(), + defer_parsing=True, + ) ) async def handle_installation(self, request: AsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/adapter/asgi/builtin/__init__.py b/slack_bolt/adapter/asgi/builtin/__init__.py index b05451f34..1c7e7b595 100644 --- a/slack_bolt/adapter/asgi/builtin/__init__.py +++ b/slack_bolt/adapter/asgi/builtin/__init__.py @@ -35,7 +35,12 @@ def __init__(self, app: App, path: str = "/slack/events"): async def dispatch(self, request: AsgiHttpRequest) -> BoltResponse: return self.app.dispatch( - BoltRequest(body=await request.get_raw_body(), query=request.query_string, headers=request.get_headers()) + BoltRequest( + body=await request.get_raw_body(), + query=request.query_string, + headers=request.get_headers(), + defer_parsing=True, + ) ) async def handle_installation(self, request: AsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/adapter/aws_lambda/chalice_handler.py b/slack_bolt/adapter/aws_lambda/chalice_handler.py index 00200b6da..2f8a13a0a 100644 --- a/slack_bolt/adapter/aws_lambda/chalice_handler.py +++ b/slack_bolt/adapter/aws_lambda/chalice_handler.py @@ -72,7 +72,7 @@ def handle(self, request: Request): bolt_resp = oauth_flow.handle_installation(bolt_req) return to_chalice_response(bolt_resp) elif method == "POST": - bolt_req = to_bolt_request(request, body) + bolt_req = to_bolt_request(request, body, defer_parsing=True) # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html aws_lambda_function_name = self.chalice.lambda_context.function_name bolt_req.context["aws_lambda_function_name"] = aws_lambda_function_name @@ -81,7 +81,7 @@ def handle(self, request: Request): aws_response = to_chalice_response(bolt_resp) return aws_response elif method == "NONE": - bolt_req = to_bolt_request(request, body) + bolt_req = to_bolt_request(request, body, defer_parsing=True) bolt_resp = self.app.dispatch(bolt_req) aws_response = to_chalice_response(bolt_resp) return aws_response @@ -89,11 +89,12 @@ def handle(self, request: Request): return not_found() -def to_bolt_request(request: Request, body: str) -> BoltRequest: +def to_bolt_request(request: Request, body: str, defer_parsing: bool = False) -> BoltRequest: return BoltRequest( body=body, query=request.query_params, # type: ignore[arg-type] headers=request.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/aws_lambda/handler.py b/slack_bolt/adapter/aws_lambda/handler.py index 088055af1..ce5c8f43e 100644 --- a/slack_bolt/adapter/aws_lambda/handler.py +++ b/slack_bolt/adapter/aws_lambda/handler.py @@ -52,7 +52,7 @@ def handle(self, event, context): bolt_resp = oauth_flow.handle_installation(bolt_req) return to_aws_response(bolt_resp) elif method == "POST": - bolt_req = to_bolt_request(event) + bolt_req = to_bolt_request(event, defer_parsing=True) # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html aws_lambda_function_name = context.function_name bolt_req.context["aws_lambda_function_name"] = aws_lambda_function_name @@ -64,7 +64,7 @@ def handle(self, event, context): aws_response = to_aws_response(bolt_resp) return aws_response elif method == "NONE": - bolt_req = to_bolt_request(event) + bolt_req = to_bolt_request(event, defer_parsing=True) bolt_resp = self.app.dispatch(bolt_req) aws_response = to_aws_response(bolt_resp) return aws_response @@ -72,7 +72,7 @@ def handle(self, event, context): return not_found() -def to_bolt_request(event) -> BoltRequest: +def to_bolt_request(event, defer_parsing: bool = False) -> BoltRequest: body = event.get("body") or "" if event.get("isBase64Encoded") is True and body: body = base64.b64decode(body).decode("utf-8") @@ -90,6 +90,7 @@ def to_bolt_request(event) -> BoltRequest: body=body, query=event.get("queryStringParameters") or {}, headers=headers, + defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/bottle/handler.py b/slack_bolt/adapter/bottle/handler.py index d99e24afa..f0276054d 100644 --- a/slack_bolt/adapter/bottle/handler.py +++ b/slack_bolt/adapter/bottle/handler.py @@ -6,7 +6,7 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: Request) -> BoltRequest: +def to_bolt_request(req: Request, defer_parsing: bool = False) -> BoltRequest: body = req.body.read() if isinstance(body, bytes): body = body.decode("utf-8") @@ -14,6 +14,7 @@ def to_bolt_request(req: Request) -> BoltRequest: body=body, query=req.query_string, headers=req.headers, + defer_parsing=defer_parsing, ) @@ -41,7 +42,7 @@ def handle(self, req: Request, resp: Response) -> str: set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req)) + bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) set_response(bolt_resp, resp) return bolt_resp.body or "" diff --git a/slack_bolt/adapter/cherrypy/handler.py b/slack_bolt/adapter/cherrypy/handler.py index f3d714cc6..8e784a584 100644 --- a/slack_bolt/adapter/cherrypy/handler.py +++ b/slack_bolt/adapter/cherrypy/handler.py @@ -8,13 +8,14 @@ from slack_bolt.response import BoltResponse -def build_bolt_request() -> BoltRequest: +def build_bolt_request(defer_parsing: bool = False) -> BoltRequest: req = cherrypy.request body = req.raw_body if hasattr(req, "raw_body") else "" return BoltRequest( body=body, query=req.query_string, headers=req.headers, + defer_parsing=defer_parsing, ) @@ -73,7 +74,7 @@ def handle(self) -> bytes: set_response_status_and_headers(bolt_resp) return (bolt_resp.body or "").encode("utf-8") elif req.method == "POST": - bolt_resp = self.app.dispatch(build_bolt_request()) + bolt_resp = self.app.dispatch(build_bolt_request(defer_parsing=True)) set_response_status_and_headers(bolt_resp) return (bolt_resp.body or "").encode("utf-8") diff --git a/slack_bolt/adapter/django/handler.py b/slack_bolt/adapter/django/handler.py index b01323a10..4c74dd789 100644 --- a/slack_bolt/adapter/django/handler.py +++ b/slack_bolt/adapter/django/handler.py @@ -23,13 +23,14 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: HttpRequest) -> BoltRequest: +def to_bolt_request(req: HttpRequest, defer_parsing: bool = False) -> BoltRequest: raw_body: bytes = req.body body: str = raw_body.decode("utf-8") if raw_body else "" return BoltRequest( body=body, query=req.META["QUERY_STRING"], headers=req.headers, + defer_parsing=defer_parsing, ) @@ -174,7 +175,7 @@ def handle(self, req: HttpRequest) -> HttpResponse: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) return to_django_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req)) + bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) return to_django_response(bolt_resp) return HttpResponse(status=404, content=b"Not Found") diff --git a/slack_bolt/adapter/falcon/async_resource.py b/slack_bolt/adapter/falcon/async_resource.py index 1c22c83a0..9e6b5ee0a 100644 --- a/slack_bolt/adapter/falcon/async_resource.py +++ b/slack_bolt/adapter/falcon/async_resource.py @@ -45,15 +45,16 @@ async def on_get(self, req: Request, resp: Response): resp.text = "The page is not found..." async def on_post(self, req: Request, resp: Response): - bolt_req = await self._to_bolt_request(req) + bolt_req = await self._to_bolt_request(req, defer_parsing=True) bolt_resp = await self.app.async_dispatch(bolt_req) await self._write_response(bolt_resp, resp) - async def _to_bolt_request(self, req: Request) -> AsyncBoltRequest: + async def _to_bolt_request(self, req: Request, defer_parsing: bool = False) -> AsyncBoltRequest: return AsyncBoltRequest( body=(await req.stream.read(req.content_length or 0)).decode("utf-8"), query=req.query_string, headers={k.lower(): v for k, v in req.headers.items()}, + defer_parsing=defer_parsing, ) async def _write_response(self, bolt_resp: BoltResponse, resp: Response): diff --git a/slack_bolt/adapter/falcon/resource.py b/slack_bolt/adapter/falcon/resource.py index f80338755..05c176f46 100644 --- a/slack_bolt/adapter/falcon/resource.py +++ b/slack_bolt/adapter/falcon/resource.py @@ -41,15 +41,16 @@ def on_get(self, req: Request, resp: Response): resp.text = "The page is not found..." def on_post(self, req: Request, resp: Response): - bolt_req = self._to_bolt_request(req) + bolt_req = self._to_bolt_request(req, defer_parsing=True) bolt_resp = self.app.dispatch(bolt_req) self._write_response(bolt_resp, resp) - def _to_bolt_request(self, req: Request) -> BoltRequest: + def _to_bolt_request(self, req: Request, defer_parsing: bool = False) -> BoltRequest: return BoltRequest( body=req.stream.read(req.content_length or 0).decode("utf-8"), query=req.query_string, headers={k.lower(): v for k, v in req.headers.items()}, + defer_parsing=defer_parsing, ) def _write_response(self, bolt_resp: BoltResponse, resp: Response): diff --git a/slack_bolt/adapter/flask/handler.py b/slack_bolt/adapter/flask/handler.py index c88c4d2e5..d3a748fd2 100644 --- a/slack_bolt/adapter/flask/handler.py +++ b/slack_bolt/adapter/flask/handler.py @@ -6,11 +6,12 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: Request) -> BoltRequest: +def to_bolt_request(req: Request, defer_parsing: bool = False) -> BoltRequest: return BoltRequest( body=req.get_data(as_text=True), query=req.query_string.decode("utf-8"), headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) @@ -40,7 +41,7 @@ def handle(self, req: Request) -> Response: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) return to_flask_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req)) + bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) return to_flask_response(bolt_resp) return make_response("Not Found", 404) diff --git a/slack_bolt/adapter/google_cloud_functions/handler.py b/slack_bolt/adapter/google_cloud_functions/handler.py index fdc62a41f..7b2a1bb58 100644 --- a/slack_bolt/adapter/google_cloud_functions/handler.py +++ b/slack_bolt/adapter/google_cloud_functions/handler.py @@ -36,7 +36,7 @@ def handle(self, req: Request) -> Response: bolt_resp = self.app.oauth_flow.handle_installation(bolt_req) return to_flask_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req)) + bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) return to_flask_response(bolt_resp) return make_response("Not Found", 404) diff --git a/slack_bolt/adapter/pyramid/handler.py b/slack_bolt/adapter/pyramid/handler.py index 0dea272ac..9b80c8da3 100644 --- a/slack_bolt/adapter/pyramid/handler.py +++ b/slack_bolt/adapter/pyramid/handler.py @@ -7,7 +7,7 @@ from slack_bolt.oauth import OAuthFlow -def to_bolt_request(request: Request) -> BoltRequest: +def to_bolt_request(request: Request, defer_parsing: bool = False) -> BoltRequest: body: str = "" if request.body is not None: if isinstance(request.body, bytes): @@ -18,6 +18,7 @@ def to_bolt_request(request: Request) -> BoltRequest: body=body, query=request.query_string, headers=request.headers, + defer_parsing=defer_parsing, ) return bolt_req @@ -53,7 +54,7 @@ def handle(self, request: Request) -> Response: bolt_resp = oauth_flow.handle_callback(bolt_req) return to_pyramid_response(bolt_resp) elif request.method == "POST": - bolt_req = _attach_pyramid_request_to_context(to_bolt_request(request), request) + bolt_req = _attach_pyramid_request_to_context(to_bolt_request(request, defer_parsing=True), request) bolt_resp = self.app.dispatch(bolt_req) return to_pyramid_response(bolt_resp) diff --git a/slack_bolt/adapter/sanic/async_handler.py b/slack_bolt/adapter/sanic/async_handler.py index 4b01d1e58..661cac95b 100644 --- a/slack_bolt/adapter/sanic/async_handler.py +++ b/slack_bolt/adapter/sanic/async_handler.py @@ -9,11 +9,16 @@ from slack_bolt.oauth.async_oauth_flow import AsyncOAuthFlow -def to_async_bolt_request(req: Request, addition_context_properties: Optional[Dict[str, Any]] = None) -> AsyncBoltRequest: +def to_async_bolt_request( + req: Request, + addition_context_properties: Optional[Dict[str, Any]] = None, + defer_parsing: bool = False, +) -> AsyncBoltRequest: request = AsyncBoltRequest( body=req.body.decode("utf-8"), query=req.query_string, headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) if addition_context_properties is not None: @@ -67,7 +72,9 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ return to_sanic_response(bolt_resp) elif req.method == "POST": - bolt_resp = await self.app.async_dispatch(to_async_bolt_request(req, addition_context_properties)) + bolt_resp = await self.app.async_dispatch( + to_async_bolt_request(req, addition_context_properties, defer_parsing=True) + ) return to_sanic_response(bolt_resp) return HTTPResponse( diff --git a/slack_bolt/adapter/starlette/async_handler.py b/slack_bolt/adapter/starlette/async_handler.py index 6e3305ac5..d360c4401 100644 --- a/slack_bolt/adapter/starlette/async_handler.py +++ b/slack_bolt/adapter/starlette/async_handler.py @@ -12,11 +12,13 @@ def to_async_bolt_request( req: Request, body: bytes, addition_context_properties: Optional[Dict[str, Any]] = None, + defer_parsing: bool = False, ) -> AsyncBoltRequest: request = AsyncBoltRequest( body=body.decode("utf-8"), query=req.query_params, # type: ignore[arg-type] headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) if addition_context_properties is not None: for k, v in addition_context_properties.items(): @@ -65,7 +67,9 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ ) return to_starlette_response(bolt_resp) elif req.method == "POST": - bolt_resp = await self.app.async_dispatch(to_async_bolt_request(req, body, addition_context_properties)) + bolt_resp = await self.app.async_dispatch( + to_async_bolt_request(req, body, addition_context_properties, defer_parsing=True) + ) return to_starlette_response(bolt_resp) return Response( diff --git a/slack_bolt/adapter/starlette/handler.py b/slack_bolt/adapter/starlette/handler.py index 7321eb86f..0e5666cc4 100644 --- a/slack_bolt/adapter/starlette/handler.py +++ b/slack_bolt/adapter/starlette/handler.py @@ -11,11 +11,13 @@ def to_bolt_request( req: Request, body: bytes, addition_context_properties: Optional[Dict[str, Any]] = None, + defer_parsing: bool = False, ) -> BoltRequest: request = BoltRequest( body=body.decode("utf-8"), query=req.query_params, # type: ignore[arg-type] headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) if addition_context_properties is not None: for k, v in addition_context_properties.items(): @@ -60,7 +62,7 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ bolt_resp = oauth_flow.handle_callback(to_bolt_request(req, body, addition_context_properties)) return to_starlette_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, body, addition_context_properties)) + bolt_resp = self.app.dispatch(to_bolt_request(req, body, addition_context_properties, defer_parsing=True)) return to_starlette_response(bolt_resp) return Response( diff --git a/slack_bolt/adapter/tornado/async_handler.py b/slack_bolt/adapter/tornado/async_handler.py index 1dfc3d374..e01379ee6 100644 --- a/slack_bolt/adapter/tornado/async_handler.py +++ b/slack_bolt/adapter/tornado/async_handler.py @@ -13,7 +13,7 @@ def initialize(self, app: AsyncApp): self.app = app async def post(self): - bolt_resp: BoltResponse = await self.app.async_dispatch(to_async_bolt_request(self.request)) + bolt_resp: BoltResponse = await self.app.async_dispatch(to_async_bolt_request(self.request, defer_parsing=True)) set_response(self, bolt_resp) return @@ -36,9 +36,10 @@ async def get(self): self.set_status(404) -def to_async_bolt_request(req: HTTPServerRequest) -> AsyncBoltRequest: +def to_async_bolt_request(req: HTTPServerRequest, defer_parsing: bool = False) -> AsyncBoltRequest: return AsyncBoltRequest( body=req.body.decode("utf-8") if req.body else "", query=req.query, headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/tornado/handler.py b/slack_bolt/adapter/tornado/handler.py index 088c9665e..e8b668c7c 100644 --- a/slack_bolt/adapter/tornado/handler.py +++ b/slack_bolt/adapter/tornado/handler.py @@ -14,7 +14,7 @@ def initialize(self, app: App): self.app = app def post(self): - bolt_resp: BoltResponse = self.app.dispatch(to_bolt_request(self.request)) + bolt_resp: BoltResponse = self.app.dispatch(to_bolt_request(self.request, defer_parsing=True)) set_response(self, bolt_resp) return @@ -37,11 +37,12 @@ def get(self): self.set_status(404) -def to_bolt_request(req: HTTPServerRequest) -> BoltRequest: +def to_bolt_request(req: HTTPServerRequest, defer_parsing: bool = False) -> BoltRequest: return BoltRequest( body=req.body.decode("utf-8") if req.body else "", query=req.query, headers=req.headers, # type: ignore[arg-type] + defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/wsgi/handler.py b/slack_bolt/adapter/wsgi/handler.py index b13e64530..c389e1045 100644 --- a/slack_bolt/adapter/wsgi/handler.py +++ b/slack_bolt/adapter/wsgi/handler.py @@ -41,7 +41,12 @@ def __init__(self, app: App, path: str = "/slack/events"): def dispatch(self, request: WsgiHttpRequest) -> BoltResponse: return self.app.dispatch( - BoltRequest(body=request.get_body(), query=request.query_string, headers=request.get_headers()) + BoltRequest( + body=request.get_body(), + query=request.query_string, + headers=request.get_headers(), + defer_parsing=True, + ) ) def handle_installation(self, request: WsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/app/app.py b/slack_bolt/app/app.py index db48330fe..775abbfce 100644 --- a/slack_bolt/app/app.py +++ b/slack_bolt/app/app.py @@ -1573,6 +1573,7 @@ def do_POST(self): query=query, # email.message.Message's mapping interface is dict compatible headers=self.headers, + defer_parsing=True, ) bolt_resp: BoltResponse = _bolt_app.dispatch(bolt_req) self._send_bolt_response(bolt_resp) diff --git a/slack_bolt/app/async_server.py b/slack_bolt/app/async_server.py index 9511a5f7b..84a899cfb 100644 --- a/slack_bolt/app/async_server.py +++ b/slack_bolt/app/async_server.py @@ -75,7 +75,7 @@ async def handle_post_requests(self, request: web.Request) -> web.Response: if self.path != request.path: return web.Response(status=404) - bolt_req = await to_bolt_request(request) + bolt_req = await to_bolt_request(request, defer_parsing=True) bolt_resp: BoltResponse = await self.bolt_app.async_dispatch(bolt_req) return await to_aiohttp_response(bolt_resp) From 286c38f0c20ccdd238213629da4e9bb49d74520a Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 11:07:12 -0500 Subject: [PATCH 05/10] fix(request_verification): reject malformed signature headers with 401 SignatureVerifier.is_valid raises on a non-numeric timestamp or a non-ASCII signature, which turned unsigned junk into a 500. Co-Authored-By: Claude --- .../async_request_verification.py | 2 +- .../request_verification/request_verification.py | 9 ++++++++- .../request_verification/test_request_verification.py | 10 ++++++++++ .../request_verification/test_request_verification.py | 11 +++++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/slack_bolt/middleware/request_verification/async_request_verification.py b/slack_bolt/middleware/request_verification/async_request_verification.py index 99b86a63c..06ca7647a 100644 --- a/slack_bolt/middleware/request_verification/async_request_verification.py +++ b/slack_bolt/middleware/request_verification/async_request_verification.py @@ -30,7 +30,7 @@ async def async_process( body = req.raw_body timestamp = req.headers.get("x-slack-request-timestamp", ["0"])[0] signature = req.headers.get("x-slack-signature", [""])[0] - if self.verifier.is_valid(body, timestamp, signature): + if self._is_valid_signature(body, timestamp, signature): return await next() else: self._debug_log_error(signature, timestamp, body) diff --git a/slack_bolt/middleware/request_verification/request_verification.py b/slack_bolt/middleware/request_verification/request_verification.py index 1425f7baf..26b082243 100644 --- a/slack_bolt/middleware/request_verification/request_verification.py +++ b/slack_bolt/middleware/request_verification/request_verification.py @@ -48,7 +48,7 @@ def process( body = req.raw_body timestamp = req.headers.get("x-slack-request-timestamp", ["0"])[0] signature = req.headers.get("x-slack-signature", [""])[0] - if self.verifier.is_valid(body, timestamp, signature): + if self._is_valid_signature(body, timestamp, signature): return next() else: self._debug_log_error(signature, timestamp, body) @@ -56,6 +56,13 @@ def process( # ----------------------------------------- + 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" diff --git a/tests/slack_bolt/middleware/request_verification/test_request_verification.py b/tests/slack_bolt/middleware/request_verification/test_request_verification.py index 53af43bf3..10e973081 100644 --- a/tests/slack_bolt/middleware/request_verification/test_request_verification.py +++ b/tests/slack_bolt/middleware/request_verification/test_request_verification.py @@ -79,3 +79,13 @@ def test_http_request_with_empty_signing_secret_raises(self): resp = BoltResponse(status=404) with pytest.raises(ValueError): middleware.process(req=req, resp=resp, next=next) + + def test_malformed_headers(self): + middleware = RequestVerification(signing_secret=self.signing_secret) + for headers in [ + {"x-slack-request-timestamp": ["abc"], "x-slack-signature": ["v0=invalid"]}, + {"x-slack-request-timestamp": [str(int(time()))], "x-slack-signature": ["v0=ñ"]}, + ]: + req = BoltRequest(body="payload={}", headers=headers) + resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) + assert resp.status == 401 diff --git a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py index 126b04f94..3d80a5b30 100644 --- a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py +++ b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py @@ -86,3 +86,14 @@ async def test_http_request_with_empty_signing_secret_raises(self): resp = BoltResponse(status=404) with pytest.raises(ValueError): await middleware.async_process(req=req, resp=resp, next=next) + + @pytest.mark.asyncio + async def test_malformed_headers(self): + middleware = AsyncRequestVerification(signing_secret=self.signing_secret) + for headers in [ + {"x-slack-request-timestamp": ["abc"], "x-slack-signature": ["v0=invalid"]}, + {"x-slack-request-timestamp": [str(int(time()))], "x-slack-signature": ["v0=ñ"]}, + ]: + req = AsyncBoltRequest(body="payload={}", headers=headers) + resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) + assert resp.status == 401 From eb5e885c1ab3a0477c3e0f7cb9caf1badc30704a Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 11:07:12 -0500 Subject: [PATCH 06/10] docs: show defer_parsing in the custom adapters guide Co-Authored-By: Claude --- docs/english/concepts/custom-adapters.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/english/concepts/custom-adapters.md b/docs/english/concepts/custom-adapters.md index 21f7f33e0..b2b3e02a4 100644 --- a/docs/english/concepts/custom-adapters.md +++ b/docs/english/concepts/custom-adapters.md @@ -5,7 +5,7 @@ - `__init__(app: App)`: Constructor that accepts and stores an instance of the Bolt `App`. - `handle(req: Request)`: Function (typically named `handle()`) that receives incoming Slack requests, parses them to conform to an instance of [`BoltRequest`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/request/request.py), then dispatches them to the stored Bolt app. -`BoltRequest` instantiation accepts four parameters: +`BoltRequest` instantiation accepts these parameters: | Parameter | Description | Required? | |-----------|-------------|-----------| @@ -13,6 +13,7 @@ | `query: any` | The query string data | No | | `headers: Dict[str, Union[str, List[str]]]` | Request headers | No | | `context: BoltContext` | Any context for the request | No | +| `defer_parsing: bool` | Waits to parse the body until after the request signature is verified. Set it to `True` when you pass the request to `app.dispatch()` | No | Your adapter will return [an instance of `BoltResponse`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/response/response.py) from the Bolt app. @@ -38,6 +39,8 @@ def to_bolt_request(req: Request) -> BoltRequest: body=req.get_data(as_text=True), query=req.query_string.decode("utf-8"), headers=req.headers, + # Leaves the body unparsed until Bolt verifies the request came from Slack + defer_parsing=True, ) # Takes in a BoltResponse and converts it to a standard Flask response From 3caef8b9ff64622c004599d51eb74a4a6c01e2a9 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 13:56:42 -0500 Subject: [PATCH 07/10] fix: always parse request bodies in RequestParsing BoltRequest and AsyncBoltRequest no longer parse the body or build the context at construction. The RequestParsing middleware, which runs right after RequestVerification, is now the only parser, so every request that reaches dispatch is protected and the defer_parsing opt-in, its adapter plumbing, and its docs are gone. A request that is read without being dispatched now has an empty body; tests that do so run RequestParsing through a small helper. Co-Authored-By: Claude --- docs/english/concepts/custom-adapters.md | 5 +- slack_bolt/adapter/aiohttp/__init__.py | 3 +- slack_bolt/adapter/asgi/aiohttp/__init__.py | 7 +- slack_bolt/adapter/asgi/builtin/__init__.py | 7 +- .../adapter/aws_lambda/chalice_handler.py | 7 +- slack_bolt/adapter/aws_lambda/handler.py | 7 +- slack_bolt/adapter/bottle/handler.py | 5 +- slack_bolt/adapter/cherrypy/handler.py | 5 +- slack_bolt/adapter/django/handler.py | 5 +- slack_bolt/adapter/falcon/async_resource.py | 5 +- slack_bolt/adapter/falcon/resource.py | 5 +- slack_bolt/adapter/flask/handler.py | 5 +- .../adapter/google_cloud_functions/handler.py | 2 +- slack_bolt/adapter/pyramid/handler.py | 5 +- slack_bolt/adapter/sanic/async_handler.py | 11 +-- slack_bolt/adapter/starlette/async_handler.py | 6 +- slack_bolt/adapter/starlette/handler.py | 4 +- slack_bolt/adapter/tornado/async_handler.py | 5 +- slack_bolt/adapter/tornado/handler.py | 5 +- slack_bolt/adapter/wsgi/handler.py | 7 +- slack_bolt/app/app.py | 1 - slack_bolt/app/async_server.py | 2 +- .../request_parsing/async_request_parsing.py | 14 ++- .../request_parsing/request_parsing.py | 13 ++- slack_bolt/request/async_request.py | 35 ++----- slack_bolt/request/request.py | 35 ++----- tests/async_utils.py | 11 +++ tests/scenario_tests/test_request_parsing.py | 98 ++++++++++-------- .../test_request_parsing.py | 99 +++++++++++++------ .../listener_matcher/test_builtins.py | 13 +-- .../test_custom_listener_matcher.py | 5 +- .../test_attaching_conversation_kwargs.py | 19 ++-- tests/slack_bolt/request/test_request.py | 7 +- .../test_async_custom_listener_matcher.py | 5 +- ...est_async_attaching_conversation_kwargs.py | 19 ++-- tests/utils.py | 9 ++ 36 files changed, 255 insertions(+), 241 deletions(-) create mode 100644 tests/async_utils.py diff --git a/docs/english/concepts/custom-adapters.md b/docs/english/concepts/custom-adapters.md index b2b3e02a4..21f7f33e0 100644 --- a/docs/english/concepts/custom-adapters.md +++ b/docs/english/concepts/custom-adapters.md @@ -5,7 +5,7 @@ - `__init__(app: App)`: Constructor that accepts and stores an instance of the Bolt `App`. - `handle(req: Request)`: Function (typically named `handle()`) that receives incoming Slack requests, parses them to conform to an instance of [`BoltRequest`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/request/request.py), then dispatches them to the stored Bolt app. -`BoltRequest` instantiation accepts these parameters: +`BoltRequest` instantiation accepts four parameters: | Parameter | Description | Required? | |-----------|-------------|-----------| @@ -13,7 +13,6 @@ | `query: any` | The query string data | No | | `headers: Dict[str, Union[str, List[str]]]` | Request headers | No | | `context: BoltContext` | Any context for the request | No | -| `defer_parsing: bool` | Waits to parse the body until after the request signature is verified. Set it to `True` when you pass the request to `app.dispatch()` | No | Your adapter will return [an instance of `BoltResponse`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/response/response.py) from the Bolt app. @@ -39,8 +38,6 @@ def to_bolt_request(req: Request) -> BoltRequest: body=req.get_data(as_text=True), query=req.query_string.decode("utf-8"), headers=req.headers, - # Leaves the body unparsed until Bolt verifies the request came from Slack - defer_parsing=True, ) # Takes in a BoltResponse and converts it to a standard Flask response diff --git a/slack_bolt/adapter/aiohttp/__init__.py b/slack_bolt/adapter/aiohttp/__init__.py index 52d0f849c..9267f2515 100644 --- a/slack_bolt/adapter/aiohttp/__init__.py +++ b/slack_bolt/adapter/aiohttp/__init__.py @@ -6,12 +6,11 @@ from slack_bolt.response import BoltResponse -async def to_bolt_request(request: web.Request, defer_parsing: bool = False) -> AsyncBoltRequest: +async def to_bolt_request(request: web.Request) -> AsyncBoltRequest: return AsyncBoltRequest( body=await request.text(), query=request.query_string, headers=request.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/asgi/aiohttp/__init__.py b/slack_bolt/adapter/asgi/aiohttp/__init__.py index a35aac76e..796098537 100644 --- a/slack_bolt/adapter/asgi/aiohttp/__init__.py +++ b/slack_bolt/adapter/asgi/aiohttp/__init__.py @@ -36,12 +36,7 @@ def __init__(self, app: AsyncApp, path: str = "/slack/events"): async def dispatch(self, request: AsgiHttpRequest) -> BoltResponse: return await self.app.async_dispatch( - AsyncBoltRequest( - body=await request.get_raw_body(), - query=request.query_string, - headers=request.get_headers(), - defer_parsing=True, - ) + AsyncBoltRequest(body=await request.get_raw_body(), query=request.query_string, headers=request.get_headers()) ) async def handle_installation(self, request: AsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/adapter/asgi/builtin/__init__.py b/slack_bolt/adapter/asgi/builtin/__init__.py index 1c7e7b595..b05451f34 100644 --- a/slack_bolt/adapter/asgi/builtin/__init__.py +++ b/slack_bolt/adapter/asgi/builtin/__init__.py @@ -35,12 +35,7 @@ def __init__(self, app: App, path: str = "/slack/events"): async def dispatch(self, request: AsgiHttpRequest) -> BoltResponse: return self.app.dispatch( - BoltRequest( - body=await request.get_raw_body(), - query=request.query_string, - headers=request.get_headers(), - defer_parsing=True, - ) + BoltRequest(body=await request.get_raw_body(), query=request.query_string, headers=request.get_headers()) ) async def handle_installation(self, request: AsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/adapter/aws_lambda/chalice_handler.py b/slack_bolt/adapter/aws_lambda/chalice_handler.py index 2f8a13a0a..00200b6da 100644 --- a/slack_bolt/adapter/aws_lambda/chalice_handler.py +++ b/slack_bolt/adapter/aws_lambda/chalice_handler.py @@ -72,7 +72,7 @@ def handle(self, request: Request): bolt_resp = oauth_flow.handle_installation(bolt_req) return to_chalice_response(bolt_resp) elif method == "POST": - bolt_req = to_bolt_request(request, body, defer_parsing=True) + bolt_req = to_bolt_request(request, body) # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html aws_lambda_function_name = self.chalice.lambda_context.function_name bolt_req.context["aws_lambda_function_name"] = aws_lambda_function_name @@ -81,7 +81,7 @@ def handle(self, request: Request): aws_response = to_chalice_response(bolt_resp) return aws_response elif method == "NONE": - bolt_req = to_bolt_request(request, body, defer_parsing=True) + bolt_req = to_bolt_request(request, body) bolt_resp = self.app.dispatch(bolt_req) aws_response = to_chalice_response(bolt_resp) return aws_response @@ -89,12 +89,11 @@ def handle(self, request: Request): return not_found() -def to_bolt_request(request: Request, body: str, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(request: Request, body: str) -> BoltRequest: return BoltRequest( body=body, query=request.query_params, # type: ignore[arg-type] headers=request.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/aws_lambda/handler.py b/slack_bolt/adapter/aws_lambda/handler.py index ce5c8f43e..088055af1 100644 --- a/slack_bolt/adapter/aws_lambda/handler.py +++ b/slack_bolt/adapter/aws_lambda/handler.py @@ -52,7 +52,7 @@ def handle(self, event, context): bolt_resp = oauth_flow.handle_installation(bolt_req) return to_aws_response(bolt_resp) elif method == "POST": - bolt_req = to_bolt_request(event, defer_parsing=True) + bolt_req = to_bolt_request(event) # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html aws_lambda_function_name = context.function_name bolt_req.context["aws_lambda_function_name"] = aws_lambda_function_name @@ -64,7 +64,7 @@ def handle(self, event, context): aws_response = to_aws_response(bolt_resp) return aws_response elif method == "NONE": - bolt_req = to_bolt_request(event, defer_parsing=True) + bolt_req = to_bolt_request(event) bolt_resp = self.app.dispatch(bolt_req) aws_response = to_aws_response(bolt_resp) return aws_response @@ -72,7 +72,7 @@ def handle(self, event, context): return not_found() -def to_bolt_request(event, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(event) -> BoltRequest: body = event.get("body") or "" if event.get("isBase64Encoded") is True and body: body = base64.b64decode(body).decode("utf-8") @@ -90,7 +90,6 @@ def to_bolt_request(event, defer_parsing: bool = False) -> BoltRequest: body=body, query=event.get("queryStringParameters") or {}, headers=headers, - defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/bottle/handler.py b/slack_bolt/adapter/bottle/handler.py index f0276054d..d99e24afa 100644 --- a/slack_bolt/adapter/bottle/handler.py +++ b/slack_bolt/adapter/bottle/handler.py @@ -6,7 +6,7 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: Request, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(req: Request) -> BoltRequest: body = req.body.read() if isinstance(body, bytes): body = body.decode("utf-8") @@ -14,7 +14,6 @@ def to_bolt_request(req: Request, defer_parsing: bool = False) -> BoltRequest: body=body, query=req.query_string, headers=req.headers, - defer_parsing=defer_parsing, ) @@ -42,7 +41,7 @@ def handle(self, req: Request, resp: Response) -> str: set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) + bolt_resp = self.app.dispatch(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" diff --git a/slack_bolt/adapter/cherrypy/handler.py b/slack_bolt/adapter/cherrypy/handler.py index 8e784a584..f3d714cc6 100644 --- a/slack_bolt/adapter/cherrypy/handler.py +++ b/slack_bolt/adapter/cherrypy/handler.py @@ -8,14 +8,13 @@ from slack_bolt.response import BoltResponse -def build_bolt_request(defer_parsing: bool = False) -> BoltRequest: +def build_bolt_request() -> BoltRequest: req = cherrypy.request body = req.raw_body if hasattr(req, "raw_body") else "" return BoltRequest( body=body, query=req.query_string, headers=req.headers, - defer_parsing=defer_parsing, ) @@ -74,7 +73,7 @@ def handle(self) -> bytes: set_response_status_and_headers(bolt_resp) return (bolt_resp.body or "").encode("utf-8") elif req.method == "POST": - bolt_resp = self.app.dispatch(build_bolt_request(defer_parsing=True)) + bolt_resp = self.app.dispatch(build_bolt_request()) set_response_status_and_headers(bolt_resp) return (bolt_resp.body or "").encode("utf-8") diff --git a/slack_bolt/adapter/django/handler.py b/slack_bolt/adapter/django/handler.py index 4c74dd789..b01323a10 100644 --- a/slack_bolt/adapter/django/handler.py +++ b/slack_bolt/adapter/django/handler.py @@ -23,14 +23,13 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: HttpRequest, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(req: HttpRequest) -> BoltRequest: raw_body: bytes = req.body body: str = raw_body.decode("utf-8") if raw_body else "" return BoltRequest( body=body, query=req.META["QUERY_STRING"], headers=req.headers, - defer_parsing=defer_parsing, ) @@ -175,7 +174,7 @@ def handle(self, req: HttpRequest) -> HttpResponse: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) return to_django_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) + bolt_resp = self.app.dispatch(to_bolt_request(req)) return to_django_response(bolt_resp) return HttpResponse(status=404, content=b"Not Found") diff --git a/slack_bolt/adapter/falcon/async_resource.py b/slack_bolt/adapter/falcon/async_resource.py index 9e6b5ee0a..1c22c83a0 100644 --- a/slack_bolt/adapter/falcon/async_resource.py +++ b/slack_bolt/adapter/falcon/async_resource.py @@ -45,16 +45,15 @@ async def on_get(self, req: Request, resp: Response): resp.text = "The page is not found..." async def on_post(self, req: Request, resp: Response): - bolt_req = await self._to_bolt_request(req, defer_parsing=True) + bolt_req = await self._to_bolt_request(req) bolt_resp = await self.app.async_dispatch(bolt_req) await self._write_response(bolt_resp, resp) - async def _to_bolt_request(self, req: Request, defer_parsing: bool = False) -> AsyncBoltRequest: + async def _to_bolt_request(self, req: Request) -> AsyncBoltRequest: return AsyncBoltRequest( body=(await req.stream.read(req.content_length or 0)).decode("utf-8"), query=req.query_string, headers={k.lower(): v for k, v in req.headers.items()}, - defer_parsing=defer_parsing, ) async def _write_response(self, bolt_resp: BoltResponse, resp: Response): diff --git a/slack_bolt/adapter/falcon/resource.py b/slack_bolt/adapter/falcon/resource.py index 05c176f46..f80338755 100644 --- a/slack_bolt/adapter/falcon/resource.py +++ b/slack_bolt/adapter/falcon/resource.py @@ -41,16 +41,15 @@ def on_get(self, req: Request, resp: Response): resp.text = "The page is not found..." def on_post(self, req: Request, resp: Response): - bolt_req = self._to_bolt_request(req, defer_parsing=True) + bolt_req = self._to_bolt_request(req) bolt_resp = self.app.dispatch(bolt_req) self._write_response(bolt_resp, resp) - def _to_bolt_request(self, req: Request, defer_parsing: bool = False) -> BoltRequest: + def _to_bolt_request(self, req: Request) -> BoltRequest: return BoltRequest( body=req.stream.read(req.content_length or 0).decode("utf-8"), query=req.query_string, headers={k.lower(): v for k, v in req.headers.items()}, - defer_parsing=defer_parsing, ) def _write_response(self, bolt_resp: BoltResponse, resp: Response): diff --git a/slack_bolt/adapter/flask/handler.py b/slack_bolt/adapter/flask/handler.py index d3a748fd2..c88c4d2e5 100644 --- a/slack_bolt/adapter/flask/handler.py +++ b/slack_bolt/adapter/flask/handler.py @@ -6,12 +6,11 @@ from slack_bolt.response import BoltResponse -def to_bolt_request(req: Request, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(req: Request) -> BoltRequest: return BoltRequest( body=req.get_data(as_text=True), query=req.query_string.decode("utf-8"), headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) @@ -41,7 +40,7 @@ def handle(self, req: Request) -> Response: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) return to_flask_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) + bolt_resp = self.app.dispatch(to_bolt_request(req)) return to_flask_response(bolt_resp) return make_response("Not Found", 404) diff --git a/slack_bolt/adapter/google_cloud_functions/handler.py b/slack_bolt/adapter/google_cloud_functions/handler.py index 7b2a1bb58..fdc62a41f 100644 --- a/slack_bolt/adapter/google_cloud_functions/handler.py +++ b/slack_bolt/adapter/google_cloud_functions/handler.py @@ -36,7 +36,7 @@ def handle(self, req: Request) -> Response: bolt_resp = self.app.oauth_flow.handle_installation(bolt_req) return to_flask_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, defer_parsing=True)) + bolt_resp = self.app.dispatch(to_bolt_request(req)) return to_flask_response(bolt_resp) return make_response("Not Found", 404) diff --git a/slack_bolt/adapter/pyramid/handler.py b/slack_bolt/adapter/pyramid/handler.py index 9b80c8da3..0dea272ac 100644 --- a/slack_bolt/adapter/pyramid/handler.py +++ b/slack_bolt/adapter/pyramid/handler.py @@ -7,7 +7,7 @@ from slack_bolt.oauth import OAuthFlow -def to_bolt_request(request: Request, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(request: Request) -> BoltRequest: body: str = "" if request.body is not None: if isinstance(request.body, bytes): @@ -18,7 +18,6 @@ def to_bolt_request(request: Request, defer_parsing: bool = False) -> BoltReques body=body, query=request.query_string, headers=request.headers, - defer_parsing=defer_parsing, ) return bolt_req @@ -54,7 +53,7 @@ def handle(self, request: Request) -> Response: bolt_resp = oauth_flow.handle_callback(bolt_req) return to_pyramid_response(bolt_resp) elif request.method == "POST": - bolt_req = _attach_pyramid_request_to_context(to_bolt_request(request, defer_parsing=True), request) + bolt_req = _attach_pyramid_request_to_context(to_bolt_request(request), request) bolt_resp = self.app.dispatch(bolt_req) return to_pyramid_response(bolt_resp) diff --git a/slack_bolt/adapter/sanic/async_handler.py b/slack_bolt/adapter/sanic/async_handler.py index 661cac95b..4b01d1e58 100644 --- a/slack_bolt/adapter/sanic/async_handler.py +++ b/slack_bolt/adapter/sanic/async_handler.py @@ -9,16 +9,11 @@ from slack_bolt.oauth.async_oauth_flow import AsyncOAuthFlow -def to_async_bolt_request( - req: Request, - addition_context_properties: Optional[Dict[str, Any]] = None, - defer_parsing: bool = False, -) -> AsyncBoltRequest: +def to_async_bolt_request(req: Request, addition_context_properties: Optional[Dict[str, Any]] = None) -> AsyncBoltRequest: request = AsyncBoltRequest( body=req.body.decode("utf-8"), query=req.query_string, headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) if addition_context_properties is not None: @@ -72,9 +67,7 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ return to_sanic_response(bolt_resp) elif req.method == "POST": - bolt_resp = await self.app.async_dispatch( - to_async_bolt_request(req, addition_context_properties, defer_parsing=True) - ) + bolt_resp = await self.app.async_dispatch(to_async_bolt_request(req, addition_context_properties)) return to_sanic_response(bolt_resp) return HTTPResponse( diff --git a/slack_bolt/adapter/starlette/async_handler.py b/slack_bolt/adapter/starlette/async_handler.py index d360c4401..6e3305ac5 100644 --- a/slack_bolt/adapter/starlette/async_handler.py +++ b/slack_bolt/adapter/starlette/async_handler.py @@ -12,13 +12,11 @@ def to_async_bolt_request( req: Request, body: bytes, addition_context_properties: Optional[Dict[str, Any]] = None, - defer_parsing: bool = False, ) -> AsyncBoltRequest: request = AsyncBoltRequest( body=body.decode("utf-8"), query=req.query_params, # type: ignore[arg-type] headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) if addition_context_properties is not None: for k, v in addition_context_properties.items(): @@ -67,9 +65,7 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ ) return to_starlette_response(bolt_resp) elif req.method == "POST": - bolt_resp = await self.app.async_dispatch( - to_async_bolt_request(req, body, addition_context_properties, defer_parsing=True) - ) + bolt_resp = await self.app.async_dispatch(to_async_bolt_request(req, body, addition_context_properties)) return to_starlette_response(bolt_resp) return Response( diff --git a/slack_bolt/adapter/starlette/handler.py b/slack_bolt/adapter/starlette/handler.py index 0e5666cc4..7321eb86f 100644 --- a/slack_bolt/adapter/starlette/handler.py +++ b/slack_bolt/adapter/starlette/handler.py @@ -11,13 +11,11 @@ def to_bolt_request( req: Request, body: bytes, addition_context_properties: Optional[Dict[str, Any]] = None, - defer_parsing: bool = False, ) -> BoltRequest: request = BoltRequest( body=body.decode("utf-8"), query=req.query_params, # type: ignore[arg-type] headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) if addition_context_properties is not None: for k, v in addition_context_properties.items(): @@ -62,7 +60,7 @@ async def handle(self, req: Request, addition_context_properties: Optional[Dict[ bolt_resp = oauth_flow.handle_callback(to_bolt_request(req, body, addition_context_properties)) return to_starlette_response(bolt_resp) elif req.method == "POST": - bolt_resp = self.app.dispatch(to_bolt_request(req, body, addition_context_properties, defer_parsing=True)) + bolt_resp = self.app.dispatch(to_bolt_request(req, body, addition_context_properties)) return to_starlette_response(bolt_resp) return Response( diff --git a/slack_bolt/adapter/tornado/async_handler.py b/slack_bolt/adapter/tornado/async_handler.py index e01379ee6..1dfc3d374 100644 --- a/slack_bolt/adapter/tornado/async_handler.py +++ b/slack_bolt/adapter/tornado/async_handler.py @@ -13,7 +13,7 @@ def initialize(self, app: AsyncApp): self.app = app async def post(self): - bolt_resp: BoltResponse = await self.app.async_dispatch(to_async_bolt_request(self.request, defer_parsing=True)) + bolt_resp: BoltResponse = await self.app.async_dispatch(to_async_bolt_request(self.request)) set_response(self, bolt_resp) return @@ -36,10 +36,9 @@ async def get(self): self.set_status(404) -def to_async_bolt_request(req: HTTPServerRequest, defer_parsing: bool = False) -> AsyncBoltRequest: +def to_async_bolt_request(req: HTTPServerRequest) -> AsyncBoltRequest: return AsyncBoltRequest( body=req.body.decode("utf-8") if req.body else "", query=req.query, headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/tornado/handler.py b/slack_bolt/adapter/tornado/handler.py index e8b668c7c..088c9665e 100644 --- a/slack_bolt/adapter/tornado/handler.py +++ b/slack_bolt/adapter/tornado/handler.py @@ -14,7 +14,7 @@ def initialize(self, app: App): self.app = app def post(self): - bolt_resp: BoltResponse = self.app.dispatch(to_bolt_request(self.request, defer_parsing=True)) + bolt_resp: BoltResponse = self.app.dispatch(to_bolt_request(self.request)) set_response(self, bolt_resp) return @@ -37,12 +37,11 @@ def get(self): self.set_status(404) -def to_bolt_request(req: HTTPServerRequest, defer_parsing: bool = False) -> BoltRequest: +def to_bolt_request(req: HTTPServerRequest) -> BoltRequest: return BoltRequest( body=req.body.decode("utf-8") if req.body else "", query=req.query, headers=req.headers, # type: ignore[arg-type] - defer_parsing=defer_parsing, ) diff --git a/slack_bolt/adapter/wsgi/handler.py b/slack_bolt/adapter/wsgi/handler.py index c389e1045..b13e64530 100644 --- a/slack_bolt/adapter/wsgi/handler.py +++ b/slack_bolt/adapter/wsgi/handler.py @@ -41,12 +41,7 @@ def __init__(self, app: App, path: str = "/slack/events"): def dispatch(self, request: WsgiHttpRequest) -> BoltResponse: return self.app.dispatch( - BoltRequest( - body=request.get_body(), - query=request.query_string, - headers=request.get_headers(), - defer_parsing=True, - ) + BoltRequest(body=request.get_body(), query=request.query_string, headers=request.get_headers()) ) def handle_installation(self, request: WsgiHttpRequest) -> BoltResponse: diff --git a/slack_bolt/app/app.py b/slack_bolt/app/app.py index 775abbfce..db48330fe 100644 --- a/slack_bolt/app/app.py +++ b/slack_bolt/app/app.py @@ -1573,7 +1573,6 @@ def do_POST(self): query=query, # email.message.Message's mapping interface is dict compatible headers=self.headers, - defer_parsing=True, ) bolt_resp: BoltResponse = _bolt_app.dispatch(bolt_req) self._send_bolt_response(bolt_resp) diff --git a/slack_bolt/app/async_server.py b/slack_bolt/app/async_server.py index 84a899cfb..9511a5f7b 100644 --- a/slack_bolt/app/async_server.py +++ b/slack_bolt/app/async_server.py @@ -75,7 +75,7 @@ async def handle_post_requests(self, request: web.Request) -> web.Response: if self.path != request.path: return web.Response(status=404) - bolt_req = await to_bolt_request(request, defer_parsing=True) + bolt_req = await to_bolt_request(request) bolt_resp: BoltResponse = await self.bolt_app.async_dispatch(bolt_req) return await to_aiohttp_response(bolt_resp) diff --git a/slack_bolt/middleware/request_parsing/async_request_parsing.py b/slack_bolt/middleware/request_parsing/async_request_parsing.py index 5f9a8ce49..dbdf5a8ea 100644 --- a/slack_bolt/middleware/request_parsing/async_request_parsing.py +++ b/slack_bolt/middleware/request_parsing/async_request_parsing.py @@ -2,14 +2,17 @@ from slack_bolt.middleware.async_middleware import AsyncMiddleware from slack_bolt.middleware.request_parsing.request_parsing import attach_team_id_to_client +from slack_bolt.request.async_internals import build_async_context from slack_bolt.request.async_request import AsyncBoltRequest +from slack_bolt.request.internals import parse_body from slack_bolt.response import BoltResponse class AsyncRequestParsing(AsyncMiddleware): - """Parses the body and builds the context of a request created with `defer_parsing=True`. + """Parses the request body and builds the context from it. Runs right after `AsyncRequestVerification`, so unsigned payloads are never parsed. + Values already in the context take precedence over the ones in the body. """ async def async_process( @@ -19,7 +22,10 @@ async def async_process( resp: BoltResponse, next: Callable[[], Awaitable[BoltResponse]], ) -> BoltResponse: - if req.defer_parsing: - req.complete_deferred_parsing() - attach_team_id_to_client(req.context) + if req.raw_body: + req.body = parse_body(req.raw_body, req.content_type) + set_before_parsing = dict(req.context) + build_async_context(req.context, req.body) + req.context.update(set_before_parsing) + attach_team_id_to_client(req.context) return await next() diff --git a/slack_bolt/middleware/request_parsing/request_parsing.py b/slack_bolt/middleware/request_parsing/request_parsing.py index 0214edd83..5177bfc1e 100644 --- a/slack_bolt/middleware/request_parsing/request_parsing.py +++ b/slack_bolt/middleware/request_parsing/request_parsing.py @@ -3,13 +3,15 @@ from slack_bolt.context.base_context import BaseContext from slack_bolt.middleware.middleware import Middleware from slack_bolt.request import BoltRequest +from slack_bolt.request.internals import build_context, parse_body from slack_bolt.response import BoltResponse class RequestParsing(Middleware): - """Parses the body and builds the context of a request created with `defer_parsing=True`. + """Parses the request body and builds the context from it. Runs right after `RequestVerification`, so unsigned payloads are never parsed. + Values already in the context take precedence over the ones in the body. """ def process( @@ -19,9 +21,12 @@ def process( resp: BoltResponse, next: Callable[[], BoltResponse], ) -> BoltResponse: - if req.defer_parsing: - req.complete_deferred_parsing() - attach_team_id_to_client(req.context) + if req.raw_body: + req.body = parse_body(req.raw_body, req.content_type) + set_before_parsing = dict(req.context) + build_context(req.context, req.body) + req.context.update(set_before_parsing) + attach_team_id_to_client(req.context) return next() diff --git a/slack_bolt/request/async_request.py b/slack_bolt/request/async_request.py index c6a477c90..0f8732a5d 100644 --- a/slack_bolt/request/async_request.py +++ b/slack_bolt/request/async_request.py @@ -2,14 +2,13 @@ from slack_bolt.context.async_context import AsyncBoltContext from slack_bolt.error import BoltError -from slack_bolt.request.async_internals import build_async_context from slack_bolt.request.internals import ( parse_query, - parse_body, build_normalized_headers, extract_content_type, error_message_raw_body_required_in_http_mode, ) +from slack_bolt.util.utils import create_copy class AsyncBoltRequest: @@ -22,7 +21,6 @@ class AsyncBoltRequest: lazy_only: bool lazy_function_name: Optional[str] mode: str # either "http" or "socket_mode" - defer_parsing: bool def __init__( self, @@ -32,19 +30,18 @@ def __init__( headers: Optional[Dict[str, Union[str, Sequence[str]]]] = None, context: Optional[Dict[str, Any]] = None, mode: str = "http", # either "http" or "socket_mode" - defer_parsing: bool = False, ): """Request to a Bolt app. + The body is parsed and the context is built from it when the app dispatches the request, + right after request verification, so unsigned payloads are never parsed. + Args: body: The raw request body (only plain text is supported for "http" mode) query: The query string data in any data format. headers: The request headers. context: The context in this request. mode: The mode used for this request. (either "http" or "socket_mode") - defer_parsing: True to leave `body` empty and skip building `context` from it until - the built-in `RequestParsing` middleware runs after `RequestVerification`. - Adapters set this so unsigned payloads are never parsed. """ if mode == "http": # HTTP Mode @@ -66,36 +63,18 @@ def __init__( self.body = body if isinstance(body, dict) else {} self.context = AsyncBoltContext(context if context else {}) - self.defer_parsing = defer_parsing - if not defer_parsing: - self._parse_body_and_build_context() self.lazy_only = bool(self.headers.get("x-slack-bolt-lazy-only", [False])[0]) self.lazy_function_name = self.headers.get("x-slack-bolt-lazy-function-name", [None])[0] self.mode = mode - def complete_deferred_parsing(self) -> None: - """Parses the body and builds the context of a request created with `defer_parsing=True`. - - Context values set after the request was created take precedence over the ones in the body. - """ - if not self.defer_parsing: - return - set_after_creation = dict(self.context) - self._parse_body_and_build_context() - self.context.update(set_after_creation) - self.defer_parsing = False - - def _parse_body_and_build_context(self) -> None: - if self.raw_body: - self.body = parse_body(self.raw_body, self.content_type) - build_async_context(self.context, self.body) - def to_copyable(self) -> "AsyncBoltRequest": body: Union[str, dict] = self.raw_body if self.mode == "http" else self.body - return AsyncBoltRequest( + copied = AsyncBoltRequest( body=body, query=self.query, headers=self.headers, context=self.context.to_copyable(), mode=self.mode, ) + copied.body = create_copy(self.body) + return copied diff --git a/slack_bolt/request/request.py b/slack_bolt/request/request.py index dcb49d8a4..ae9ffaf38 100644 --- a/slack_bolt/request/request.py +++ b/slack_bolt/request/request.py @@ -4,12 +4,11 @@ from slack_bolt.error import BoltError from slack_bolt.request.internals import ( parse_query, - parse_body, build_normalized_headers, - build_context, extract_content_type, error_message_raw_body_required_in_http_mode, ) +from slack_bolt.util.utils import create_copy class BoltRequest: @@ -22,7 +21,6 @@ class BoltRequest: lazy_only: bool lazy_function_name: Optional[str] mode: str # either "http" or "socket_mode" - defer_parsing: bool def __init__( self, @@ -32,19 +30,18 @@ def __init__( headers: Optional[Dict[str, Union[str, Sequence[str]]]] = None, context: Optional[Dict[str, Any]] = None, mode: str = "http", # either "http" or "socket_mode" - defer_parsing: bool = False, ): """Request to a Bolt app. + The body is parsed and the context is built from it when the app dispatches the request, + right after request verification, so unsigned payloads are never parsed. + Args: body: The raw request body (only plain text is supported for "http" mode) query: The query string data in any data format. headers: The request headers. context: The context in this request. mode: The mode used for this request. (either "http" or "socket_mode") - defer_parsing: True to leave `body` empty and skip building `context` from it until - the built-in `RequestParsing` middleware runs after `RequestVerification`. - Adapters set this so unsigned payloads are never parsed. """ if mode == "http": # HTTP Mode @@ -66,36 +63,18 @@ def __init__( self.body = body if isinstance(body, dict) else {} self.context = BoltContext(context if context else {}) - self.defer_parsing = defer_parsing - if not defer_parsing: - self._parse_body_and_build_context() self.lazy_only = bool(self.headers.get("x-slack-bolt-lazy-only", [False])[0]) self.lazy_function_name = self.headers.get("x-slack-bolt-lazy-function-name", [None])[0] self.mode = mode - def complete_deferred_parsing(self) -> None: - """Parses the body and builds the context of a request created with `defer_parsing=True`. - - Context values set after the request was created take precedence over the ones in the body. - """ - if not self.defer_parsing: - return - set_after_creation = dict(self.context) - self._parse_body_and_build_context() - self.context.update(set_after_creation) - self.defer_parsing = False - - def _parse_body_and_build_context(self) -> None: - if self.raw_body: - self.body = parse_body(self.raw_body, self.content_type) - build_context(self.context, self.body) - def to_copyable(self) -> "BoltRequest": body: Union[str, dict] = self.raw_body if self.mode == "http" else self.body - return BoltRequest( + copied = BoltRequest( body=body, query=self.query, headers=self.headers, context=self.context.to_copyable(), mode=self.mode, ) + copied.body = create_copy(self.body) + return copied diff --git a/tests/async_utils.py b/tests/async_utils.py new file mode 100644 index 000000000..ff6fdf76c --- /dev/null +++ b/tests/async_utils.py @@ -0,0 +1,11 @@ +from slack_bolt.middleware.request_parsing.async_request_parsing import AsyncRequestParsing +from slack_bolt.request.async_request import AsyncBoltRequest +from slack_bolt.response import BoltResponse + + +async def async_parse_request(req: AsyncBoltRequest) -> AsyncBoltRequest: + async def next_(): + return BoltResponse(status=200) + + await AsyncRequestParsing().async_process(req=req, resp=BoltResponse(status=200), next=next_) + return req diff --git a/tests/scenario_tests/test_request_parsing.py b/tests/scenario_tests/test_request_parsing.py index b5998c6c1..ae7d1fc05 100644 --- a/tests/scenario_tests/test_request_parsing.py +++ b/tests/scenario_tests/test_request_parsing.py @@ -1,5 +1,5 @@ import json -from time import time +import time from slack_sdk.signature import SignatureVerifier from slack_sdk.web import WebClient @@ -8,7 +8,7 @@ from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server from tests.scenario_tests import test_block_actions, test_shortcut, test_slash_command, test_view_submission from tests.slack_bolt.request import test_internals -from tests.utils import remove_os_env_temporarily, restore_os_env +from tests.utils import parse_request, remove_os_env_temporarily, restore_os_env form_bodies = [ test_block_actions.raw_body, @@ -62,8 +62,11 @@ def teardown_method(self): cleanup_mock_web_api_server(self) restore_os_env(self.old_os_env) - def build_request(self, body: str, defer_parsing: bool) -> BoltRequest: - timestamp = str(int(time())) + def build_app(self, **kwargs) -> App: + return App(client=self.web_client, signing_secret=self.signing_secret, **kwargs) + + def build_request(self, body: str) -> BoltRequest: + timestamp = str(int(time.time())) content_type = "application/json" if body.startswith("{") else "application/x-www-form-urlencoded" return BoltRequest( body=body, @@ -72,11 +75,10 @@ def build_request(self, body: str, defer_parsing: bool) -> BoltRequest: "x-slack-signature": [self.signature_verifier.generate_signature(body=body, timestamp=timestamp)], "x-slack-request-timestamp": [timestamp], }, - defer_parsing=defer_parsing, ) def capture_after_dispatch(self, request: BoltRequest) -> dict: - app = App(client=self.web_client, signing_secret=self.signing_secret) + app = self.build_app() captured = {} @app.middleware @@ -89,38 +91,43 @@ def capture(context, body, next): app.dispatch(request) return captured - def test_deferred_parsing_matches_eager_parsing(self): + def test_dispatch_matches_parsing_before_dispatch(self): for body in signed_bodies: - eager = self.capture_after_dispatch(self.build_request(body, defer_parsing=False)) - deferred = self.capture_after_dispatch(self.build_request(body, defer_parsing=True)) - assert eager != {} - assert deferred == eager, body + parsed_before = self.capture_after_dispatch(parse_request(self.build_request(body))) + parsed_in_dispatch = self.capture_after_dispatch(self.build_request(body)) + assert parsed_before != {} + assert parsed_in_dispatch == parsed_before, body - def test_deferred_request_is_unparsed_until_dispatch(self): - request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + def test_new_request_is_unparsed(self): + request = self.build_request(test_slash_command.slash_command_body) assert request.body == {} assert request.context.team_id is None - request.complete_deferred_parsing() - assert request.body["team_id"] == "T111" - assert request.context.team_id == "T111" - def test_context_set_after_creation_wins_over_body(self): - request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + def test_context_set_before_dispatch_wins_over_body(self): + app = self.build_app() + captured = {} + + @app.middleware + def capture(context, next): + captured["team_id"] = context.team_id + captured["user_id"] = context.user_id + captured["lambda_request"] = context["lambda_request"] + next() + + request = self.build_request(test_slash_command.slash_command_body) request.context["team_id"] = "T_FROM_ADAPTER" request.context["lambda_request"] = {"source": "adapter"} - request.complete_deferred_parsing() - assert request.context.team_id == "T_FROM_ADAPTER" - assert request.context["lambda_request"] == {"source": "adapter"} - assert request.context.user_id == "W111" + app.dispatch(request) + assert captured == {"team_id": "T_FROM_ADAPTER", "user_id": "W111", "lambda_request": {"source": "adapter"}} - def test_malformed_unsigned_deferred_requests_are_rejected(self): - app = App(client=self.web_client, signing_secret=self.signing_secret) + def test_malformed_unsigned_requests_are_rejected(self): + app = self.build_app() for body in malformed_unsigned_bodies: - request = BoltRequest(body=body, headers={"content-type": ["application/json"]}, defer_parsing=True) + request = BoltRequest(body=body, headers={"content-type": ["application/json"]}) assert app.dispatch(request).status == 401 - def test_deferred_parsing_without_request_verification(self): - app = App(client=self.web_client, signing_secret=self.signing_secret, request_verification_enabled=False) + def test_parsing_without_request_verification(self): + app = self.build_app(request_verification_enabled=False) captured = {} @app.middleware @@ -128,26 +135,39 @@ def capture(context, next): captured["team_id"] = context.team_id next() - request = BoltRequest(body=test_slash_command.slash_command_body, defer_parsing=True) - app.dispatch(request) + app.dispatch(BoltRequest(body=test_slash_command.slash_command_body)) assert captured["team_id"] == "T111" def test_signed_invalid_json_is_handled_by_the_error_handler(self): - app = App(client=self.web_client, signing_secret=self.signing_secret) - response = app.dispatch(self.build_request('{"type": "event_callback", ', defer_parsing=True)) + response = self.build_app().dispatch(self.build_request('{"type": "event_callback", ')) assert response.status == 500 - def test_ssl_check_on_deferred_request(self): - app = App(client=self.web_client, signing_secret=self.signing_secret) - request = BoltRequest(body="token=random&ssl_check=1", defer_parsing=True) - response = app.dispatch(request) + def test_ssl_check(self): + response = self.build_app().dispatch(BoltRequest(body="token=random&ssl_check=1")) assert response.status == 200 assert response.body == "" - def test_to_copyable_of_deferred_request_is_parsed(self): - request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) - request.complete_deferred_parsing() + def test_to_copyable_keeps_the_parsed_body(self): + request = parse_request(self.build_request(test_slash_command.slash_command_body)) copied = request.to_copyable() - assert copied.defer_parsing is False assert copied.body == request.body + assert copied.body is not request.body assert copied.context.team_id == "T111" + + def test_lazy_listener_reads_the_body(self): + app = self.build_app() + lazy_bodies = [] + + def just_ack(ack): + ack() + + def read_body(body): + lazy_bodies.append(body) + + app.command("/hello-world")(ack=just_ack, lazy=[read_body]) + response = app.dispatch(self.build_request(test_slash_command.slash_command_body)) + assert response.status == 200 + deadline = time.time() + 2 + while not lazy_bodies and time.time() < deadline: + time.sleep(0.05) + assert lazy_bodies[0]["command"] == "/hello-world" diff --git a/tests/scenario_tests_async/test_request_parsing.py b/tests/scenario_tests_async/test_request_parsing.py index cd03ac7b6..7731665fc 100644 --- a/tests/scenario_tests_async/test_request_parsing.py +++ b/tests/scenario_tests_async/test_request_parsing.py @@ -1,4 +1,5 @@ -from time import time +import asyncio +import time import pytest from slack_sdk.signature import SignatureVerifier @@ -6,6 +7,7 @@ from slack_bolt.app.async_app import AsyncApp from slack_bolt.request.async_request import AsyncBoltRequest +from tests.async_utils import async_parse_request from tests.mock_web_api_server import cleanup_mock_web_api_server_async, setup_mock_web_api_server_async from tests.scenario_tests import test_slash_command from tests.scenario_tests.test_request_parsing import malformed_unsigned_bodies, plain_values, signed_bodies @@ -29,8 +31,11 @@ def setup_teardown(self): cleanup_mock_web_api_server_async(self) restore_os_env(old_os_env) - def build_request(self, body: str, defer_parsing: bool) -> AsyncBoltRequest: - timestamp = str(int(time())) + def build_app(self, **kwargs) -> AsyncApp: + return AsyncApp(client=self.web_client, signing_secret=self.signing_secret, **kwargs) + + def build_request(self, body: str) -> AsyncBoltRequest: + timestamp = str(int(time.time())) content_type = "application/json" if body.startswith("{") else "application/x-www-form-urlencoded" return AsyncBoltRequest( body=body, @@ -39,11 +44,10 @@ def build_request(self, body: str, defer_parsing: bool) -> AsyncBoltRequest: "x-slack-signature": [self.signature_verifier.generate_signature(body=body, timestamp=timestamp)], "x-slack-request-timestamp": [timestamp], }, - defer_parsing=defer_parsing, ) async def capture_after_dispatch(self, request: AsyncBoltRequest) -> dict: - app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) + app = self.build_app() captured = {} @app.middleware @@ -57,31 +61,45 @@ async def capture(context, body, next): return captured @pytest.mark.asyncio - async def test_deferred_parsing_matches_eager_parsing(self): + async def test_dispatch_matches_parsing_before_dispatch(self): for body in signed_bodies: - eager = await self.capture_after_dispatch(self.build_request(body, defer_parsing=False)) - deferred = await self.capture_after_dispatch(self.build_request(body, defer_parsing=True)) - assert eager != {} - assert deferred == eager, body + parsed_before = await self.capture_after_dispatch(await async_parse_request(self.build_request(body))) + parsed_in_dispatch = await self.capture_after_dispatch(self.build_request(body)) + assert parsed_before != {} + assert parsed_in_dispatch == parsed_before, body @pytest.mark.asyncio - async def test_malformed_unsigned_deferred_requests_are_rejected(self): - app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) - for body in malformed_unsigned_bodies: - request = AsyncBoltRequest(body=body, headers={"content-type": ["application/json"]}, defer_parsing=True) - assert (await app.async_dispatch(request)).status == 401 + async def test_new_request_is_unparsed(self): + request = self.build_request(test_slash_command.slash_command_body) + assert request.body == {} + assert request.context.team_id is None @pytest.mark.asyncio - async def test_context_set_after_creation_wins_over_body(self): - request = self.build_request(test_slash_command.slash_command_body, defer_parsing=True) + async def test_context_set_before_dispatch_wins_over_body(self): + app = self.build_app() + captured = {} + + @app.middleware + async def capture(context, next): + captured["team_id"] = context.team_id + captured["user_id"] = context.user_id + await next() + + request = self.build_request(test_slash_command.slash_command_body) request.context["team_id"] = "T_FROM_ADAPTER" - request.complete_deferred_parsing() - assert request.context.team_id == "T_FROM_ADAPTER" - assert request.context.user_id == "W111" + await app.async_dispatch(request) + assert captured == {"team_id": "T_FROM_ADAPTER", "user_id": "W111"} @pytest.mark.asyncio - async def test_deferred_parsing_without_request_verification(self): - app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret, request_verification_enabled=False) + async def test_malformed_unsigned_requests_are_rejected(self): + app = self.build_app() + for body in malformed_unsigned_bodies: + request = AsyncBoltRequest(body=body, headers={"content-type": ["application/json"]}) + assert (await app.async_dispatch(request)).status == 401 + + @pytest.mark.asyncio + async def test_parsing_without_request_verification(self): + app = self.build_app(request_verification_enabled=False) captured = {} @app.middleware @@ -89,17 +107,42 @@ async def capture(context, next): captured["team_id"] = context.team_id await next() - await app.async_dispatch(AsyncBoltRequest(body=test_slash_command.slash_command_body, defer_parsing=True)) + await app.async_dispatch(AsyncBoltRequest(body=test_slash_command.slash_command_body)) assert captured["team_id"] == "T111" @pytest.mark.asyncio async def test_signed_invalid_json_is_handled_by_the_error_handler(self): - app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) - response = await app.async_dispatch(self.build_request('{"type": "event_callback", ', defer_parsing=True)) + response = await self.build_app().async_dispatch(self.build_request('{"type": "event_callback", ')) assert response.status == 500 @pytest.mark.asyncio - async def test_ssl_check_on_deferred_request(self): - app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret) - response = await app.async_dispatch(AsyncBoltRequest(body="token=random&ssl_check=1", defer_parsing=True)) + async def test_ssl_check(self): + response = await self.build_app().async_dispatch(AsyncBoltRequest(body="token=random&ssl_check=1")) + assert response.status == 200 + + @pytest.mark.asyncio + async def test_to_copyable_keeps_the_parsed_body(self): + request = await async_parse_request(self.build_request(test_slash_command.slash_command_body)) + copied = request.to_copyable() + assert copied.body == request.body + assert copied.body is not request.body + assert copied.context.team_id == "T111" + + @pytest.mark.asyncio + async def test_lazy_listener_reads_the_body(self): + app = self.build_app() + lazy_bodies = [] + + async def just_ack(ack): + await ack() + + async def read_body(body): + lazy_bodies.append(body) + + app.command("/hello-world")(ack=just_ack, lazy=[read_body]) + response = await app.async_dispatch(self.build_request(test_slash_command.slash_command_body)) assert response.status == 200 + deadline = time.time() + 2 + while not lazy_bodies and time.time() < deadline: + await asyncio.sleep(0.05) + assert lazy_bodies[0]["command"] == "/hello-world" diff --git a/tests/slack_bolt/listener_matcher/test_builtins.py b/tests/slack_bolt/listener_matcher/test_builtins.py index 4bb353913..c8191061e 100644 --- a/tests/slack_bolt/listener_matcher/test_builtins.py +++ b/tests/slack_bolt/listener_matcher/test_builtins.py @@ -10,6 +10,7 @@ event, shortcut, ) +from tests.utils import parse_request class TestBuiltins: @@ -34,7 +35,7 @@ def test_block_action(self): } raw_body = f"payload={quote(json.dumps(body))}" headers = {"Content-Type": "application/x-www-form-urlencoded"} - req = BoltRequest(body=raw_body, headers=headers) + req = parse_request(BoltRequest(body=raw_body, headers=headers)) resp = BoltResponse(status=404) assert block_action("valid_action_id").matches(req, resp) is True @@ -91,7 +92,7 @@ def test_workflow_step_execute(self): "event_time": 1601541373, } - request = BoltRequest(body=f"payload={quote(json.dumps(payload))}") + request = parse_request(BoltRequest(body=f"payload={quote(json.dumps(payload))}")) m = workflow_step_execute("copy_review") assert m.matches(request, None) == True @@ -103,7 +104,7 @@ def test_workflow_step_execute(self): assert m.matches(request, None) == True def test_events(self): - request = BoltRequest(body=json.dumps(event_payload)) + request = parse_request(BoltRequest(body=json.dumps(event_payload))) m = event("app_mention") assert m.matches(request, None) @@ -114,7 +115,7 @@ def test_events(self): m = event({"type": "message"}) assert not m.matches(request, None) - request = BoltRequest(body=f"payload={quote(json.dumps(shortcut_payload))}") + request = parse_request(BoltRequest(body=f"payload={quote(json.dumps(shortcut_payload))}")) m = event("app_mention") assert not m.matches(request, None) @@ -122,7 +123,7 @@ def test_events(self): assert not m.matches(request, None) def test_global_shortcuts(self): - request = BoltRequest(body=f"payload={quote(json.dumps(shortcut_payload))}") + request = parse_request(BoltRequest(body=f"payload={quote(json.dumps(shortcut_payload))}")) m = shortcut("test-shortcut") assert m.matches(request, None) @@ -137,7 +138,7 @@ def test_global_shortcuts(self): assert not m.matches(request, None) def test_message_shortcuts(self): - request = BoltRequest(body=f"payload={quote(json.dumps(message_shortcut_payload))}") + request = parse_request(BoltRequest(body=f"payload={quote(json.dumps(message_shortcut_payload))}")) m = shortcut("test-shortcut") assert m.matches(request, None) diff --git a/tests/slack_bolt/listener_matcher/test_custom_listener_matcher.py b/tests/slack_bolt/listener_matcher/test_custom_listener_matcher.py index 5a680f137..af8ae66f9 100644 --- a/tests/slack_bolt/listener_matcher/test_custom_listener_matcher.py +++ b/tests/slack_bolt/listener_matcher/test_custom_listener_matcher.py @@ -1,5 +1,6 @@ from slack_bolt import BoltRequest, BoltResponse, CustomListenerMatcher from slack_bolt.listener_matcher import ListenerMatcher +from tests.utils import parse_request def func(body, request, response, dummy): @@ -24,10 +25,10 @@ def test_instantiation(self): ) resp = BoltResponse(status=201) - req = BoltRequest(body='payload={"result":true}') + req = parse_request(BoltRequest(body='payload={"result":true}')) result = matcher.matches(req, resp) assert result is True - req = BoltRequest(body='payload={"result":false}') + req = parse_request(BoltRequest(body='payload={"result":false}')) result = matcher.matches(req, resp) assert result is False diff --git a/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py b/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py index 3f46a6b67..e243a6ee5 100644 --- a/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py +++ b/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py @@ -9,6 +9,7 @@ user_message_event_body, channel_user_message_event_body, ) +from tests.utils import parse_request def next(): @@ -85,7 +86,7 @@ def next(): class TestAttachingConversationKwargs: def test_assistant_event_attaches_kwargs(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=thread_started_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=thread_started_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -99,7 +100,7 @@ def test_assistant_event_attaches_kwargs(self): def test_user_message_event_attaches_kwargs(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=user_message_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=user_message_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -113,7 +114,7 @@ def test_user_message_event_attaches_kwargs(self): def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=top_level_im_message_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=top_level_im_message_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -129,7 +130,7 @@ def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self): def test_bot_dm_attaches_suggested_prompts(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=bot_im_message_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=bot_im_message_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -139,7 +140,7 @@ def test_bot_dm_attaches_suggested_prompts(self): def test_file_share_dm_attaches_suggested_prompts(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=file_share_im_message_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=file_share_im_message_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -149,7 +150,7 @@ def test_file_share_dm_attaches_suggested_prompts(self): def test_app_home_opened_messages_tab_attaches_suggested_prompts(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -163,7 +164,7 @@ def test_app_home_opened_messages_tab_attaches_suggested_prompts(self): def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=app_home_opened_home_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=app_home_opened_home_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -173,7 +174,7 @@ def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self): def test_non_assistant_event_does_not_attach_kwargs(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body=channel_user_message_event_body, mode="socket_mode") + req = parse_request(BoltRequest(body=channel_user_message_event_body, mode="socket_mode")) req.context["client"] = WebClient(token="xoxb-test") resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) @@ -186,7 +187,7 @@ def test_non_assistant_event_does_not_attach_kwargs(self): def test_non_event_does_not_attach_kwargs(self): middleware = AttachingConversationKwargs() - req = BoltRequest(body="payload={}", headers={}) + req = parse_request(BoltRequest(body="payload={}", headers={})) resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) diff --git a/tests/slack_bolt/request/test_request.py b/tests/slack_bolt/request/test_request.py index e091f9a21..09eef0312 100644 --- a/tests/slack_bolt/request/test_request.py +++ b/tests/slack_bolt/request/test_request.py @@ -1,6 +1,7 @@ from urllib.parse import quote from slack_bolt.request.request import BoltRequest +from tests.utils import parse_request class TestRequest: @@ -70,7 +71,7 @@ def test_org_wide_installations_block_actions(self): ] } """ - req = BoltRequest(body=f"payload={quote(payload)}") + req = parse_request(BoltRequest(body=f"payload={quote(payload)}")) assert req is not None assert req.context.team_id == "T_expected" assert req.context.user_id == "W111" @@ -158,7 +159,7 @@ def test_org_wide_installations_view_submission(self): } } """ - req = BoltRequest(body=f"payload={quote(payload)}") + req = parse_request(BoltRequest(body=f"payload={quote(payload)}")) assert req is not None assert req.context.team_id == "T_expected" assert req.context.user_id == "W111" @@ -236,7 +237,7 @@ def test_org_wide_installations_view_closed(self): } } """ - req = BoltRequest(body=f"payload={quote(payload)}") + req = parse_request(BoltRequest(body=f"payload={quote(payload)}")) assert req is not None assert req.context.team_id == "T_expected" assert req.context.user_id == "W111" diff --git a/tests/slack_bolt_async/listener_matcher/test_async_custom_listener_matcher.py b/tests/slack_bolt_async/listener_matcher/test_async_custom_listener_matcher.py index 96a407aab..40777d73c 100644 --- a/tests/slack_bolt_async/listener_matcher/test_async_custom_listener_matcher.py +++ b/tests/slack_bolt_async/listener_matcher/test_async_custom_listener_matcher.py @@ -6,6 +6,7 @@ ) from slack_bolt.request.async_request import AsyncBoltRequest from slack_bolt.response import BoltResponse +from tests.async_utils import async_parse_request async def func(body, request, response, dummy): @@ -25,10 +26,10 @@ async def test_instantiation(self): ) resp = BoltResponse(status=201) - req = AsyncBoltRequest(body='payload={"result":true}') + req = await async_parse_request(AsyncBoltRequest(body='payload={"result":true}')) result = await matcher.async_matches(req, resp) assert result is True - req = AsyncBoltRequest(body='payload={"result":false}') + req = await async_parse_request(AsyncBoltRequest(body='payload={"result":false}')) result = await matcher.async_matches(req, resp) assert result is False diff --git a/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py b/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py index c7da4ce93..a6ef76b1e 100644 --- a/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py +++ b/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py @@ -12,6 +12,7 @@ user_message_event_body, channel_user_message_event_body, ) +from tests.async_utils import async_parse_request async def next(): @@ -89,7 +90,7 @@ class TestAsyncAttachingConversationKwargs: @pytest.mark.asyncio async def test_assistant_event_attaches_kwargs(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=thread_started_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=thread_started_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -104,7 +105,7 @@ async def test_assistant_event_attaches_kwargs(self): @pytest.mark.asyncio async def test_user_message_event_attaches_kwargs(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=user_message_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=user_message_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -119,7 +120,7 @@ async def test_user_message_event_attaches_kwargs(self): @pytest.mark.asyncio async def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=top_level_im_message_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=top_level_im_message_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -136,7 +137,7 @@ async def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self): @pytest.mark.asyncio async def test_bot_dm_attaches_suggested_prompts(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=bot_im_message_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=bot_im_message_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -147,7 +148,7 @@ async def test_bot_dm_attaches_suggested_prompts(self): @pytest.mark.asyncio async def test_file_share_dm_attaches_suggested_prompts(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=file_share_im_message_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=file_share_im_message_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -158,7 +159,7 @@ async def test_file_share_dm_attaches_suggested_prompts(self): @pytest.mark.asyncio async def test_app_home_opened_messages_tab_attaches_suggested_prompts(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -173,7 +174,7 @@ async def test_app_home_opened_messages_tab_attaches_suggested_prompts(self): @pytest.mark.asyncio async def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=app_home_opened_home_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=app_home_opened_home_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -184,7 +185,7 @@ async def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self): @pytest.mark.asyncio async def test_non_assistant_event_does_not_attach_kwargs(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body=channel_user_message_event_body, mode="socket_mode") + req = await async_parse_request(AsyncBoltRequest(body=channel_user_message_event_body, mode="socket_mode")) req.context["client"] = AsyncWebClient(token="xoxb-test") resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) @@ -198,7 +199,7 @@ async def test_non_assistant_event_does_not_attach_kwargs(self): @pytest.mark.asyncio async def test_non_event_does_not_attach_kwargs(self): middleware = AsyncAttachingConversationKwargs() - req = AsyncBoltRequest(body="payload={}", headers={}) + req = await async_parse_request(AsyncBoltRequest(body="payload={}", headers={})) resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) diff --git a/tests/utils.py b/tests/utils.py index e06d0f861..aed1d9437 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,6 +1,10 @@ import os import asyncio +from slack_bolt.middleware.request_parsing import RequestParsing +from slack_bolt.request import BoltRequest +from slack_bolt.response import BoltResponse + def remove_os_env_temporarily() -> dict: old_env = os.environ.copy() @@ -13,3 +17,8 @@ def remove_os_env_temporarily() -> dict: def restore_os_env(old_env: dict) -> None: os.environ.update(old_env) + + +def parse_request(req: BoltRequest) -> BoltRequest: + RequestParsing().process(req=req, resp=BoltResponse(status=200), next=lambda: BoltResponse(status=200)) + return req From 1a21eeb252f3a2f54cba4e5626b815cfdeca7845 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 15:21:58 -0500 Subject: [PATCH 08/10] revert: move the malformed signature header fix to its own PR It is independent of parsing after verification. Co-Authored-By: Claude --- .../async_request_verification.py | 2 +- .../request_verification/request_verification.py | 9 +-------- .../request_verification/test_request_verification.py | 10 ---------- .../request_verification/test_request_verification.py | 11 ----------- 4 files changed, 2 insertions(+), 30 deletions(-) diff --git a/slack_bolt/middleware/request_verification/async_request_verification.py b/slack_bolt/middleware/request_verification/async_request_verification.py index 06ca7647a..99b86a63c 100644 --- a/slack_bolt/middleware/request_verification/async_request_verification.py +++ b/slack_bolt/middleware/request_verification/async_request_verification.py @@ -30,7 +30,7 @@ async def async_process( 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): + if self.verifier.is_valid(body, timestamp, signature): return await next() else: self._debug_log_error(signature, timestamp, body) diff --git a/slack_bolt/middleware/request_verification/request_verification.py b/slack_bolt/middleware/request_verification/request_verification.py index 26b082243..1425f7baf 100644 --- a/slack_bolt/middleware/request_verification/request_verification.py +++ b/slack_bolt/middleware/request_verification/request_verification.py @@ -48,7 +48,7 @@ def process( 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): + if self.verifier.is_valid(body, timestamp, signature): return next() else: self._debug_log_error(signature, timestamp, body) @@ -56,13 +56,6 @@ def process( # ----------------------------------------- - 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" diff --git a/tests/slack_bolt/middleware/request_verification/test_request_verification.py b/tests/slack_bolt/middleware/request_verification/test_request_verification.py index 10e973081..53af43bf3 100644 --- a/tests/slack_bolt/middleware/request_verification/test_request_verification.py +++ b/tests/slack_bolt/middleware/request_verification/test_request_verification.py @@ -79,13 +79,3 @@ def test_http_request_with_empty_signing_secret_raises(self): resp = BoltResponse(status=404) with pytest.raises(ValueError): middleware.process(req=req, resp=resp, next=next) - - def test_malformed_headers(self): - middleware = RequestVerification(signing_secret=self.signing_secret) - for headers in [ - {"x-slack-request-timestamp": ["abc"], "x-slack-signature": ["v0=invalid"]}, - {"x-slack-request-timestamp": [str(int(time()))], "x-slack-signature": ["v0=ñ"]}, - ]: - req = BoltRequest(body="payload={}", headers=headers) - resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next) - assert resp.status == 401 diff --git a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py index 3d80a5b30..126b04f94 100644 --- a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py +++ b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py @@ -86,14 +86,3 @@ async def test_http_request_with_empty_signing_secret_raises(self): resp = BoltResponse(status=404) with pytest.raises(ValueError): await middleware.async_process(req=req, resp=resp, next=next) - - @pytest.mark.asyncio - async def test_malformed_headers(self): - middleware = AsyncRequestVerification(signing_secret=self.signing_secret) - for headers in [ - {"x-slack-request-timestamp": ["abc"], "x-slack-signature": ["v0=invalid"]}, - {"x-slack-request-timestamp": [str(int(time()))], "x-slack-signature": ["v0=ñ"]}, - ]: - req = AsyncBoltRequest(body="payload={}", headers=headers) - resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next) - assert resp.status == 401 From 5f69d8a18c3b88747b8b3020f04b7a1fe4e0a35f Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 16:37:47 -0500 Subject: [PATCH 09/10] fix: skip JSON bodies in SslCheck form parsing parse_qsl split JSON event bodies on "&", so a signed event whose text contained "&ssl_check=1&" was answered as an ssl_check and never reached its listener. Co-Authored-By: Claude --- slack_bolt/middleware/ssl_check/ssl_check.py | 2 ++ tests/scenario_tests/test_ssl_check.py | 30 +++++++++++++++++++ tests/scenario_tests_async/test_ssl_check.py | 31 ++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/slack_bolt/middleware/ssl_check/ssl_check.py b/slack_bolt/middleware/ssl_check/ssl_check.py index 0a7f8e603..910ede907 100644 --- a/slack_bolt/middleware/ssl_check/ssl_check.py +++ b/slack_bolt/middleware/ssl_check/ssl_check.py @@ -51,6 +51,8 @@ def process( @staticmethod def _parse_form_params(raw_body: str) -> Dict[str, str]: + if raw_body.startswith("{"): + return {} return dict(parse_qsl(raw_body, keep_blank_values=True)) @staticmethod diff --git a/tests/scenario_tests/test_ssl_check.py b/tests/scenario_tests/test_ssl_check.py index 937f9d7e4..2853ee387 100644 --- a/tests/scenario_tests/test_ssl_check.py +++ b/tests/scenario_tests/test_ssl_check.py @@ -1,3 +1,4 @@ +import json from time import time from slack_sdk.signature import SignatureVerifier @@ -76,3 +77,32 @@ def test_ssl_check_disabled(self): response = app.dispatch(request) assert response.status == 404 assert response.body == """{"error": "unhandled request"}""" + + def test_json_body_containing_ssl_check_reaches_its_listener(self): + app = App(client=self.web_client, signing_secret=self.signing_secret, process_before_response=True) + handled = [] + + @app.event("link_shared") + def handle_link_shared(): + handled.append(True) + + timestamp = str(int(time())) + body = json.dumps( + { + "type": "event_callback", + "team_id": "T111", + "event": {"type": "link_shared", "links": [{"url": "https://x.io/?a=1&ssl_check=1&b=2"}]}, + } + ) + request: BoltRequest = BoltRequest( + body=body, + query={}, + headers={ + "content-type": ["application/json"], + "x-slack-signature": [self.generate_signature(body, timestamp)], + "x-slack-request-timestamp": [timestamp], + }, + ) + response = app.dispatch(request) + assert response.status == 200 + assert handled == [True] diff --git a/tests/scenario_tests_async/test_ssl_check.py b/tests/scenario_tests_async/test_ssl_check.py index ef32bc0dd..1839c75ed 100644 --- a/tests/scenario_tests_async/test_ssl_check.py +++ b/tests/scenario_tests_async/test_ssl_check.py @@ -1,3 +1,4 @@ +import json from time import time import pytest @@ -61,3 +62,33 @@ async def test_ssl_check(self): response = await app.async_dispatch(request) assert response.status == 200 assert response.body == "" + + @pytest.mark.asyncio + async def test_json_body_containing_ssl_check_reaches_its_listener(self): + app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret, process_before_response=True) + handled = [] + + @app.event("link_shared") + async def handle_link_shared(): + handled.append(True) + + timestamp = str(int(time())) + body = json.dumps( + { + "type": "event_callback", + "team_id": "T111", + "event": {"type": "link_shared", "links": [{"url": "https://x.io/?a=1&ssl_check=1&b=2"}]}, + } + ) + request: AsyncBoltRequest = AsyncBoltRequest( + body=body, + query={}, + headers={ + "content-type": ["application/json"], + "x-slack-signature": [self.generate_signature(body, timestamp)], + "x-slack-request-timestamp": [timestamp], + }, + ) + response = await app.async_dispatch(request) + assert response.status == 200 + assert handled == [True] From 6bd06b16d769834ef940b903c15b6ec26d46259f Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Thu, 26 Nov 2026 16:37:56 -0500 Subject: [PATCH 10/10] docs: drop the request parsing docstrings They claimed unsigned payloads are never parsed, which is false with request verification disabled; test_parsing_without_request_verification pins the real behavior. Co-Authored-By: Claude --- .../middleware/request_parsing/async_request_parsing.py | 6 ------ slack_bolt/middleware/request_parsing/request_parsing.py | 6 ------ slack_bolt/request/async_request.py | 3 --- slack_bolt/request/request.py | 3 --- 4 files changed, 18 deletions(-) diff --git a/slack_bolt/middleware/request_parsing/async_request_parsing.py b/slack_bolt/middleware/request_parsing/async_request_parsing.py index dbdf5a8ea..611e842e2 100644 --- a/slack_bolt/middleware/request_parsing/async_request_parsing.py +++ b/slack_bolt/middleware/request_parsing/async_request_parsing.py @@ -9,12 +9,6 @@ class AsyncRequestParsing(AsyncMiddleware): - """Parses the request body and builds the context from it. - - Runs right after `AsyncRequestVerification`, so unsigned payloads are never parsed. - Values already in the context take precedence over the ones in the body. - """ - async def async_process( self, *, diff --git a/slack_bolt/middleware/request_parsing/request_parsing.py b/slack_bolt/middleware/request_parsing/request_parsing.py index 5177bfc1e..42e551d9d 100644 --- a/slack_bolt/middleware/request_parsing/request_parsing.py +++ b/slack_bolt/middleware/request_parsing/request_parsing.py @@ -8,12 +8,6 @@ class RequestParsing(Middleware): - """Parses the request body and builds the context from it. - - Runs right after `RequestVerification`, so unsigned payloads are never parsed. - Values already in the context take precedence over the ones in the body. - """ - def process( self, *, diff --git a/slack_bolt/request/async_request.py b/slack_bolt/request/async_request.py index 0f8732a5d..ee6f2579b 100644 --- a/slack_bolt/request/async_request.py +++ b/slack_bolt/request/async_request.py @@ -33,9 +33,6 @@ def __init__( ): """Request to a Bolt app. - The body is parsed and the context is built from it when the app dispatches the request, - right after request verification, so unsigned payloads are never parsed. - Args: body: The raw request body (only plain text is supported for "http" mode) query: The query string data in any data format. diff --git a/slack_bolt/request/request.py b/slack_bolt/request/request.py index ae9ffaf38..716f892f7 100644 --- a/slack_bolt/request/request.py +++ b/slack_bolt/request/request.py @@ -33,9 +33,6 @@ def __init__( ): """Request to a Bolt app. - The body is parsed and the context is built from it when the app dispatches the request, - right after request verification, so unsigned payloads are never parsed. - Args: body: The raw request body (only plain text is supported for "http" mode) query: The query string data in any data format.