aws-amplify / amplify-flutter

A declarative library with an easy-to-use interface for building Flutter applications on AWS.
https://docs.amplify.aws
Apache License 2.0
1.32k stars 247 forks source link

Error when uploading images with logged-in user: Invalid identity pool configuration. Check assigned IAM roles for this pool. #5304

Open freidev opened 2 months ago

freidev commented 2 months ago

Description

I'm encountering an issue while using the amplify_storage_s3 package in a Flutter application. The issue occurs under the following circumstances:

  1. When the user is not logged in, I can upload images to S3 without any problems.
  2. However, once the user is logged in, attempting to upload an image results in the following error: Invalid identity pool configuration. Check assigned IAM roles for this pool.

Expected Behavior:

I expect to be able to upload images to S3 whether the user is logged in or not.

Environment:

Possible Cause:

The error suggests there might be an issue with the identity pool configuration and the assigned IAM roles. It seems that the configuration used for the authenticated user does not have the correct permissions or is misconfigured.

Actions Taken:

Additional Comments:

Any guidance or solution on how to resolve this issue would be greatly appreciated. Thank you for your help!

Categories

Steps to Reproduce

  1. Set up a Flutter application using the amplify_storage_s3 package.
  2. Attempt to upload an image when the user is not logged in (works correctly).
  3. Log the user in using Amplify.Auth.signIn.
  4. Attempt to upload an image again (the mentioned error occurs).

Screenshots

No response

Platforms

Flutter Version

3.24.0

Amplify Flutter Version

2.3.0

Deployment Method

Amplify CLI

Schema

No response

khatruong2009 commented 2 months ago

Hi @freidev, thank you for submitting this issue. We will take a look at this issue and get back to you when we have any updates or questions.

khatruong2009 commented 2 months ago

Hi @freidev, did you use the CLI to set up your amplify project or did you use the Gen 2 backend?

freidev commented 2 months ago

I tried both methods, I'm currently using Gen 2

On Fri, Aug 16, 2024 at 6:02 PM Kha Truong @.***> wrote:

Hi @freidev https://github.com/freidev, did you use the CLI to set up your amplify project or did you use the Gen 2 backend?

— Reply to this email directly, view it on GitHub https://github.com/aws-amplify/amplify-flutter/issues/5304#issuecomment-2294368693, or unsubscribe https://github.com/notifications/unsubscribe-auth/ANBD4AJ7O7PYS3A5SFCJ7SLZRZZIDAVCNFSM6AAAAABMS4XSP6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDEOJUGM3DQNRZGM . You are receiving this because you were mentioned.Message ID: @.***>

NikaHsn commented 2 months ago

@freidev would you please

freidev commented 2 months ago

Thank you for the response. Below, I am sharing the requested information along with additional details about the issue we are facing.

Gen 1 Configuration

The original project in Amplify was configured some time ago using the following settings (with sensitive information removed):

{
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify-cli/0.1.0",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CredentialsProvider": {
                    "CognitoIdentity": {
                        "Default": {
                            "PoolId": "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                            "Region": "us-east-1"
                        }
                    }
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "us-east-1_xxxxxxxxx",
                        "AppClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
                        "Region": "us-east-1"
                    }
                },
                "Auth": {
                    "Default": {
                        "authenticationFlowType": "USER_SRP_AUTH",
                        "socialProviders": [],
                        "usernameAttributes": [],
                        "signupAttributes": [],
                        "passwordProtectionSettings": {
                            "passwordPolicyMinLength": 8,
                            "passwordPolicyCharacters": [
                                "REQUIRES_LOWERCASE",
                                "REQUIRES_UPPERCASE",
                                "REQUIRES_NUMBERS",
                                "REQUIRES_SYMBOLS"
                            ]
                        },
                        "mfaConfiguration": "OFF",
                        "mfaTypes": [],
                        "verificationMechanisms": []
                    }
                },
                "S3TransferUtility": {
                    "Default": {
                        "Bucket": "xxxx-app-staging",
                        "Region": "us-east-1"
                    }
                }
            }
        }
    },
    "storage": {
        "plugins": {
            "awsS3StoragePlugin": {
                "bucket": "xxxx-app-staging",
                "region": "us-east-1",
                "defaultAccessLevel": "guest"
            }
        }
    }
}

Gen 2 Configuration

We recently tested with the Gen 2 configuration, and this works correctly. Here is the configuration (also with sensitive information removed):

