From e545793be9f55d2973d1b19dcab0ac3547f0fa82 Mon Sep 17 00:00:00 2001 From: heitorlessa Date: Thu, 16 Jun 2022 15:54:47 +0200 Subject: [PATCH] fix(event-handler): ALB requires empty body but null for CORS preflight --- .../event_handler/api_gateway.py | 2 +- .../functional/event_handler/test_api_gateway.py | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/aws_lambda_powertools/event_handler/api_gateway.py b/aws_lambda_powertools/event_handler/api_gateway.py index e6d1af01dfc..78cee8f2051 100644 --- a/aws_lambda_powertools/event_handler/api_gateway.py +++ b/aws_lambda_powertools/event_handler/api_gateway.py @@ -595,7 +595,7 @@ def _not_found(self, method: str) -> ResponseBuilder: if method == "OPTIONS": logger.debug("Pre-flight request detected. Returning CORS with null response") headers["Access-Control-Allow-Methods"] = ",".join(sorted(self._cors_methods)) - return ResponseBuilder(Response(status_code=204, content_type=None, headers=headers, body=None)) + return ResponseBuilder(Response(status_code=204, content_type=None, headers=headers, body="")) handler = self._lookup_exception_handler(NotFoundError) if handler: diff --git a/tests/functional/event_handler/test_api_gateway.py b/tests/functional/event_handler/test_api_gateway.py index 1ca28f869cf..0c6d1954836 100644 --- a/tests/functional/event_handler/test_api_gateway.py +++ b/tests/functional/event_handler/test_api_gateway.py @@ -236,6 +236,19 @@ def handler(event, context): assert "Access-Control-Allow-Origin" not in result["headers"] +def test_cors_preflight_body_is_empty_not_null(): + # GIVEN CORS is configured + app = ALBResolver(cors=CORSConfig()) + + event = {"path": "/my/request", "httpMethod": "OPTIONS"} + + # WHEN calling the event handler + result = app(event, {}) + + # THEN there body should be empty strings + assert result["body"] == "" + + def test_compress(): # GIVEN a function that has compress=True # AND an event with a "Accept-Encoding" that include gzip @@ -485,7 +498,7 @@ def post_no_cors(): # THEN return no content # AND include Access-Control-Allow-Methods of the cors methods used assert result["statusCode"] == 204 - assert result["body"] is None + assert result["body"] == "" headers = result["headers"] assert "Content-Type" not in headers assert "Access-Control-Allow-Origin" in result["headers"]