|
| 1 | +import warnings |
| 2 | +from collections import defaultdict |
| 3 | +from typing import Any, Dict, List, Union |
| 4 | + |
| 5 | + |
| 6 | +class BaseHeadersSerializer: |
| 7 | + """ |
| 8 | + Helper class to correctly serialize headers and cookies for Amazon API Gateway, |
| 9 | + ALB and Lambda Function URL response payload. |
| 10 | + """ |
| 11 | + |
| 12 | + def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[str]) -> Dict[str, Any]: |
| 13 | + """ |
| 14 | + Serializes headers and cookies according to the request type. |
| 15 | + Returns a dict that can be merged with the response payload. |
| 16 | +
|
| 17 | + Parameters |
| 18 | + ---------- |
| 19 | + headers: Dict[str, List[str]] |
| 20 | + A dictionary of headers to set in the response |
| 21 | + cookies: List[str] |
| 22 | + A list of cookies to set in the response |
| 23 | + """ |
| 24 | + raise NotImplementedError() |
| 25 | + |
| 26 | + |
| 27 | +class HttpApiHeadersSerializer(BaseHeadersSerializer): |
| 28 | + def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[str]) -> Dict[str, Any]: |
| 29 | + """ |
| 30 | + When using HTTP APIs or LambdaFunctionURLs, everything is taken care automatically for us. |
| 31 | + We can directly assign a list of cookies and a dict of headers to the response payload, and the |
| 32 | + runtime will automatically serialize them correctly on the output. |
| 33 | +
|
| 34 | + https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html#http-api-develop-integrations-lambda.proxy-format |
| 35 | + https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html#http-api-develop-integrations-lambda.response |
| 36 | + """ |
| 37 | + |
| 38 | + # Format 2.0 doesn't have multiValueHeaders or multiValueQueryStringParameters fields. |
| 39 | + # Duplicate headers are combined with commas and included in the headers field. |
| 40 | + combined_headers: Dict[str, str] = {} |
| 41 | + for key, values in headers.items(): |
| 42 | + if isinstance(values, str): |
| 43 | + combined_headers[key] = values |
| 44 | + else: |
| 45 | + combined_headers[key] = ", ".join(values) |
| 46 | + |
| 47 | + return {"headers": combined_headers, "cookies": cookies} |
| 48 | + |
| 49 | + |
| 50 | +class MultiValueHeadersSerializer(BaseHeadersSerializer): |
| 51 | + def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[str]) -> Dict[str, Any]: |
| 52 | + """ |
| 53 | + When using REST APIs, headers can be encoded using the `multiValueHeaders` key on the response. |
| 54 | + This is also the case when using an ALB integration with the `multiValueHeaders` option enabled. |
| 55 | + The solution covers headers with just one key or multiple keys. |
| 56 | +
|
| 57 | + https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format |
| 58 | + https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers-response |
| 59 | + """ |
| 60 | + payload: Dict[str, List[str]] = defaultdict(list) |
| 61 | + |
| 62 | + for key, values in headers.items(): |
| 63 | + if isinstance(values, str): |
| 64 | + payload[key].append(values) |
| 65 | + else: |
| 66 | + for value in values: |
| 67 | + payload[key].append(value) |
| 68 | + |
| 69 | + if cookies: |
| 70 | + payload.setdefault("Set-Cookie", []) |
| 71 | + for cookie in cookies: |
| 72 | + payload["Set-Cookie"].append(cookie) |
| 73 | + |
| 74 | + return {"multiValueHeaders": payload} |
| 75 | + |
| 76 | + |
| 77 | +class SingleValueHeadersSerializer(BaseHeadersSerializer): |
| 78 | + def serialize(self, headers: Dict[str, Union[str, List[str]]], cookies: List[str]) -> Dict[str, Any]: |
| 79 | + """ |
| 80 | + The ALB integration has `multiValueHeaders` disabled by default. |
| 81 | + If we try to set multiple headers with the same key, or more than one cookie, print a warning. |
| 82 | +
|
| 83 | + https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#respond-to-load-balancer |
| 84 | + """ |
| 85 | + payload: Dict[str, Dict[str, str]] = {} |
| 86 | + payload.setdefault("headers", {}) |
| 87 | + |
| 88 | + if cookies: |
| 89 | + if len(cookies) > 1: |
| 90 | + warnings.warn( |
| 91 | + "Can't encode more than one cookie in the response. Sending the last cookie only. " |
| 92 | + "Did you enable multiValueHeaders on the ALB Target Group?" |
| 93 | + ) |
| 94 | + |
| 95 | + # We can only send one cookie, send the last one |
| 96 | + payload["headers"]["Set-Cookie"] = cookies[-1] |
| 97 | + |
| 98 | + for key, values in headers.items(): |
| 99 | + if isinstance(values, str): |
| 100 | + payload["headers"][key] = values |
| 101 | + else: |
| 102 | + if len(values) > 1: |
| 103 | + warnings.warn( |
| 104 | + f"Can't encode more than one header value for the same key ('{key}') in the response. " |
| 105 | + "Did you enable multiValueHeaders on the ALB Target Group?" |
| 106 | + ) |
| 107 | + |
| 108 | + # We can only set one header per key, send the last one |
| 109 | + payload["headers"][key] = values[-1] |
| 110 | + |
| 111 | + return payload |
0 commit comments