{
  "auth": {
    "user_pool_id": "us-east-1_xxxxxxxxx",
    "aws_region": "us-east-1",
    "user_pool_client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "identity_pool_id": "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "mfa_methods": [],
    "standard_required_attributes": [
      "email"
    ],
    "username_attributes": [
      "email"
    ],
    "user_verification_types": [
      "email"
    ],
    "mfa_configuration": "NONE",
    "password_policy": {
      "min_length": 8,
      "require_lowercase": true,
      "require_numbers": true,
      "require_symbols": true,
      "require_uppercase": true
    },
    "unauthenticated_identities_enabled": true
  },
  "data": {
    "url": "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
    "aws_region": "us-east-1",
    "default_authorization_type": "AWS_IAM",
    "authorization_types": [
      "AMAZON_COGNITO_USER_POOLS"
    ],
    "model_introspection": {
      "version": 1,
      "models": {
        "Todo": {
          "name": "Todo",
          "fields": {
            "id": {
              "name": "id",
              "isArray": false,
              "type": "ID",
              "isRequired": true,
              "attributes": []
            },
            "content": {
              "name": "content",
              "isArray": false,
              "type": "String",
              "isRequired": false,
              "attributes": []
            },
            "createdAt": {
              "name": "createdAt",
              "isArray": false,
              "type": "AWSDateTime",
              "isRequired": false,
              "attributes": [],
              "isReadOnly": true
            },
            "updatedAt": {
              "name": "updatedAt",
              "isArray": false,
              "type": "AWSDateTime",
              "isRequired": false,
              "attributes": [],
              "isReadOnly": true
            }
          },
          "syncable": true,
          "pluralName": "Todos",
          "attributes": [
            {
              "type": "model",
              "properties": {}
            },
            {
              "type": "auth",
              "properties": {
                "rules": [
                  {
                    "allow": "public",
                    "provider": "iam",
                    "operations": [
                      "create",
                      "update",
                      "delete",
                      "read"
                    ]
                  }
                ]
              }
            }
          ],
          "primaryKeyInfo": {
            "isCustomPrimaryKey": false,
            "primaryKeyFieldName": "id",
            "sortKeyFieldNames": []
          }
        }
      },
      "enums": {},
      "nonModels": {}
    }
  },
  "storage": {
    "aws_region": "us-east-1",
    "bucket_name": "amplify-xxxx-xxxx-xxxxxx-amplifyteamdrivebucket28-xxxxxxxxxxxx",
    "buckets": [
      {
        "name": "amplifyTeamDrive",
        "bucket_name": "amplify-xxxx-xxxx-xxxxxx-amplifyteamdrivebucket28-xxxxxxxxxxxx",
        "aws_region": "us-east-1"
      }
    ]
  },
  "version": "1.1"
}

Issue

The problem lies in the fact that the Gen 1 configuration (the original for the project) does not work correctly, while the Gen 2 configuration does. This presents a challenge since the Amplify project was created some time ago and is based on the Gen 1 setup.

File Upload Function

Here is the code snippet I use for uploading files in the app, for both types of users, authenticated and unauthenticated:

import 'dart:io';
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_storage_s3/amplify_storage_s3.dart';
import 'package:aws_common/vm.dart';
import 'package:file_picker/file_picker.dart';

Future<void> uploadFile() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.image,
      withReadStream: true,
      withData: false,
    );

    if (result == null) {
      safePrint('No file selected');
      return;
    }

    final platformFile = result.files.single;

    try {
      await Amplify.Storage.uploadFile(
        localFile: AWSFile.fromStream(
          platformFile.readStream!,
          size: platformFile.size,
        ),
        path: StoragePath.fromString('public/${platformFile.name}'),
        onProgress: (p) => safePrint(
          'Uploading: ${p.transferredBytes}/${p.totalBytes}',
        ),
      ).result;
    } on StorageException catch (e) {
      safePrint('Error uploading file - ${e.message}');
    }
  }
NikaHsn commented 2 months ago

@freidev thanks for providing these details. Do you use different s3 buckets for Gen 1 and Gen 2 backend? can you share the access level for Gen 1 bucket and Gen 2 bucket. I suspect that you may not have the create/write access for auth users on the Gen 1 storage bucket. you may find the access level for Gen 1 storage bucket in amplify/backend/storage/[friendly-category-name]/cli-inputs.json more info on setting up storage with CLI Gen 1 here for Gen 2 storage backend you may find the access level defined as part the call to defineStorage({...}) function in amplify/storage/resource.ts more info on setting up storage backend with CLI Gen 2 here