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

Bug: APIGateWayProxyEvent.request_context.authorizer results in KeyError #4102

Closed
dirkdebruin opened this issue Apr 10, 2024 · 12 comments · Fixed by #4298
Closed

Bug: APIGateWayProxyEvent.request_context.authorizer results in KeyError #4102

dirkdebruin opened this issue Apr 10, 2024 · 12 comments · Fixed by #4298
Assignees
Labels
event_sources Event Source Data Class utility not-a-bug

Comments

@dirkdebruin
Copy link

dirkdebruin commented Apr 10, 2024

Expected Behaviour

returns authorizer dictionary

Current Behaviour

KeyError

Code snippet

powertools-lambda-python/aws_lambda_powertools/utilities/data_classes/api_gateway_proxy_event.py
line 94 in class APIGatewayEventRequestContext

 def authorizer(self) -> APIGatewayEventAuthorizer:
        return APIGatewayEventAuthorizer(self._data["requestContext"]["authorizer"])

Possible Solution

 def authorizer(self) -> APIGatewayEventAuthorizer:
        return APIGatewayEventAuthorizer(self.["requestContext"].get("authorizer"))

Steps to Reproduce

@event_source(data_class=APIGatewayProxyEvent)
def handler(event: APIGatewayProxyEvent, context):
    authorizer = event.request_context.authorizer

Powertools for AWS Lambda (Python) version

2.36.0

AWS Lambda function runtime

3.11

Packaging format used

PyPi

Debugging logs

No response

@dirkdebruin dirkdebruin added bug Something isn't working triage Pending triage from maintainers labels Apr 10, 2024
Copy link

boring-cyborg bot commented Apr 10, 2024

Thanks for opening your first issue here! We'll come back to you as soon as we can.
In the meantime, check out the #python channel on our Powertools for AWS Lambda Discord: Invite link

@rubenfonseca
Copy link
Contributor

Looking now

@rubenfonseca
Copy link
Contributor

Hi @dirkdebruin thank you for opening this issue!

It seems that you are trying to use the Event Source feature directly without using any event handler resolver, which is ok.

However, I need to understand more about which event source are you connecting this Lambda handler to.

Can you please clear this up for me? Alternatively you could also paste the input payload (redact any unwanted info) that is being passed to the Lambda handler? Thank you!

@rubenfonseca rubenfonseca added triage Pending triage from maintainers need-more-information Pending information to continue and removed triage Pending triage from maintainers labels Apr 10, 2024
@rubenfonseca rubenfonseca moved this from Triage to Pending customer in Powertools for AWS Lambda (Python) Apr 10, 2024
@rubenfonseca
Copy link
Contributor

Hi @dirkdebruin can you get me the information above so we can continue to debug the problem please?

@rubenfonseca rubenfonseca self-assigned this Apr 12, 2024
@rubenfonseca
Copy link
Contributor

Hi again @dirkdebruin happy to continue looking into this if you get me some more information :)

@AndreyNenashev
Copy link

Hey, @rubenfonseca! I'm actually having the similar issue with accessing to authorizer. When I'm trying to test it with cogntio auth token it throws authorizer KeyError. AWS cloudwatch truncates events in the log so I cannot provide valid usefull example. But I can say that it works if I try to access to authorizer without resolver - like this

def lambda_handler(event, context):
  username = event['requestContext']['authorizer']['claims']['cognito:username']

But using APIGatewayRestResolver causing the KeyError.
This is a code example:

app = APIGatewayRestResolver(cors=CORS_CONFIG, enable_validation=True)


def inject_feature_resolver_context(
        app_: APIGatewayRestResolver, next_middleware: NextMiddleware
) -> Response:
    user_email = app_.current_event.request_context.authorizer.claims.get('email')   // => throws KeyError for 'authorizer'
    params = {"user_email": user_email,  **app_.current_event.query_string_parameters}

    if params is not None:
        app_.append_context(feature_resolver_context=params)

    return next_middleware(app_)


@app.get('/v2/feature_flags', middlewares=[inject_feature_resolver_context])
def get_feature_flags():
    return FeatureResolver().get_enabled_features(
        context=app.context.get('feature_resolver_context')
    )

...

@heitorlessa
Copy link
Contributor

hey @AndreyNenashev -- does that happen at runtime (real invocation) or when testing only?

What we've been trying to get confirmation is whether:

A. There's a bug in the Event Source Data Class in accessing the authorizer key with real events

or

B. It fails with tests events as the authorizer key is not present.

For the former, the authorizer key must be present.

For the latter, we're looking to address this in multiple places: #2605

@heitorlessa
Copy link
Contributor

Quick update. @leandrodamascena is creating a stack to reproduce this with Cognito Authorizer to confirm. If we reproduce, we'll send a fix by having sane defaults here.

@heitorlessa
Copy link
Contributor

Leandro reproduced - it doesn't happen at runtime, the key authorizer is always present when there's an authorizer.

That said, we still need to make it safe to access a authorizer property and return an empty dictionary to prevent a KeyError when testing locally.

I'll get back to this as soon as I handle a runtime bug #4277

@heitorlessa heitorlessa added not-a-bug event_sources Event Source Data Class utility and removed bug Something isn't working need-more-information Pending information to continue labels May 8, 2024
@heitorlessa
Copy link
Contributor

Updated to not-a-bug to reflect our tests... however we'll include sane default values for container types (dict/list) to avoid this situation in non-prod.

That means accessing claims will return an empty dict if not available, or an empty list when accessing scopes and that isn't available, and so on.

@heitorlessa heitorlessa moved this from Pending customer to Pending review in Powertools for AWS Lambda (Python) May 8, 2024
@heitorlessa heitorlessa linked a pull request May 8, 2024 that will close this issue
11 tasks
@github-project-automation github-project-automation bot moved this from Pending review to Coming soon in Powertools for AWS Lambda (Python) May 9, 2024
Copy link
Contributor

github-actions bot commented May 9, 2024

⚠️COMMENT VISIBILITY WARNING⚠️

This issue is now closed. Please be mindful that future comments are hard for our team to see.

If you need more assistance, please either tag a team member or open a new issue that references this one.

If you wish to keep having a conversation with other community members under this issue feel free to do so.

@github-actions github-actions bot added the pending-release Fix or implementation already in dev waiting to be released label May 9, 2024
Copy link
Contributor

This is now released under 2.38.0 version!

@github-actions github-actions bot removed the pending-release Fix or implementation already in dev waiting to be released label May 17, 2024
@heitorlessa heitorlessa moved this from Coming soon to Shipped in Powertools for AWS Lambda (Python) Jun 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
event_sources Event Source Data Class utility not-a-bug
Projects
Status: Shipped
Development

Successfully merging a pull request may close this issue.

5 participants