aws / aws-sdk-js

AWS SDK for JavaScript in the browser and Node.js
https://aws.amazon.com/developer/language/javascript/
Apache License 2.0
7.59k stars 1.55k forks source link

"InvalidIdentityPoolConfigurationException" when getting credentials #4112

Closed richardbullin closed 4 hours ago

richardbullin commented 2 years ago

Describe the bug

I have an S3 bucket which all of my customers data is stored in, the first "folder" level is made up of the Cognito Identity Id for each customer and my IAM policies have been setup so each user can only access the items from their own directories, this all works fine.

I'm trying to allow my customers to share their S3 directories with each other by making use of attributes as described in this article https://docs.aws.amazon.com/cognito/latest/developerguide/attributes-for-access-control.html, I have setup Principle tags in my Cognito Identity pool:

image

I have setup IAM policy to make use of these tags

tempsnip

I have a Cognito PreToken generation lambda setup to add the S3 share paths to the JWT, as an example:

  const S3_KEY_TO_SHARE = '<USER1_IDENTITY_ID>/Folder/Another Folder';
  const S3_KEY_TO_SHARE2 = '<USER2_IDENTITY_ID>/Folder/Another Folder';

  event.response = {
    "claimsOverrideDetails": {
      "claimsToAddOrOverride": {
        'ROShare10': S3_KEY_TO_SHARE,
        'ROShare8': S3_KEY_TO_SHARE2,
      },
    }
  };

  callback(null, event); // Return to Amazon Cognito

I can successfully access another users data via this mechanism but depending on the value of the attribute (S3 share path) you can get a "InvalidIdentityPoolConfigurationException" when trying to setup the credentials (code used on client side can be found under the Reprodution Steps section below).

Referring to https://docs.aws.amazon.com/cognito/latest/developerguide/tagging.html#tagging-restrictions I narrowed down one cause of this to be when some characters were in the s3 path which aren't allowed (i.e. round brackets, please allow use of round brackets though as they are used quite often in "folder" names).

The part I can't figure out is related to the length of the values, the previous URL says that the maximum attribute value length can be 256 unicode characters. With just one share attribute added to the JWT and putting some random text into the value it worked up to 255 unicode chars before I would start getting the "InvalidIdentityPoolConfigurationException", changing the contents of the jwt claims would change whether or not this exception occurs. The below shows various pre token lambda claims which worked and didnt work.


// With 255 unicode chars in the attribute value for 'ROShare1' it works, the size of the JWT is 1541 bytes
event.response = {
  "claimsOverrideDetails": {
    "claimsToAddOrOverride": {
      'ROShare1': 'This can be caused by having invalid characters in the JWT Cognito Principal tag values which are currently setThis can be caused by having invalid characters in the JWT Cognito Principal tag values which are currently setThis canThisROShare2Taassssrtz255',
    },
  }
};

// With 256 unicode chars in the attribute value for 'ROShare1' it DOESNT work, the size of the JWT is 1542 bytes
event.response = {
  "claimsOverrideDetails": {
    "claimsToAddOrOverride": {
      'ROShare1': 'This can be caused by having invalid characters in the JWT Cognito Principal tag values which are currently setThis can be caused by having invalid characters in the JWT Cognito Principal tag values which are currently setThis canThisROShare2Taassssrtzz256',
    },
  }
};

// Using two claims , one of length 107 and the other of 150 unicode chars in the attribute value for 'ROShare1' and 'ROShare2' it DOESNT work, the size of the JWT is 1562 bytes
event.response = {
  "claimsOverrideDetails": {
    "claimsToAddOrOverride": {
      'ROShare1': 'characters in the JWT Cognito Principal tag values which are currently setThis canThisROShare2Taassssrtz107',
      'ROShare2': 'This can be caused by having invalid characters in the JWT Cognito Principal tag values which are currently setThis can be caused by having invalid150'
    },
  }
};

As an aside it would be nice if the allowed attribute value length could be the same length as the allowed S3 key which is 1024 unicode chars?

Expected Behavior

To not have an error thrown and for the credentials to be correctly setup.

Current Behavior

Depending on the attribute value used a "InvalidIdentityPoolConfigurationException" error is generated with a message of "Invalid identity pool configuration. Check assigned IAM roles for this pool."

Reproduction Steps

The below client side code shows how I'm setting up (using TypeScript):


