Skip to content
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

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

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
28 changes: 26 additions & 2 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
VPCLatticeEventV2,
)
from aws_lambda_powertools.utilities.data_classes.common import BaseProxyEvent
from aws_lambda_powertools.utilities.data_classes.shared_functions import get_header_value
from aws_lambda_powertools.utilities.typing import LambdaContext

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -217,6 +218,27 @@ def to_dict(self, origin: Optional[str]) -> Dict[str, str]:
headers["Access-Control-Allow-Credentials"] = "true"
return headers

@staticmethod
def extract_origin_header(resolver_headers: Dict):
"""
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(resolver_headers, "origin", None, case_sensitive=False)
if isinstance(resolved_header, str):
return resolved_header
if isinstance(resolved_header, list):
return resolved_header[0]

return resolved_header


class Response(Generic[ResponseT]):
"""Response data class that provides greater control over what is returned from the proxy event"""
Expand Down Expand Up @@ -782,7 +804,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 = cors.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 +2152,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 = self._cors.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
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