Skip to content

fix(event_handler): CORS Origin for ALBResolver multi-headers #4385

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 22, 2024
Merged
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
8 changes: 5 additions & 3 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
validation_error_definition,
validation_error_response_definition,
)
from aws_lambda_powertools.event_handler.util import _FrozenDict
from aws_lambda_powertools.event_handler.util import _FrozenDict, extract_origin_header
from aws_lambda_powertools.shared.cookies import Cookie
from aws_lambda_powertools.shared.functions import powertools_dev_is_set
from aws_lambda_powertools.shared.json_encoder import Encoder
Expand Down Expand Up @@ -782,7 +782,8 @@ def __init__(

def _add_cors(self, event: ResponseEventT, cors: CORSConfig):
"""Update headers to include the configured Access-Control headers"""
self.response.headers.update(cors.to_dict(event.get_header_value("Origin")))
extracted_origin_header = extract_origin_header(event.resolved_headers_field)
self.response.headers.update(cors.to_dict(extracted_origin_header))

def _add_cache_control(self, cache_control: str):
"""Set the specified cache control headers for 200 http responses. For non-200 `no-cache` is used."""
Expand Down Expand Up @@ -2129,7 +2130,8 @@ def _not_found(self, method: str) -> ResponseBuilder:
headers = {}
if self._cors:
logger.debug("CORS is enabled, updating headers.")
headers.update(self._cors.to_dict(self.current_event.get_header_value("Origin")))
extracted_origin_header = extract_origin_header(self.current_event.resolved_headers_field)
headers.update(self._cors.to_dict(extracted_origin_header))

if method == "OPTIONS":
logger.debug("Pre-flight request detected. Returning CORS with null response")
Expand Down
29 changes: 29 additions & 0 deletions aws_lambda_powertools/event_handler/util.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
from typing import Any, Dict

from aws_lambda_powertools.utilities.data_classes.shared_functions import get_header_value


class _FrozenDict(dict):
"""
A dictionary that can be used as a key in another dictionary.
Expand All @@ -11,3 +16,27 @@ class _FrozenDict(dict):

def __hash__(self):
return hash(frozenset(self.keys()))


def extract_origin_header(resolver_headers: Dict[str, Any]):
"""
Extracts the 'origin' or 'Origin' header from the provided resolver headers.

The 'origin' or 'Origin' header can be either a single header or a multi-header.

Args:
resolver_headers (Dict): A dictionary containing the headers.

Returns:
Optional[str]: The value(s) of the origin header or None.
"""
resolved_header = get_header_value(
headers=resolver_headers,
name="origin",
default_value=None,
case_sensitive=False,
)
if isinstance(resolved_header, list):
return resolved_header[0]

return resolved_header
10 changes: 5 additions & 5 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ You can install Powertools for AWS Lambda (Python) using your favorite dependenc
=== "CDK"

```python hl_lines="13 19"
--8<-- "examples/homepage/install/x86_64/cdk.py"
--8<-- "examples/homepage/install/x86_64/cdk_x86.py"
```

=== "Terraform"
Expand All @@ -101,7 +101,7 @@ You can install Powertools for AWS Lambda (Python) using your favorite dependenc
=== "Pulumi"

```python hl_lines="21-27"
--8<-- "examples/homepage/install/x86_64/pulumi.py"
--8<-- "examples/homepage/install/x86_64/pulumi_x86.py"
```

=== "Amplify"
Expand All @@ -127,7 +127,7 @@ You can install Powertools for AWS Lambda (Python) using your favorite dependenc
=== "CDK"

```python hl_lines="13 19"
--8<-- "examples/homepage/install/arm64/cdk.py"
--8<-- "examples/homepage/install/arm64/cdk_arm64.py"
```

=== "Terraform"
Expand All @@ -139,7 +139,7 @@ You can install Powertools for AWS Lambda (Python) using your favorite dependenc
=== "Pulumi"

```python hl_lines="21-27"
--8<-- "examples/homepage/install/arm64/pulumi.py"
--8<-- "examples/homepage/install/arm64/pulumi_arm64.py"
```

=== "Amplify"
Expand Down Expand Up @@ -275,7 +275,7 @@ Compared with the [public Layer ARN](#lambda-layer) option, SAR allows you to ch
=== "CDK"

```python hl_lines="7 16-20 23-27"
--8<-- "examples/homepage/install/sar/cdk.py"
--8<-- "examples/homepage/install/sar/cdk_sar.py"
```

=== "Terraform"
Expand Down
6 changes: 6 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ disable_error_code = annotation-unchecked
[mypy-jmespath]
ignore_missing_imports=True

[mypy-pulumi.*]
ignore_missing_imports=True

[mypy-pulumi_aws.*]
ignore_missing_imports=True

[mypy-aws_encryption_sdk.*]
ignore_missing_imports=True

Expand Down
3 changes: 3 additions & 0 deletions tests/events/apiGatewayProxyEvent.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"Header1": [
"value1"
],
"Origin": [
"https://aws.amazon.com"
],
"Header2": [
"value1",
"value2"
Expand Down