Skip to content

Commit 29f71c3

Browse files
committed
fix(LambdaHandler): remove context option
The LambdaContext paramater for Validator#validate_event calls have bben removed in order to avoid any tampering with the context object. BREAKING CHANGE: The context option has been removed.
1 parent 14393a9 commit 29f71c3

14 files changed

+47
-101
lines changed

lambda_handlers/__init__.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,7 @@
99
InternalServerError,
1010
)
1111
from lambda_handlers.version import __version__ # noqa
12-
from lambda_handlers.handlers import ( # noqa
13-
HTTPHandler,
14-
EventHandler,
15-
LambdaHandler,
16-
)
12+
from lambda_handlers.handlers import HTTPHandler, EventHandler, LambdaHandler # noqa
1713
from lambda_handlers.response import cors_headers, response_builder # noqa
1814
from lambda_handlers.formatters import input_format, output_format # noqa
1915
from lambda_handlers.validators import jsonschema, marshmallow # noqa

lambda_handlers/handlers/event_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def validator(self) -> Validator:
4242

4343
def before(self, event, context):
4444
"""Event hook called before the handler. It formats and validates `event`."""
45-
return self.validate_event(self.format_input(event), context)
45+
return self.validate_event(self.format_input(event)), context
4646

4747
def after(self, result):
4848
"""Event method called after the handler. It formats and validates `result`."""

lambda_handlers/handlers/http_handler.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,7 @@
44
from typing import Any, Dict
55

66
from lambda_handlers.types import Headers, APIGatewayProxyResult
7-
from lambda_handlers.errors import (
8-
FormatError,
9-
NotFoundError,
10-
BadRequestError,
11-
ValidationError,
12-
ResultValidationError,
13-
)
7+
from lambda_handlers.errors import FormatError, NotFoundError, BadRequestError, ValidationError, ResultValidationError
148
from lambda_handlers.response import CORSHeaders
159
from lambda_handlers.handlers.event_handler import EventHandler
1610
from lambda_handlers.response.response_builder import (
@@ -96,7 +90,8 @@ def _create_headers(self, headers: Headers) -> Headers:
9690

9791
return headers or None
9892

99-
def _handle_error(self, error) -> APIGatewayProxyResult:
93+
@staticmethod
94+
def _handle_error(error) -> APIGatewayProxyResult:
10095
if isinstance(error, NotFoundError):
10196
return not_found(error.description)
10297
if isinstance(error, ResultValidationError):

lambda_handlers/handlers/lambda_handler.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""A base class for AWS Lambda handlers."""
22

33
from abc import ABC
4-
from typing import Any, Dict, Tuple, Callable, Optional
4+
from typing import Any, Dict, Tuple, NewType, Callable, Optional
55
from functools import wraps
66

77
Event = Dict[str, Any]
8-
Context = Dict[str, Any]
8+
LambdaContext = NewType('LambdaContext', object)
99

1010

1111
class LambdaHandler(ABC):
@@ -17,25 +17,20 @@ class LambdaHandler(ABC):
1717
def __init__(self, handler: Optional[Callable] = None):
1818
self._handler = handler
1919

20-
def __call__(self, handler: Callable):
21-
"""Decorate `handler`."""
20+
def __call__(self, handler: Callable): # noqa: D102
2221
@wraps(handler)
2322
def wrapper(event, context):
2423
return self._call_handler(handler, event, context)
24+
2525
return wrapper
2626

27-
def _call_handler(
28-
self,
29-
handler: Callable,
30-
event: Event,
31-
context: Context,
32-
) -> Any:
27+
def _call_handler(self, handler: Callable, event: Event, context: LambdaContext) -> Any:
3328
try:
3429
return self.after(handler(*self.before(event, context)))
3530
except Exception as exception:
3631
return self.on_exception(exception)
3732

38-
def before(self, event: Event, context: Context) -> Tuple[Event, Context]:
33+
def before(self, event: Event, context: LambdaContext) -> Tuple[Event, LambdaContext]:
3934
"""Event method to be called just before the handler is executed."""
4035
return event, context
4136

lambda_handlers/handlers/mixins/validation_mixin.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,12 @@ def validator(self):
1313
"""Return the validator for events and results."""
1414
pass
1515

16-
def validate_event(self, event, context):
16+
def validate_event(self, event):
1717
"""Validate the event with `self.validator`, return event and context."""
1818
if self.validator:
19-
transformed_event, transformed_context = self.validator.validate_event(event, context)
19+
transformed_event = self.validator.validate_event(event)
2020
event.update(transformed_event)
21-
if context is not None:
22-
context.update(transformed_context)
23-
return event, context
21+
return event
2422

2523
def validate_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
2624
"""Validate and return the result with `self.validator`."""

lambda_handlers/handlers/tests/test_lambda_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import pytest
44

5-
from lambda_handlers.handlers.lambda_handler import Context, LambdaHandler
5+
from lambda_handlers.handlers.lambda_handler import LambdaContext, LambdaHandler
66

77
Event = Dict[str, Any]
88

@@ -14,7 +14,7 @@ def __init__(self, message: str, event: Event):
1414

1515

1616
class CallOrderAwareHandler(LambdaHandler):
17-
def before(self, event: Event, context: Context) -> Tuple[Event, Context]:
17+
def before(self, event: Event, context: LambdaContext) -> Tuple[Event, LambdaContext]:
1818
event['route'].append('before')
1919
return super().before(event, context)
2020

lambda_handlers/response/response_builder.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,7 @@
44
from typing import Any, Union
55

66
from lambda_handlers.types import APIGatewayProxyResult
7-
from lambda_handlers.errors import (
8-
LambdaError,
9-
NotFoundError,
10-
ForbiddenError,
11-
BadRequestError,
12-
InternalServerError,
13-
)
7+
from lambda_handlers.errors import LambdaError, NotFoundError, ForbiddenError, BadRequestError, InternalServerError
148

159

1610
def ok(result: Any) -> APIGatewayProxyResult:

lambda_handlers/validators/http/http_marshmallow_validator.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
"""A AWS HTTP event validator that uses Marshmallow."""
22

33
from lambda_handlers.validators.http.http_validator import HttpValidator
4-
from lambda_handlers.validators.marshmallow_validator import (
5-
MarshmallowValidator,
6-
)
4+
from lambda_handlers.validators.marshmallow_validator import MarshmallowValidator
75

86

97
class HttpMarshmallowValidator(MarshmallowValidator, HttpValidator):

lambda_handlers/validators/http/tests/test_http_jsonschema_validator.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
from lambda_handlers.validators.http.http_validator import HttpValidator
44
from lambda_handlers.validators.jsonschema_validator import JSONSchemaValidator
5-
from lambda_handlers.validators.http.http_jsonschema_validator import (
6-
HttpJSONSchemaValidator,
7-
)
5+
from lambda_handlers.validators.http.http_jsonschema_validator import HttpJSONSchemaValidator
86

97

108
@pytest.fixture(scope='session')

lambda_handlers/validators/http/tests/test_http_marshmallow_validator.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,8 @@
33

44
from lambda_handlers.errors import EventValidationError
55
from lambda_handlers.validators.http.http_validator import HttpValidator
6-
from lambda_handlers.validators.marshmallow_validator import (
7-
MarshmallowValidator,
8-
)
9-
from lambda_handlers.validators.http.http_marshmallow_validator import (
10-
HttpMarshmallowValidator,
11-
)
6+
from lambda_handlers.validators.marshmallow_validator import MarshmallowValidator
7+
from lambda_handlers.validators.http.http_marshmallow_validator import HttpMarshmallowValidator
128

139

1410
class TestHttpMarshmallowSchemaValidator:
@@ -39,19 +35,16 @@ def test_validate_valid_request(self, subject):
3935
'accountable': True,
4036
},
4137
}
42-
context = {}
43-
assert subject.validate_event(event, context)
38+
assert subject.validate_event(event)
4439

4540
def test_validate_invalid_request(self, subject):
4641
event = {
4742
'pathParameters': {
4843
'user_name': True,
4944
},
5045
}
51-
context = {}
52-
5346
with pytest.raises(EventValidationError) as error:
54-
subject.validate_event(event, context)
47+
subject.validate_event(event)
5548

5649
nested_errors = error.value.description
5750
assert isinstance(nested_errors, list)

0 commit comments

Comments
 (0)