export function AuthenticateUser(): Promise<any>
{
  return new Promise<void>(
    (resolve, reject) =>
    {
      // Configure Amplify before kicking the application off
      const COOKIE_STORAGE_CONFIG = {
        domain: nsAWSConstants.COOKIE_DOMAIN, // REQUIRED - Cookie domain (only required if cookieStorage is provided)
        expires: undefined,  // OPTIONAL - Cookie expiration in days
        path: '/', // OPTIONAL - Cookie path
        sameSite: 'strict', // OPTIONAL "strict" | "lax" | none - See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
        secure: nsAWSConstants.COOKIE_SECURE // OPTIONAL - Cookie secure flag, Either true or false, indicating if the cookie transmission requires a secure protocol (https).
      };

      aws_amplify.default.configure({
        Auth: {
          identityPoolId: nsAWSConstants.IDENTITY_POOL_ID, // REQUIRED only for Federated Authentication - Amazon Cognito Identity Pool ID, refer to cognito federtated Identites in sydney and look at samepl code
          region: nsAWSConstants.AUTH_REGION, // REQUIRED - Amazon Cognito Region
          identityPoolRegion: nsAWSConstants.AUTH_REGION, // OPTIONAL - Amazon Cognito Federated Identity Pool Region, only requried if different from cognito region
          userPoolId: nsAWSConstants.USER_POOL_ID, // OPTIONAL - Amazon Cognito User Pool ID
          userPoolWebClientId: nsAWSConstants.WEB_CLIENT_ID, // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
          mandatorySignIn: false, // OPTIONAL - Enforce user authentication prior to accessing AWS resources or not
          cookieStorage: COOKIE_STORAGE_CONFIG, // OPTIONAL - Configuration for cookie storage
        },
      });

      aws_amplify.Auth.currentAuthenticatedUser()
        .then(
          async (user) =>
          {
            AUTH_USER = user;

            const INITIALISE_PROMISE = InitialiseS3UserCredentials();

            return INITIALISE_PROMISE;
          }
        )
        .then(
          () =>
          {
            const CREDENTIALS = AWS.config.credentials as AWS.Credentials;
            return CREDENTIALS.getPromise();
          }
        )
        .then(
          () =>
          {
            resolve();
          }
        )
        .catch(
          error =>
          {
            // error.code === 'InvalidIdentityPoolConfigurationException' is caught here
          });
    }
  );
}

export function InitialiseS3UserCredentials(): Promise<void>
{
  return new Promise<void>(
    (resolve, reject) =>
    {
      if (!AUTH_USER)
      {
        reject();
        return;
      }

      AUTH_USER.getSession(function (err, result)
      {
        if (!result)
        {
          reject();
          return;
        }

        const JWT_TOKEN = result.getIdToken().getJwtToken();
        const LOGINS_OBJ = {};

        LOGINS_OBJ[`cognito-idp.${nsAWSConstants.AUTH_REGION}.amazonaws.com/${nsAWSConstants.USER_POOL_ID}`] = JWT_TOKEN;

        AWS.config.update(
          {
            region: nsAWSConstants.AUTH_REGION,
            credentials: new AWS.CognitoIdentityCredentials(
              {
                IdentityPoolId: nsAWSConstants.IDENTITY_POOL_ID,
                Logins: LOGINS_OBJ,
              }
            )
          },
        );

        resolve();
      });
    });
}

Possible Solution

No response

Additional Information/Context

No response

SDK version used

2.1142.0

Environment details (OS name and version, etc.)

Windows 10 Pro v10.0.19043 Build 19043

ajredniwja commented 2 years ago

Hi @richardbullin thanks for opening this issue. This seems to be a client side issue not really with the SDK, the one thing I would check is the trust relationship for your identity pool id. See: https://docs.aws.amazon.com/cognito/latest/developerguide/role-trust-and-permissions.html

richardbullin commented 2 years ago

Hello @ajredniwja, thanks for looking into this!

I'm confident my setup is correct because it normally works and I only get this exception when I make changes to the JWT claims on the server side lambda with nothing on the client side changing, I can make this happen consistently.

I also assume my trust document is setup correctly because I can successfully access another users s3 folders which I normally cant do but only if a single claim is added to the JWT and is under 200 char length. Below is my trust relationship for authorized roles.

image

The error is returned after making a server side call to aws from within SDK.

Let me know if there is anything else I can provide to help?

Shubh-bhalla commented 2 years ago

I am having the exact same problem as you @richardbullin

aBurmeseDev commented 4 hours ago

Hi there - sorry for the long silence. As previously mentioned, this needs to be addressed on service side and I have reached out to Cognito team on your behalf.

Since there's no action item for SDK team and this repo is dedicated only for SDK related issue, I'm going to close this. You can follow up by reaching out to service team directly via AWS Support.