Skip to content

fix(parser): apigw wss validation check_message_id; housekeeping #553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions aws_lambda_powertools/tracing/tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ def decorate(event, context, **kwargs):
# see #465
@overload
def capture_method(self, method: "AnyCallableT") -> "AnyCallableT":
...
... # pragma: no cover

@overload
def capture_method(
Expand All @@ -344,7 +344,7 @@ def capture_method(
capture_response: Optional[bool] = None,
capture_error: Optional[bool] = None,
) -> Callable[["AnyCallableT"], "AnyCallableT"]:
...
... # pragma: no cover

def capture_method(
self,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Any, Dict, Optional
from typing import Any, Dict, Optional, cast

from botocore.config import Config

Expand Down Expand Up @@ -56,11 +56,15 @@ def get_json_configuration(self) -> Dict[str, Any]:
parsed JSON dictionary
"""
try:
return self._conf_store.get(
name=self.configuration_name,
transform=TRANSFORM_TYPE,
max_age=self._cache_seconds,
) # parse result conf as JSON, keep in cache for self.max_age seconds
# parse result conf as JSON, keep in cache for self.max_age seconds
return cast(
dict,
self._conf_store.get(
name=self.configuration_name,
transform=TRANSFORM_TYPE,
max_age=self._cache_seconds,
),
)
except (GetParameterError, TransformParameterError) as exc:
error_str = f"unable to get AWS AppConfig configuration file, exception={str(exc)}"
self._logger.error(error_str)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def _update_record(self, data_record: DataRecord):
"ExpressionAttributeNames": expression_attr_names,
}

self.table.update_item(**kwargs)
self.table.update_item(**kwargs) # type: ignore

def _delete_record(self, data_record: DataRecord) -> None:
logger.debug(f"Deleting record for idempotency key: {data_record.idempotency_key}")
Expand Down
11 changes: 3 additions & 8 deletions aws_lambda_powertools/utilities/parameters/dynamodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""


from typing import Any, Dict, Optional
from typing import Dict, Optional

import boto3
from boto3.dynamodb.conditions import Key
Expand Down Expand Up @@ -141,11 +141,6 @@ class DynamoDBProvider(BaseProvider):
c Parameter value c
"""

table: Any = None
key_attr = None
sort_attr = None
value_attr = None

def __init__(
self,
table_name: str,
Expand Down Expand Up @@ -183,7 +178,7 @@ def _get(self, name: str, **sdk_options) -> str:
# Explicit arguments will take precedence over keyword arguments
sdk_options["Key"] = {self.key_attr: name}

return self.table.get_item(**sdk_options)["Item"][self.value_attr]
return str(self.table.get_item(**sdk_options)["Item"][self.value_attr])

def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
"""
Expand All @@ -209,4 +204,4 @@ def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
response = self.table.query(**sdk_options)
items.extend(response.get("Items", []))

return {item[self.sort_attr]: item[self.value_attr] for item in items}
return {str(item[self.sort_attr]): str(item[self.value_attr]) for item in items}
14 changes: 7 additions & 7 deletions aws_lambda_powertools/utilities/parser/models/apigw.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ class APIGatewayEventRequestContext(BaseModel):
routeKey: Optional[str]
operationName: Optional[str]

@root_validator()
def check_message_id(cls, values):
message_id, event_type = values.get("messageId"), values.get("eventType")
if message_id is not None and event_type != "MESSAGE":
raise TypeError("messageId is available only when the `eventType` is `MESSAGE`")
return values


class APIGatewayProxyEventModel(BaseModel):
version: Optional[str]
Expand All @@ -83,10 +90,3 @@ class APIGatewayProxyEventModel(BaseModel):
stageVariables: Optional[Dict[str, str]]
isBase64Encoded: bool
body: str

@root_validator()
def check_message_id(cls, values):
message_id, event_type = values.get("messageId"), values.get("eventType")
if message_id is not None and event_type != "MESSAGE":
raise TypeError("messageId is available only when the `eventType` is `MESSAGE`")
return values
20 changes: 20 additions & 0 deletions tests/functional/parser/test_apigw.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import pytest
from pydantic import ValidationError

from aws_lambda_powertools.utilities.parser import envelopes, event_parser
from aws_lambda_powertools.utilities.parser.models import APIGatewayProxyEventModel
from aws_lambda_powertools.utilities.typing import LambdaContext
Expand Down Expand Up @@ -100,3 +103,20 @@ def test_apigw_event():
assert request_context.operationName is None
assert identity.apiKey is None
assert identity.apiKeyId is None


def test_apigw_event_with_invalid_websocket_request():
# GIVEN an event with an eventType != MESSAGE and has a messageId
event = {
"requestContext": {
"eventType": "DISCONNECT",
"messageId": "messageId",
},
}

# WHEN calling event_parser with APIGatewayProxyEventModel
with pytest.raises(ValidationError) as err:
handle_apigw_event(event, LambdaContext())

# THEN raise TypeError for invalid event
assert "messageId is available only when the `eventType` is `MESSAGE`" in str(err.value)