Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
42 changes: 31 additions & 11 deletions templates/api/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
repository = Repository(settings.table_name)
app = APIGatewayRestResolver()

SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
}


@app.get("/items/<id>")
def get_item(id: str) -> Response:
Expand All @@ -32,17 +38,23 @@ def get_item(id: str) -> Response:
"""
try:
if (item := repository.get_item(id)) is None:
return Response(status_code=404, content_type="application/json", body=dumps({"message": "Not found"}))
return Response(
status_code=404,
content_type="application/json",
body=dumps({"message": "Not found"}),
headers=SECURITY_HEADERS,
)
item = Item.model_validate(item) # Validate model after retrieval to ensure data integrity
except Exception as exc:
message = (
"Item validation failed" if isinstance(exc, ValidationError) else f"Error retrieving item with id {id}"
)
logger.error(message, exc_info=exc)
message = "Item validation failed" if isinstance(exc, ValidationError) else "Error retrieving item"
logger.error(message, exc_info=exc, extra={"item_id": id})
return Response(
status_code=500, content_type="application/json", body=dumps({"message": "Internal server error"})
status_code=500,
content_type="application/json",
body=dumps({"message": "Internal server error"}),
headers=SECURITY_HEADERS,
)
return Response(status_code=200, content_type="application/json", body=item.dump())
return Response(status_code=200, content_type="application/json", body=item.dump(), headers=SECURITY_HEADERS)


@app.post("/items")
Expand All @@ -55,17 +67,25 @@ def create_item() -> Response:
try:
item = Item.model_validate_json(app.current_event.body)
except ValidationError as exc:
return Response(status_code=422, content_type="application/json", body=dumps({"errors": exc.errors()}))
return Response(
status_code=422,
content_type="application/json",
body=dumps({"errors": exc.errors()}),
headers=SECURITY_HEADERS,
)

try:
repository.put_item(item.model_dump())
except Exception as exc:
logger.error("DynamoDB put_item failed", exc_info=exc)
logger.error("DynamoDB put_item failed", exc_info=exc, extra={"item_id": item.id})
return Response(
status_code=500, content_type="application/json", body=dumps({"message": "Internal server error"})
status_code=500,
content_type="application/json",
body=dumps({"message": "Internal server error"}),
headers=SECURITY_HEADERS,
)

return Response(status_code=201, content_type="application/json", body=item.dump())
return Response(status_code=201, content_type="application/json", body=item.dump(), headers=SECURITY_HEADERS)


@logger.inject_lambda_context
Expand Down
16 changes: 16 additions & 0 deletions tests/api/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,21 @@ def test_get_item_validation_error_returns_500(mock_repo, lambda_context):
assert body["message"] == "Internal server error"


def test_response_headers_contain_security_headers(mock_repo, lambda_context):
"""API responses should contain standard security headers."""
from templates.api.handler import main

mock_repo.get_item.return_value = {"id": "abc", "name": "Widget"}

event = _apigw_event("GET", "/items/abc", path_params={"id": "abc"})
response = main(event, lambda_context)

assert response["statusCode"] == 200
headers = response["multiValueHeaders"]
assert headers["X-Content-Type-Options"] == ["nosniff"]
assert headers["X-Frame-Options"] == ["DENY"]
assert "Strict-Transport-Security" in headers


if __name__ == "__main__":
main()