Skip to content

Commit d28d84a

Browse files
fix(event_handler): add Vary: Accept-Encoding to responses of compressed routes (#8711)
* fix(event_handler): add Vary: Accept-Encoding to responses of compressed routes * refactor(event_handler): reuse the Vary helper for CORS and cover list-valued Vary CORS now goes through _add_vary too, which also stops it from emitting 'Origin, Origin' or '*, Origin' when the route already set Vary. --------- Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent 30ebaa4 commit d28d84a

2 files changed

Lines changed: 62 additions & 5 deletions

File tree

‎aws_lambda_powertools/event_handler/api_gateway.py‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -785,12 +785,23 @@ def _add_cors(self, event: ResponseEventT, cors: CORSConfig):
785785
if origin is not None:
786786
cors_headers = cors.to_dict(origin)
787787
# Keep any Vary value the route already set, and add Origin to it
788-
existing_vary = self.response.headers.get("Vary")
789-
if isinstance(existing_vary, list):
790-
existing_vary = ", ".join(existing_vary)
791-
if existing_vary and "Vary" in cors_headers:
792-
cors_headers["Vary"] = f"{existing_vary}, Origin"
788+
vary = cors_headers.pop("Vary", None)
793789
self.response.headers.update(cors_headers)
790+
if vary:
791+
self._add_vary(vary)
792+
793+
def _add_vary(self, field: str):
794+
"""Add a request header name to the Vary response header, keeping any value already set"""
795+
existing_vary = self.response.headers.get("Vary")
796+
if isinstance(existing_vary, list):
797+
existing_vary = ", ".join(existing_vary)
798+
if not existing_vary:
799+
self.response.headers["Vary"] = field
800+
return
801+
values = {value.strip().lower() for value in existing_vary.split(",")}
802+
# "*" already covers every request header
803+
if field.lower() not in values and "*" not in values:
804+
self.response.headers["Vary"] = f"{existing_vary}, {field}"
794805

795806
def _add_cache_control(self, cache_control: str):
796807
"""Set the specified cache control headers for 200 http responses. For non-200 `no-cache` is used."""
@@ -857,6 +868,10 @@ def _route(self, event: ResponseEventT, cors: CORSConfig | None):
857868
self._add_cors(event, cors or CORSConfig())
858869
if self.route.cache_control:
859870
self._add_cache_control(self.route.cache_control)
871+
compression = self.response.compress if self.response.compress is not None else self.route.compress
872+
if compression:
873+
# The body depends on Accept-Encoding, so shared caches must not reuse it across encodings
874+
self._add_vary("Accept-Encoding")
860875
if self._has_compression_enabled(
861876
route_compression=self.route.compress,
862877
response_compression=self.response.compress,

‎tests/functional/event_handler/required_dependencies/test_api_gateway.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,48 @@ def return_text() -> Response:
621621
assert result["body"] == expected_value
622622

623623

624+
@pytest.mark.parametrize(
625+
"route_compress, response_compress, response_headers, accept_encoding, expected_vary",
626+
[
627+
pytest.param(True, None, None, "gzip", ["Accept-Encoding"], id="compressed response"),
628+
pytest.param(True, None, None, "deflate", ["Accept-Encoding"], id="uncompressed response of a compress route"),
629+
pytest.param(False, True, None, "gzip", ["Accept-Encoding"], id="compress enabled on the response"),
630+
pytest.param(True, None, {"Vary": "Origin"}, "gzip", ["Origin, Accept-Encoding"], id="existing Vary kept"),
631+
pytest.param(True, None, {"Vary": "accept-encoding"}, "gzip", ["accept-encoding"], id="not added twice"),
632+
pytest.param(True, None, {"Vary": "*"}, "gzip", ["*"], id="wildcard Vary kept as is"),
633+
pytest.param(
634+
True,
635+
None,
636+
{"Vary": ["Accept", "Accept-Language"]},
637+
"gzip",
638+
["Accept, Accept-Language, Accept-Encoding"],
639+
id="existing Vary list kept",
640+
),
641+
pytest.param(False, None, None, "gzip", None, id="compression not enabled"),
642+
pytest.param(True, False, None, "gzip", None, id="compression disabled on the response"),
643+
],
644+
)
645+
def test_compress_sets_vary_accept_encoding(
646+
route_compress: bool,
647+
response_compress: bool | None,
648+
response_headers: dict | None,
649+
accept_encoding: str,
650+
expected_vary: list[str] | None,
651+
):
652+
# GIVEN a route whose body depends on the request Accept-Encoding when compression is enabled
653+
app = ApiGatewayResolver()
654+
655+
@app.get("/my/path", compress=route_compress)
656+
def return_text() -> Response:
657+
return Response(200, content_types.TEXT_PLAIN, "Foo", headers=response_headers, compress=response_compress)
658+
659+
# WHEN calling the event handler
660+
result = app({"path": "/my/path", "httpMethod": "GET", "headers": {"Accept-Encoding": accept_encoding}}, None)
661+
662+
# THEN Vary names Accept-Encoding whenever compression can change the body, so caches keep encodings apart
663+
assert result["multiValueHeaders"].get("Vary") == expected_vary
664+
665+
624666
@pytest.mark.parametrize(
625667
"accept_encoding, expected_compressed",
626668
[

0 commit comments

Comments
 (0)