Skip to content

feat(data-classes): AppSync Lambda authorizer event #610

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 14 commits into from
Aug 16, 2021

Conversation

michaelbrewer
Copy link
Contributor

@michaelbrewer michaelbrewer commented Aug 14, 2021

Issue #, if available:

Description of changes:

Change:

  • Add test fixtures for request and response
  • Add Request event source
  • Add correlation_id APPSYNC_AUTHORIZER
  • Add Response helper
  • Add docs

Example usage:

from typing import Dict

from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.logging.logger import Logger
from aws_lambda_powertools.utilities.data_classes.appsync_authorizer_event import (
    AppSyncAuthorizerEvent,
    AppSyncAuthorizerResponse,
)
from aws_lambda_powertools.utilities.data_classes.event_source import event_source

logger = Logger()


def get_user_by_token(token: str):
    """Look a user by token"""


@logger.inject_lambda_context(correlation_id_path=correlation_paths.APPSYNC_AUTHORIZER)
@event_source(data_class=AppSyncAuthorizerEvent)
def lambda_handler(event: AppSyncAuthorizerEvent, context) -> Dict:
    user = get_user_by_token(event.authorization_token)

    if not user:
        # No user found, return not authorized
        return AppSyncAuthorizerResponse().to_dict()

    return AppSyncAuthorizerResponse(
        authorize=True,
        resolver_context={"id": user.id},
        # Only allow admins to delete events
        deny_fields=None if user.is_admin else ["Mutation.deleteEvent"],
    ).asdict()

Checklist

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@pull-request-size pull-request-size bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Aug 14, 2021
@codecov-commenter
Copy link

codecov-commenter commented Aug 14, 2021

Codecov Report

Merging #610 (18c09aa) into develop (f7cd398) will increase coverage by 0.00%.
The diff coverage is 100.00%.

Impacted file tree graph

@@           Coverage Diff            @@
##           develop     #610   +/-   ##
========================================
  Coverage    99.95%   99.95%           
========================================
  Files          113      114    +1     
  Lines         4535     4579   +44     
  Branches       246      249    +3     
========================================
+ Hits          4533     4577   +44     
  Partials         2        2           
Impacted Files Coverage Δ
aws_lambda_powertools/logging/correlation_paths.py 100.00% <100.00%> (ø)
...utilities/data_classes/appsync_authorizer_event.py 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update f7cd398...18c09aa. Read the comment docs.

@pull-request-size pull-request-size bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Aug 15, 2021
@michaelbrewer
Copy link
Contributor Author

@heitorlessa - i am not sure if fluent apis is a thing in Python? Maybe just optionals?

@gwlester
Copy link
Contributor

How does this tie in with

app.resolve(event, context)


@michaelbrewer
Copy link
Contributor Author

How does this tie in with

app.resolve(event, context)

--


@gwlester - this applies to AppSync only. API gateway use case would be based on how this is implemented.

Copy link
Contributor

@heitorlessa heitorlessa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Some minor changes. Should we have a method to ease adding a fully qualified field name?

Because we're mimicking the data classes, I think we can set some good defaults, correct the constructor, and simply get rid of self._data.

If we do add a method to add a fully qualified field, we can make a nice experience in the AppSync Handler since we would know both API ID and Region to construct the ARN while also making it standalone ;)

    def __init__(
        self,
        authorize: bool = False,
        max_age: int = 300,
        resolver_context: Optional[Dict[str, Any]] = None,
        deny_fields: Optional[List[str]] = None,
    ):
        self.authorize = authorize
    	self.max_age = max_age
        self.resolver_context = resolver_context or {}
        self.deny_fields = deny_fields or []
        
   def to_dict(self) -> dict:
       """Return the response as dict"""
       return {
           "isAuthorized": self.authorize,
           "resolverContext": json.dumps(self.resolver_context),
           "ttlOverride": self.max_age,
           "deniedFields": self.deny_fields
       }

@heitorlessa heitorlessa self-assigned this Aug 15, 2021
@heitorlessa heitorlessa added this to the 1.20.0 milestone Aug 15, 2021
@boring-cyborg boring-cyborg bot added the documentation Improvements or additions to documentation label Aug 16, 2021
@heitorlessa heitorlessa added the feature New feature or functionality label Aug 16, 2021
@heitorlessa heitorlessa changed the title feat(event-sources): AppSync lambda authorizer event feat(data-classes): AppSync Lambda authorizer event Aug 16, 2021
@heitorlessa heitorlessa merged commit 0258400 into aws-powertools:develop Aug 16, 2021
@michaelbrewer michaelbrewer deleted the feat-appsync-authorizer branch August 16, 2021 17:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation feature New feature or functionality size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants