|
| 1 | +import logging |
| 2 | +from typing import Dict, Optional |
| 3 | + |
| 4 | +from aws_lambda_powertools.event_handler.api_gateway import Response |
| 5 | +from aws_lambda_powertools.event_handler.exceptions import BadRequestError, InternalServerError |
| 6 | +from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware |
| 7 | +from aws_lambda_powertools.event_handler.types import EventHandlerInstance |
| 8 | +from aws_lambda_powertools.utilities.validation import validate |
| 9 | +from aws_lambda_powertools.utilities.validation.exceptions import InvalidSchemaFormatError, SchemaValidationError |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class SchemaValidationMiddleware(BaseMiddlewareHandler): |
| 15 | + """Middleware to validate API request and response against JSON Schema using the [Validation utility](https://docs.powertools.aws.dev/lambda/python/latest/utilities/validation/). |
| 16 | +
|
| 17 | + Examples |
| 18 | + -------- |
| 19 | + **Validating incoming event** |
| 20 | +
|
| 21 | + ```python |
| 22 | + import requests |
| 23 | +
|
| 24 | + from aws_lambda_powertools import Logger |
| 25 | + from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response |
| 26 | + from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware |
| 27 | + from aws_lambda_powertools.event_handler.middlewares.schema_validation import SchemaValidationMiddleware |
| 28 | +
|
| 29 | + app = APIGatewayRestResolver() |
| 30 | + logger = Logger() |
| 31 | + json_schema_validation = SchemaValidationMiddleware(inbound_schema=INCOMING_JSON_SCHEMA) |
| 32 | +
|
| 33 | +
|
| 34 | + @app.get("/todos", middlewares=[json_schema_validation]) |
| 35 | + def get_todos(): |
| 36 | + todos: requests.Response = requests.get("https://jsonplaceholder.typicode.com/todos") |
| 37 | + todos.raise_for_status() |
| 38 | +
|
| 39 | + # for brevity, we'll limit to the first 10 only |
| 40 | + return {"todos": todos.json()[:10]} |
| 41 | +
|
| 42 | +
|
| 43 | + @logger.inject_lambda_context |
| 44 | + def lambda_handler(event, context): |
| 45 | + return app.resolve(event, context) |
| 46 | + ``` |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + inbound_schema: Dict, |
| 52 | + inbound_formats: Optional[Dict] = None, |
| 53 | + outbound_schema: Optional[Dict] = None, |
| 54 | + outbound_formats: Optional[Dict] = None, |
| 55 | + ): |
| 56 | + """See [Validation utility](https://docs.powertools.aws.dev/lambda/python/latest/utilities/validation/) docs for examples on all parameters. |
| 57 | +
|
| 58 | + Parameters |
| 59 | + ---------- |
| 60 | + inbound_schema : Dict |
| 61 | + JSON Schema to validate incoming event |
| 62 | + inbound_formats : Optional[Dict], optional |
| 63 | + Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool, by default None |
| 64 | + JSON Schema to validate outbound event, by default None |
| 65 | + outbound_formats : Optional[Dict], optional |
| 66 | + Custom formats containing a key (e.g. int64) and a value expressed as regex or callback returning bool, by default None |
| 67 | + """ # noqa: E501 |
| 68 | + super().__init__() |
| 69 | + self.inbound_schema = inbound_schema |
| 70 | + self.inbound_formats = inbound_formats |
| 71 | + self.outbound_schema = outbound_schema |
| 72 | + self.outbound_formats = outbound_formats |
| 73 | + |
| 74 | + def bad_response(self, error: SchemaValidationError) -> Response: |
| 75 | + message: str = f"Bad Response: {error.message}" |
| 76 | + logger.debug(message) |
| 77 | + raise BadRequestError(message) |
| 78 | + |
| 79 | + def bad_request(self, error: SchemaValidationError) -> Response: |
| 80 | + message: str = f"Bad Request: {error.message}" |
| 81 | + logger.debug(message) |
| 82 | + raise BadRequestError(message) |
| 83 | + |
| 84 | + def bad_config(self, error: InvalidSchemaFormatError) -> Response: |
| 85 | + logger.debug(f"Invalid Schema Format: {error}") |
| 86 | + raise InternalServerError("Internal Server Error") |
| 87 | + |
| 88 | + def handler(self, app: EventHandlerInstance, next_middleware: NextMiddleware) -> Response: |
| 89 | + """Validates incoming JSON payload (body) against JSON Schema provided. |
| 90 | +
|
| 91 | + Parameters |
| 92 | + ---------- |
| 93 | + app : EventHandlerInstance |
| 94 | + An instance of an Event Handler |
| 95 | + next_middleware : NextMiddleware |
| 96 | + Callable to get response from the next middleware or route handler in the chain |
| 97 | +
|
| 98 | + Returns |
| 99 | + ------- |
| 100 | + Response |
| 101 | + It can return three types of response objects |
| 102 | +
|
| 103 | + - Original response: Propagates HTTP response returned from the next middleware if validation succeeds |
| 104 | + - HTTP 400: Payload or response failed JSON Schema validation |
| 105 | + - HTTP 500: JSON Schema provided has incorrect format |
| 106 | + """ |
| 107 | + try: |
| 108 | + validate(event=app.current_event.json_body, schema=self.inbound_schema, formats=self.inbound_formats) |
| 109 | + except SchemaValidationError as error: |
| 110 | + return self.bad_request(error) |
| 111 | + except InvalidSchemaFormatError as error: |
| 112 | + return self.bad_config(error) |
| 113 | + |
| 114 | + result = next_middleware(app) |
| 115 | + |
| 116 | + if self.outbound_formats is not None: |
| 117 | + try: |
| 118 | + validate(event=result.body, schema=self.inbound_schema, formats=self.inbound_formats) |
| 119 | + except SchemaValidationError as error: |
| 120 | + return self.bad_response(error) |
| 121 | + except InvalidSchemaFormatError as error: |
| 122 | + return self.bad_config(error) |
| 123 | + |
| 124 | + return result |
0 commit comments