Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions slack_bolt/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
Middleware,
SslCheck,
RequestVerification,
RequestParsing,
SingleTeamAuthorization,
MultiTeamsAuthorization,
IgnoringSelfEvents,
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions slack_bolt/app/async_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
from slack_bolt.middleware.async_builtins import (
AsyncSslCheck,
AsyncRequestVerification,
AsyncRequestParsing,
AsyncIgnoringSelfEvents,
AsyncUrlVerification,
AsyncAttachingFunctionToken,
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions slack_bolt/middleware/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -23,6 +24,7 @@
builtin_middleware_classes = [
SslCheck,
RequestVerification,
RequestParsing,
SingleTeamAuthorization,
MultiTeamsAuthorization,
IgnoringSelfEvents,
Expand All @@ -40,6 +42,7 @@
"IgnoringSelfEvents",
"Middleware",
"RequestVerification",
"RequestParsing",
"SslCheck",
"UrlVerification",
"AttachingFunctionToken",
Expand Down
2 changes: 2 additions & 0 deletions slack_bolt/middleware/async_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -15,6 +16,7 @@
__all__ = [
"AsyncIgnoringSelfEvents",
"AsyncRequestVerification",
"AsyncRequestParsing",
"AsyncSslCheck",
"AsyncUrlVerification",
"AsyncMessageListenerMatches",
Expand Down
5 changes: 5 additions & 0 deletions slack_bolt/middleware/request_parsing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .request_parsing import RequestParsing

__all__ = [
"RequestParsing",
]
31 changes: 31 additions & 0 deletions slack_bolt/middleware/request_parsing/async_request_parsing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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_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 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,
*,
req: AsyncBoltRequest,
resp: BoltResponse,
next: Callable[[], Awaitable[BoltResponse]],
) -> BoltResponse:
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()
35 changes: 35 additions & 0 deletions slack_bolt/middleware/request_parsing/request_parsing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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.request.internals import build_context, parse_body
from slack_bolt.response import BoltResponse


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.
"""
Comment thread
WilliamBergamin marked this conversation as resolved.
Resolved

def process(
self,
*,
req: BoltRequest,
resp: BoltResponse,
next: Callable[[], BoltResponse],
) -> BoltResponse:
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)
Comment thread
WilliamBergamin marked this conversation as resolved.
Resolved
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
5 changes: 3 additions & 2 deletions slack_bolt/middleware/ssl_check/async_ssl_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 9 additions & 3 deletions slack_bolt/middleware/ssl_check/ssl_check.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -38,15 +39,20 @@ 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:
return next()

# -----------------------------------------

@staticmethod
def _parse_form_params(raw_body: str) -> Dict[str, str]:
return dict(parse_qsl(raw_body, keep_blank_values=True))
Comment thread
WilliamBergamin marked this conversation as resolved.
Resolved

@staticmethod
def _is_ssl_check_request(body: dict):
return "ssl_check" in body and body["ssl_check"] == "1"
Expand Down
20 changes: 9 additions & 11 deletions slack_bolt/request/async_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -34,6 +33,9 @@ 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.
Expand All @@ -59,24 +61,20 @@ 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.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 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
20 changes: 9 additions & 11 deletions slack_bolt/request/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -34,6 +33,9 @@ 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.
Expand All @@ -59,24 +61,20 @@ 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 {}
Comment thread
WilliamBergamin marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question (blocking): Your earlier thread on this got resolved, but the PR is still semver:minor while the release notes list BoltRequest(body=raw).body == {} before dispatch. Are we shipping this as a minor on the security-fix grounds, or should it carry the next major? Either works for me once the call and a migration note are in the release notes.

self.context = BoltContext(context if context else {})
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 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
23 changes: 23 additions & 0 deletions tests/adapter_tests/aws/test_aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
11 changes: 11 additions & 0 deletions tests/async_utils.py
Original file line number Diff line number Diff line change
@@ -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
Loading