Skip to content

Bug: REST response compression does not work when multiValueHeaders are enabled #6912

@kimsappi

Description

@kimsappi

Expected Behaviour

Response compression is possible when "multiValueHeaders" are enabled.

Current Behaviour

Compression does not work under any circumstances when "multiValueHeaders" are enabled.

Code snippet

import json
import unittest

from aws_lambda_powertools.event_handler import ALBResolver

app = ALBResolver()

@app.get("/poc", compress=True)
def test_poc():
    return {
        "statusCode": 200,
        "body": json.dumps({"foo": "bar"}),
    }

def lambda_handler(event, context):
    return app.resolve(event, context)

class TestLambdaHandler(unittest.TestCase):
    def setUp(self):
        self.event_base = {
            "httpMethod": "GET",
            "path": "/poc",
        }
        self.context = {}

    def test_lambda_handler_with_headers(self):
        event = self.event_base.copy()
        event["headers"] = {"accept-encoding": "gzip, deflate"}
        response = lambda_handler(event, self.context)
        assert "Content-Encoding" in response["headers"]

    def test_lambda_handler_with_multivalueheaders(self):
        event = self.event_base.copy()
        event["multiValueHeaders"] = {"accept-encoding": ["gzip", "deflate"]}
        response = lambda_handler(event, self.context)
        print(response)
        assert "multiValueHeaders" in response
        assert "headers" not in response
        assert "Content-Encoding" in response["multiValueHeaders"], response["multiValueHeaders"]

if __name__ == "__main__":
    unittest.main()

--
Result:

     assert "Content-Encoding" in response["multiValueHeaders"], response["multiValueHeaders"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: defaultdict(<class 'list'>, {'Content-Type': ['application/json']})

Possible Solution

This seems to stem from the compressibility request header check only checking event.headers:

encoding = event.headers.get("accept-encoding", "")

event.resolved_headers_field is more generic, but requires some additional processing (e.g. "gzip, deflate" can be a single header value within the sequence of event.multi_value_headers).

Steps to Reproduce

Code snippet above

Powertools for AWS Lambda (Python) version

latest

AWS Lambda function runtime

3.11

Packaging format used

PyPi

Debugging logs

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

Status

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions