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 246 forks source link

DataStore Authorization rule with owner doesn't work #2515

Closed skim037 closed 9 months ago

skim037 commented 1 year ago

Description

I've been trying to apply owner strategy to restrict the access to data but it hasn't been successful so far.

I have a model that looks like this

type Profile @model @auth(rules: [
  { allow: owner }
]) {
...
}

After authenticating user using Cognito by logging in, when the app tries to write a record in Profile table, nothing happens. Write happens only when I add { allow: public, operations: [create, read]}, to the model.

As far as I know, there is no code changes required to get this working. I tried after running amplify codegen models but didn't work.

I've been struggling with this for days. Not sure if this is a bug or miss on my side. Any suggestions would be appreciated.

Categories

Steps to Reproduce

No response

Screenshots

No response

Platforms

Android Device/Emulator API Level

No response

Environment

[✓] Flutter (Channel stable, 3.3.10, on macOS 13.0 22A380 darwin-arm, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] VS Code (version 1.74.0)
[✓] Connected device (4 available)
[✓] HTTP Host Availability

Dependencies

Dart SDK 2.18.6
Flutter SDK 3.3.10
chummy 1.0.0+1

dependencies:
- amplify_analytics_pinpoint 0.6.10 [amplify_analytics_pinpoint_android amplify_analytics_pinpoint_ios amplify_core aws_common flutter meta]
- amplify_api 0.6.10 [amplify_api_android amplify_api_ios amplify_core amplify_flutter aws_common collection flutter meta plugin_platform_interface]
- amplify_auth_cognito 0.6.10 [amplify_auth_cognito_android amplify_auth_cognito_ios amplify_core aws_common collection flutter meta plugin_platform_interface]
- amplify_authenticator 0.2.4 [amplify_auth_cognito amplify_core amplify_flutter async aws_common collection flutter flutter_localizations intl stream_transform]
- amplify_datastore 0.6.10 [flutter amplify_datastore_plugin_interface amplify_core plugin_platform_interface meta collection async]
- amplify_flutter 0.6.10 [amplify_core amplify_datastore_plugin_interface amplify_flutter_android amplify_flutter_ios aws_common collection flutter meta plugin_platform_interface]
- amplify_storage_s3 0.6.10 [amplify_storage_s3_android amplify_storage_s3_ios amplify_core aws_common flutter meta plugin_platform_interface path_provider path]
- cached_network_image 3.2.3 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web]
- connectivity_plus 3.0.2 [flutter flutter_web_plugins connectivity_plus_platform_interface js meta nm]
- cupertino_icons 1.0.5
- dotted_border 2.0.0+2 [flutter path_drawing]
- dropdown_button2 1.8.5 [flutter]
- email_validator 2.1.17
- firebase_core 2.3.0 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_messaging 14.1.1 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine]
- flutter_app_badger 1.5.0 [flutter]
- flutter_bloc 8.1.1 [flutter bloc provider]
- flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid]
- flutter_image_compress 1.1.3 [flutter]
- flutter_local_notifications 12.0.4 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_native_splash 2.2.15 [args flutter flutter_web_plugins js html image meta path universal_io xml yaml]
- flutter_slidable 2.0.0 [flutter]
- geocoding 2.0.5 [flutter geocoding_platform_interface]
- geolocator 9.0.2 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- google_maps_flutter 2.2.1 [flutter google_maps_flutter_android google_maps_flutter_ios google_maps_flutter_platform_interface]
- google_mobile_ads 2.3.0 [meta flutter visibility_detector]
- google_place 0.4.7 [http]
- image_picker 0.8.6 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_platform_interface]
- intl 0.17.0 [clock path]
- material_design_icons_flutter 6.0.7096 [flutter]
- path_provider 2.0.11 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows]
- percent_indicator 4.2.2 [flutter]
- permission_handler 10.2.0 [flutter meta permission_handler_android permission_handler_apple permission_handler_windows permission_handler_platform_interface]
- quiver 3.1.0 [matcher]
- social_login_buttons 1.0.7 [flutter]
- url_launcher 6.1.7 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]

transitive dependencies:
- _flutterfire_internals 1.0.9 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- amplify_analytics_pinpoint_android 0.6.10 [flutter]
- amplify_analytics_pinpoint_ios 0.6.10 [flutter]
- amplify_api_android 0.6.10 [flutter]
- amplify_api_ios 0.6.10 [amplify_core flutter]
- amplify_auth_cognito_android 0.6.10 [flutter]
- amplify_auth_cognito_ios 0.6.10 [amplify_core flutter]
- amplify_core 0.6.10 [aws_common collection flutter intl json_annotation meta plugin_platform_interface uuid]
- amplify_datastore_plugin_interface 0.6.10 [amplify_core collection flutter meta]
- amplify_flutter_android 0.6.10 [flutter]
- amplify_flutter_ios 0.6.10 [amplify_core flutter]
- amplify_storage_s3_android 0.6.10 [flutter]
- amplify_storage_s3_ios 0.6.10 [flutter]
- archive 3.3.4 [crypto path pointycastle]
- args 2.3.1
- async 2.9.0 [collection meta]
- aws_common 0.1.1 [async collection http meta stream_transform uuid]
- bloc 8.1.0 [meta]
- boolean_selector 2.1.0 [source_span string_scanner]
- cached_network_image_platform_interface 2.0.0 [flutter flutter_cache_manager]
- cached_network_image_web 1.0.2 [flutter flutter_cache_manager cached_network_image_platform_interface]
- characters 1.2.1
- clock 1.1.1
- cloud_firestore_platform_interface 5.9.0 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 3.1.0 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js]
- collection 1.16.0
- connectivity_plus_platform_interface 1.2.3 [flutter meta plugin_platform_interface]
- convert 3.1.1 [typed_data]
- cross_file 0.3.3+2 [js meta]
- crypto 3.0.2 [typed_data]
- csslib 0.17.2 [source_span]
- dbus 0.7.8 [args ffi meta xml]
- fake_async 1.3.1 [clock collection]
- ffi 2.0.1
- file 6.1.4 [meta path]
- firebase_core_platform_interface 4.5.2 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.0.1 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_messaging_platform_interface 4.2.7 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.2.7 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- flutter_blurhash 0.7.0 [flutter]
- flutter_local_notifications_linux 2.0.0 [flutter flutter_local_notifications_platform_interface dbus path xdg_directories]
- flutter_local_notifications_platform_interface 6.0.0 [flutter plugin_platform_interface]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math]
- flutter_plugin_android_lifecycle 2.0.7 [flutter]
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters collection matcher material_color_utilities meta source_span stream_channel string_scanner term_glyph]
- flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math]
- geocoding_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- geolocator_android 4.1.4 [flutter geolocator_platform_interface]
- geolocator_apple 2.2.2 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.0.6 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 2.1.6 [flutter flutter_web_plugins geolocator_platform_interface]
- geolocator_windows 0.1.1 [flutter geolocator_platform_interface]
- google_maps_flutter_android 2.3.2 [flutter flutter_plugin_android_lifecycle google_maps_flutter_platform_interface stream_transform]
- google_maps_flutter_ios 2.1.12 [flutter google_maps_flutter_platform_interface stream_transform]
- google_maps_flutter_platform_interface 2.2.4 [collection flutter plugin_platform_interface stream_transform]
- html 0.15.1 [csslib source_span]
- http 0.13.5 [async http_parser meta path]
- http_parser 4.0.1 [collection source_span string_scanner typed_data]
- image 3.2.2 [archive meta xml]
- image_picker_android 0.8.5+3 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 2.1.10 [flutter flutter_web_plugins image_picker_platform_interface]
- image_picker_ios 0.8.6+1 [flutter image_picker_platform_interface]
- image_picker_platform_interface 2.6.2 [cross_file flutter http plugin_platform_interface]
- js 0.6.4
- json_annotation 4.7.0 [meta]
- matcher 0.12.12 [stack_trace]
- material_color_utilities 0.1.5
- meta 1.8.0
- nested 1.0.0 [flutter]
- nm 0.5.0 [dbus]
- octo_image 1.0.2 [flutter flutter_blurhash]
- path 1.8.2
- path_drawing 1.0.1 [vector_math meta path_parsing flutter]
- path_parsing 1.0.1 [vector_math meta]
- path_provider_android 2.0.20 [flutter path_provider_platform_interface]
- path_provider_ios 2.0.11 [flutter path_provider_platform_interface]
- path_provider_linux 2.1.7 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_macos 2.0.6 [flutter path_provider_platform_interface]
- path_provider_platform_interface 2.0.5 [flutter platform plugin_platform_interface]
- path_provider_windows 2.1.3 [ffi flutter path path_provider_platform_interface win32]
- pedantic 1.11.1
- permission_handler_android 10.2.0 [flutter permission_handler_platform_interface]
- permission_handler_apple 9.0.7 [flutter permission_handler_platform_interface]
- permission_handler_platform_interface 3.9.0 [flutter meta plugin_platform_interface]
- permission_handler_windows 0.1.2 [flutter permission_handler_platform_interface]
- petitparser 5.1.0 [meta]
- platform 3.1.0
- plugin_platform_interface 2.1.3 [meta]
- pointycastle 3.6.2 [collection convert js]
- process 4.2.4 [file path platform]
- provider 6.0.3 [collection flutter nested]
- rxdart 0.27.5
- sky_engine 0.0.99
- source_span 1.9.0 [collection path term_glyph]
- sqflite 2.1.0+1 [flutter sqflite_common path]
- sqflite_common 2.3.0 [synchronized path meta]
- stack_trace 1.10.0 [path]
- stream_channel 2.1.0 [async]
- stream_transform 2.0.0
- string_scanner 1.1.1 [source_span]
- synchronized 3.0.0+3
- term_glyph 1.2.1
- test_api 0.4.12 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher]
- timezone 0.9.0 [path]
- typed_data 1.3.1 [collection]
- universal_io 2.0.4 [collection crypto meta typed_data]
- url_launcher_android 6.0.22 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.0.17 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.0.1 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.1.1 [flutter plugin_platform_interface]
- url_launcher_web 2.0.13 [flutter flutter_web_plugins url_launcher_platform_interface]
- url_launcher_windows 3.0.1 [flutter url_launcher_platform_interface]
- uuid 3.0.6 [crypto]
- vector_math 2.1.2
- visibility_detector 0.3.3 [flutter]
- win32 3.0.1 [ffi]
- xdg_directories 0.2.0+2 [meta path process]
- xml 6.1.0 [collection meta petitparser]
- yaml 3.1.1 [collection source_span string_scanner]

Device

iPhone 12

OS

iOS 16.1.2

Deployment Method

Amplify CLI

CLI Version

10.5.2

Additional Context

No response

Amplify Config

?

fjnoyp commented 1 year ago

Hi @skim037 thanks for sharing this issue.

How are you performing user sign ins? Are you using authenticator and if you call Amplify.Auth.fetchAuthSession before the Datastore save, is a valid user id printed out?

Also, can you share the code to you save command. These details will help me reproduce your issue on my side.

skim037 commented 1 year ago

Hi @fjnoyp

When my app starts, it generates UserLoginInitiated event. And this is how I handle this event.

    on<UserLoginInitiated>((event, emit) async {
      try {
        final userInfo = await authRepo.attemptAutoSignIn();
        final credentials = AuthCredentials(
            userId: userInfo['userId'],
            email: userInfo['email'],
            registered: false); 

In AuthRepository class, I have

  Future<Map> attemptAutoSignIn() async {
    final session = await Amplify.Auth.fetchAuthSession();

    if (session.isSignedIn) {
      return await fetchUserIdFromAttribute();
    } else {
      throw Exception('Not signed in');
    }
  }

  Future<Map> fetchUserIdFromAttribute() async {
    final attributes = await Amplify.Auth.fetchUserAttributes().timeout(const Duration(seconds: 5),);
    final subAttribute = attributes
      .firstWhere((element) => element.userAttributeKey.key == 'sub');
    final emailAttribute = attributes
        .firstWhere((element) => element.userAttributeKey.key == 'email');
    final userId = subAttribute.value;
    final email = emailAttribute.value;

    final userInfo = {"email": email, "userId": userId};
    return userInfo;
  }

My save operation looks like below.

  Future<void> saveProfile(Profile profile) async {
    try {
      await Amplify.DataStore.save(profile);
    } on Exception catch (e) {
      rethrow;
    }
  }

I verified that I have proper token and user Id when I call below operation before trying to save the data.

    final session = await Amplify.Auth.fetchAuthSession(
      options: CognitoSessionOptions(getAWSCredentials: true),
    );
fjnoyp commented 1 year ago

Hi @skim037 thanks for the detailed response here. I've been able to reproduce your issue and I think your problem is with a cli auth/api setup.

I was not able to save the model like you. I did the following: 1) add api and save model with datastore 2) add auth 3) add auth rules to model 4) save model with datastore no longer works even with signed in user

This is because the auth rules for your api category are not configured properly in the cli.

If you did the same as I did above, you probably got the following when you ran amplify codegen models:

InvalidDirectiveError: @auth directive with 'userPools' provider found, but the project has no Cognito User Pools authentication provider configured.

You need to fix this by configuring api correctly with amplify cli:

amplify update api ? Please select from one of the below mentioned services: GraphQL ? Select from the options below Update auth settings ? Choose the default authorization type for the API Amazon Cognito User Pool Use a Cognito user pool configured as a part of this project. ? Configure additional auth types? Yes ? Choose the additional authorization types you want to configure for the API API key API key configuration ? Enter a description for the API key: Public API ? After how many days from now the API key should expire (1-365): 365

Since you already have an auth user, I don't know if making this update will work for that user account. The safest would be to regenerate your backend and to apply the above steps to properly configure auth for api.

skim037 commented 1 year ago

Hi @fjnoyp

I was able to get owner strategy to work after reading your reply. I think the issue has to do with what I choose for default authorization type. I was using API Key as a default authorization type and Amazon Cognito User Pool as an additional auth type. This did not work even when I initialize new environment and try to save a new record. After I update auth to use Amazon Cognito User Pool as a default type and API Key as an additional type, and initialize new environment, the owner strategy started to work. Could you verify this and address this issue if this is not intentional? I think I'm unblocked for now. Thanks for looking into this.

I ran into another issue but I will open a separate case for this one.

cwomack commented 1 year ago

Possibly related to #1693

Equartey commented 9 months ago

Hi @skim037, looks like this issue was resolved and subsequent updates have been released since the original issue was observed. I'm going to mark this as pending close, if you are still experiencing an issue please respond and we will take a look.

Jordan-Nelson commented 9 months ago

Closing this out since we have not heard back. If you are still facing an issue let us know and we can reopen the issue.