Skip to content

Commit a7c2a75

Browse files
fix(event-handler): strip whitespace from Content-Type headers during OpenAPI schema validation (#3677)
Fixing problems with spaces in header
1 parent b2c1047 commit a7c2a75

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

aws_lambda_powertools/event_handler/middlewares/openapi_validation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def _get_body(self, app: EventHandlerInstance) -> Dict[str, Any]:
212212
"""
213213

214214
content_type_value = app.current_event.get_header_value("content-type")
215-
if not content_type_value or content_type_value.startswith("application/json"):
215+
if not content_type_value or content_type_value.strip().startswith("application/json"):
216216
try:
217217
return app.current_event.json_body
218218
except json.JSONDecodeError as e:

tests/functional/event_handler/test_openapi_validation_middleware.py

+26
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,32 @@ def handler(user: Model) -> Model:
289289
assert json.loads(result["body"]) == {"name": "John", "age": 30}
290290

291291

292+
def test_validate_body_param_with_stripped_headers():
293+
# GIVEN an APIGatewayRestResolver with validation enabled
294+
app = APIGatewayRestResolver(enable_validation=True)
295+
296+
class Model(BaseModel):
297+
name: str
298+
age: int
299+
300+
# WHEN a handler is defined with a body parameter
301+
# WHEN headers has spaces
302+
@app.post("/")
303+
def handler(user: Model) -> Model:
304+
return user
305+
306+
LOAD_GW_EVENT["httpMethod"] = "POST"
307+
LOAD_GW_EVENT["headers"] = {"Content-type": " application/json "}
308+
LOAD_GW_EVENT["path"] = "/"
309+
LOAD_GW_EVENT["body"] = json.dumps({"name": "John", "age": 30})
310+
311+
# THEN the handler should be invoked and return 200
312+
# THEN the body must be a JSON object
313+
result = app(LOAD_GW_EVENT, {})
314+
assert result["statusCode"] == 200
315+
assert json.loads(result["body"]) == {"name": "John", "age": 30}
316+
317+
292318
def test_validate_body_param_with_invalid_date():
293319
# GIVEN an APIGatewayRestResolver with validation enabled
294320
app = APIGatewayRestResolver(enable_validation=True)

0 commit comments

Comments
 (0)