-
Notifications
You must be signed in to change notification settings - Fork 429
feat(parser): add support for API Gateway HTTP API #434 #441
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
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
aws_lambda_powertools/utilities/parser/envelopes/apigwv2.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import logging | ||
from typing import Any, Dict, Optional, Type, Union | ||
|
||
from ..models import APIGatewayProxyEventV2Model | ||
from ..types import Model | ||
from .base import BaseEnvelope | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class ApiGatewayV2Envelope(BaseEnvelope): | ||
"""API Gateway V2 envelope to extract data within body key""" | ||
|
||
def parse(self, data: Optional[Union[Dict[str, Any], Any]], model: Type[Model]) -> Optional[Model]: | ||
"""Parses data found with model provided | ||
|
||
Parameters | ||
---------- | ||
data : Dict | ||
Lambda event to be parsed | ||
model : Type[Model] | ||
Data model provided to parse after extracting data using envelope | ||
|
||
Returns | ||
------- | ||
Any | ||
Parsed detail payload with model provided | ||
""" | ||
logger.debug(f"Parsing incoming data with Api Gateway model V2 {APIGatewayProxyEventV2Model}") | ||
parsed_envelope = APIGatewayProxyEventV2Model.parse_obj(data) | ||
logger.debug(f"Parsing event payload in `detail` with {model}") | ||
return self._parse(data=parsed_envelope.body, model=model) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
from datetime import datetime | ||
from typing import Any, Dict, List, Optional | ||
|
||
from pydantic import BaseModel, Field | ||
from pydantic.networks import IPvAnyNetwork | ||
|
||
from ..types import Literal | ||
|
||
|
||
class RequestContextV2AuthorizerIamCognito(BaseModel): | ||
amr: List[str] | ||
identityId: str | ||
identityPoolId: str | ||
|
||
|
||
class RequestContextV2AuthorizerIam(BaseModel): | ||
accessKey: Optional[str] | ||
accountId: Optional[str] | ||
callerId: Optional[str] | ||
principalOrgId: Optional[str] | ||
userArn: Optional[str] | ||
userId: Optional[str] | ||
cognitoIdentity: RequestContextV2AuthorizerIamCognito | ||
|
||
|
||
class RequestContextV2AuthorizerJwt(BaseModel): | ||
claims: Dict[str, Any] | ||
scopes: List[str] | ||
|
||
|
||
class RequestContextV2Authorizer(BaseModel): | ||
jwt: Optional[RequestContextV2AuthorizerJwt] | ||
iam: Optional[RequestContextV2AuthorizerIam] | ||
lambda_value: Optional[Dict[str, Any]] = Field(None, alias="lambda") | ||
|
||
|
||
class RequestContextV2Http(BaseModel): | ||
method: Literal["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] | ||
path: str | ||
protocol: str | ||
sourceIp: IPvAnyNetwork | ||
userAgent: str | ||
|
||
|
||
class RequestContextV2(BaseModel): | ||
accountId: str | ||
apiId: str | ||
authorizer: Optional[RequestContextV2Authorizer] | ||
domainName: str | ||
domainPrefix: str | ||
requestId: str | ||
routeKey: str | ||
stage: str | ||
property | ||
time: str | ||
timeEpoch: datetime | ||
http: RequestContextV2Http | ||
|
||
|
||
class APIGatewayProxyEventV2Model(BaseModel): | ||
version: str | ||
routeKey: str | ||
rawPath: str | ||
rawQueryString: str | ||
cookies: Optional[List[str]] | ||
headers: Dict[str, str] | ||
queryStringParameters: Dict[str, str] | ||
pathParameters: Optional[Dict[str, str]] | ||
stageVariables: Optional[Dict[str, str]] | ||
requestContext: RequestContextV2 | ||
body: str | ||
isBase64Encoded: bool |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
from aws_lambda_powertools.utilities.parser import envelopes, event_parser | ||
from aws_lambda_powertools.utilities.parser.models import ( | ||
APIGatewayProxyEventV2Model, | ||
RequestContextV2, | ||
RequestContextV2Authorizer, | ||
) | ||
from aws_lambda_powertools.utilities.typing import LambdaContext | ||
from tests.functional.parser.schemas import MyApiGatewayBusiness | ||
from tests.functional.utils import load_event | ||
|
||
|
||
@event_parser(model=MyApiGatewayBusiness, envelope=envelopes.ApiGatewayV2Envelope) | ||
def handle_apigw_with_envelope(event: MyApiGatewayBusiness, _: LambdaContext): | ||
assert event.message == "Hello" | ||
assert event.username == "Ran" | ||
|
||
|
||
@event_parser(model=APIGatewayProxyEventV2Model) | ||
def handle_apigw_event(event: APIGatewayProxyEventV2Model, _: LambdaContext): | ||
return event | ||
|
||
|
||
def test_apigw_v2_event_with_envelope(): | ||
event = load_event("apiGatewayProxyV2Event.json") | ||
event["body"] = '{"message": "Hello", "username": "Ran"}' | ||
handle_apigw_with_envelope(event, LambdaContext()) | ||
|
||
|
||
def test_apigw_v2_event_jwt_authorizer(): | ||
event = load_event("apiGatewayProxyV2Event.json") | ||
parsed_event: APIGatewayProxyEventV2Model = handle_apigw_event(event, LambdaContext()) | ||
assert parsed_event.version == event["version"] | ||
assert parsed_event.routeKey == event["routeKey"] | ||
assert parsed_event.rawPath == event["rawPath"] | ||
assert parsed_event.rawQueryString == event["rawQueryString"] | ||
assert parsed_event.cookies == event["cookies"] | ||
assert parsed_event.cookies[0] == "cookie1" | ||
assert parsed_event.headers == event["headers"] | ||
assert parsed_event.queryStringParameters == event["queryStringParameters"] | ||
assert parsed_event.queryStringParameters["parameter2"] == "value" | ||
|
||
request_context = parsed_event.requestContext | ||
assert request_context.accountId == event["requestContext"]["accountId"] | ||
assert request_context.apiId == event["requestContext"]["apiId"] | ||
assert request_context.authorizer.jwt.claims == event["requestContext"]["authorizer"]["jwt"]["claims"] | ||
assert request_context.authorizer.jwt.scopes == event["requestContext"]["authorizer"]["jwt"]["scopes"] | ||
assert request_context.domainName == event["requestContext"]["domainName"] | ||
assert request_context.domainPrefix == event["requestContext"]["domainPrefix"] | ||
|
||
http = request_context.http | ||
assert http.method == "POST" | ||
assert http.path == "/my/path" | ||
assert http.protocol == "HTTP/1.1" | ||
assert str(http.sourceIp) == "192.168.0.1/32" | ||
assert http.userAgent == "agent" | ||
|
||
assert request_context.requestId == event["requestContext"]["requestId"] | ||
assert request_context.routeKey == event["requestContext"]["routeKey"] | ||
assert request_context.stage == event["requestContext"]["stage"] | ||
assert request_context.time == event["requestContext"]["time"] | ||
convert_time = int(round(request_context.timeEpoch.timestamp() * 1000)) | ||
assert convert_time == event["requestContext"]["timeEpoch"] | ||
assert parsed_event.body == event["body"] | ||
assert parsed_event.pathParameters == event["pathParameters"] | ||
assert parsed_event.isBase64Encoded == event["isBase64Encoded"] | ||
assert parsed_event.stageVariables == event["stageVariables"] | ||
|
||
|
||
def test_api_gateway_proxy_v2_event_lambda_authorizer(): | ||
event = load_event("apiGatewayProxyV2LambdaAuthorizerEvent.json") | ||
parsed_event: APIGatewayProxyEventV2Model = handle_apigw_event(event, LambdaContext()) | ||
request_context: RequestContextV2 = parsed_event.requestContext | ||
assert request_context is not None | ||
lambda_props: RequestContextV2Authorizer = request_context.authorizer.lambda_value | ||
assert lambda_props is not None | ||
assert lambda_props["key"] == "value" | ||
|
||
|
||
def test_api_gateway_proxy_v2_event_iam_authorizer(): | ||
event = load_event("apiGatewayProxyV2IamEvent.json") | ||
parsed_event: APIGatewayProxyEventV2Model = handle_apigw_event(event, LambdaContext()) | ||
iam = parsed_event.requestContext.authorizer.iam | ||
assert iam is not None | ||
assert iam.accessKey == "ARIA2ZJZYVUEREEIHAKY" | ||
assert iam.accountId == "1234567890" | ||
assert iam.callerId == "AROA7ZJZYVRE7C3DUXHH6:CognitoIdentityCredentials" | ||
assert iam.cognitoIdentity.amr == ["foo"] | ||
assert iam.cognitoIdentity.identityId == "us-east-1:3f291106-8703-466b-8f2b-3ecee1ca56ce" | ||
assert iam.cognitoIdentity.identityPoolId == "us-east-1:4f291106-8703-466b-8f2b-3ecee1ca56ce" | ||
assert iam.principalOrgId == "AwsOrgId" | ||
assert iam.userArn == "arn:aws:iam::1234567890:user/Admin" | ||
assert iam.userId == "AROA2ZJZYVRE7Y3TUXHH6" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.