Stuck with a Cognito Post-Confirmation Lambda trigger that does not work!

0

Hello guys, I have written a Lambda function of a few Python lines which, when it try to assign a self-registered user to a default group immediately after registration, tells me that the user does not exist. The Lambda, has a role with the following permissions:

  • cognito-idp:AdminGetUser
  • cognito-idp:ListUsers
  • cognito-idp:GetGroup
  • cognito-idp:AdminAddUserToGroup

When a person self-registers, the user is set into the User Pool, then confirmed by sending/receiving the activation code. Unfortunately the Lambda trigger returns an error and does not add the user the group.

This is the Lambda I'm using:

    import boto3
    def lambda_handler(event, context):
    try:

    # Log the entire event to inspect its structure

    print(f"Received event: {event}")

    # Extract user information from the event

    user_attributes = event.get("request", {}).get("userAttributes", {})

    # Log the userAttributes dictionary

    print(f"userAttributes: {user_attributes}")

    # Check if 'sub' is present in userAttributes

    if "sub" not in user_attributes:

        raise ValueError("User ID (sub) not found in userAttributes")

    username = user_attributes["sub"]  # User ID

    # Add the user to the "default" group in Cognito User Pool

    user_pool_id = "eu-south-1_*********"

    group_name = "users"

    client = boto3.client("cognito-idp")

    # Check if the user exists before adding to the group

    try:

        client.admin_get_user(UserPoolId=user_pool_id, Username=username)

    except client.exceptions.UserNotFoundException:

        print(f"User {username} not found in the User Pool. Skipping group assignment.")

        return event

    # Add the user to the group

    response = client.admin_add_user_to_group( UserPoolId=user_pool_id, Username=username, GroupName=group_name )

    print(f"User {username} added to group {group_name}")

    return event

# except ValueError(s) are omitted. . . 

For the sake of completeness, I also enclose the entire set of logged events:

START RequestId: d5d3be28-70e5-4f56-ad12-48b2f26bdf00 Version: $LATEST Received event: { 'version': '1', 'region': 'eu-south-1', 'userPoolId': 'eu-south-1_#########, 'userName': 'G**.N***', 'callerContext': { 'awsSdkVersion': 'aws-sdk-unknown-unknown', 'clientId': '5sqdae#########' }, 'triggerSource': 'PostConfirmation_ConfirmSignUp', 'request': { userAttributes': { 'sub': 'f6ce52c0-1091-7032-8f7b-353e8ae07cc9', 'email_verified': 'true', 'cognito:user_status': 'CONFIRMED', 'name': 'Giselle Normand', 'email': 'g***@***.com' } }, 'response': {} }

userAttributes: {'sub': 'f6ce52c0-1091-7032-8f7b-353e8ae07cc9', 'email_verified': 'true', 'cognito:user_status': 'CONFIRMED', 'name': 'Giselle Normand', 'email': 'g***@***.com'}

User f6ce52c0-1091-7032-8f7b-353e8ae07cc9 not found in the User Pool. Skipping group assignment.**

END RequestId: d5d3be28-70e5-4f56-ad12-48b2f26bdf00

Any idea why this Lambda fails?

THX Ste

PS I can't understand the reason of: 'aws-sdk-unknown'; everything runs within AWS services and BOTO3 is the latest AWS-SDK for Python PS2 be forgiving, per cortesia, this is the first time I got my hands on AWS

Ste
asked 4 months ago230 views
3 Answers
0
  1. I see that your logs include personal identifiable data. Please consider redacting UserName, name and email from your post.
  2. The documentation for the admin-get-user API (and others that take the username argument) it says that you can use the sub under the condition that the username isn't an alias attribute in your user pool. I would assume that is what fails you in this case - the sub is not recognized as the username.

I think you have two options from here: Option 1: check the users in your UserPool for what value is stored in the username field. If it is a value that you can retrieve from the request details, provide it in the API call accordingly. Or make sure your UserPool stores a unique value that you can retrieve from the request details, like email. Option 2: use the list-users API and filter for the sub attribute or any other unique identifier you can retrieve from the request details.

(Not sure about the "aws-sdk-unknown-unknown" but should not be relevant for this to otherwise work.)

profile pictureAWS
Martin
answered 4 months ago
  • I will try Option #1, THX As for the personal data, don't worry, they are fake, I edited them before publishing them.

0

How did it go? Were you able to resolve the issue?

Even if the user information is fake, it would be better to redact it, replace it with common placeholders (Jon/ Jane Doe, or localized equivalents, with example.com domain) or mask it (g***@.). There is a very small but non-zero chance that a user with these details may exist in the future.

profile pictureAWS
Martin
answered 4 months ago
0

Fixed! As usual devil is in details, I had forgotten to add an important statement after “import boto3”

client = boto3.client(‘cognito-idp’; region_name=‘*****’)

“All is well that ends well!”

Thank you all

Ste
answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions