From 74c6ebecc2a053954b32b5ab6fbe0d5ea150d5bc Mon Sep 17 00:00:00 2001 From: y1585740638 Date: Wed, 24 Aug 2022 15:35:31 +0800 Subject: [PATCH 1/2] =?UTF-8?q?IsAllwoUsingPermission=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.vscode/c_cpp_properties.json | 19 + .../.vscode/settings.json | 65 + security_access_token-yl_0822/BUILD.gn | 35 + security_access_token-yl_0822/LICENSE | 177 + security_access_token-yl_0822/OAT.xml | 83 + security_access_token-yl_0822/README.md | 82 + security_access_token-yl_0822/README_zh.md | 82 + .../access_token.gni | 26 + security_access_token-yl_0822/bundle.json | 117 + .../frameworks/accesstoken/BUILD.gn | 55 + .../accesstoken/include/hap_info_parcel.h | 40 + .../accesstoken/include/hap_policy_parcel.h | 39 + .../include/hap_token_info_for_sync_parcel.h | 40 + .../include/hap_token_info_parcel.h | 40 + .../include/i_accesstoken_manager.h | 124 + .../include/i_permission_state_callback.h | 43 + .../native_token_info_for_sync_parcel.h | 40 + .../include/native_token_info_parcel.h | 40 + .../include/permission_def_parcel.h | 39 + .../include/permission_list_state_parcel.h | 39 + .../permission_state_change_info_parcel.h | 40 + .../permission_state_change_scope_parcel.h | 40 + .../include/permission_state_full_parcel.h | 39 + .../accesstoken/src/hap_info_parcel.cpp | 48 + .../accesstoken/src/hap_policy_parcel.cpp | 87 + .../src/hap_token_info_for_sync_parcel.cpp | 66 + .../accesstoken/src/hap_token_info_parcel.cpp | 61 + .../src/native_token_info_for_sync_parcel.cpp | 66 + .../src/native_token_info_parcel.cpp | 95 + .../accesstoken/src/permission_def_parcel.cpp | 61 + .../src/permission_list_state_parcel.cpp | 41 + .../permission_state_change_info_parcel.cpp | 44 + .../permission_state_change_scope_parcel.cpp | 63 + .../src/permission_state_full_parcel.cpp | 79 + .../com.ohos.permissionmanager/.gitignore | 4 + .../AppScope/app.json5 | 26 + .../resources/base/element/string.json | 8 + .../resources/base/media/app_icon.png | Bin 0 -> 6790 bytes .../build-profile.json5 | 58 + .../entry/.gitignore | 3 + .../entry/build-profile.json5 | 28 + .../entry/hvigorfile.js | 2 + .../entry/package-lock.json | 5 + .../entry/package.json | 14 + .../src/main/ets/Application/AbilityStage.ts | 7 + .../src/main/ets/MainAbility/MainAbility.ts | 34 + .../entry/src/main/ets/pages/index.ets | 32 + .../entry/src/main/module.json5 | 51 + .../main/resources/base/element/string.json | 16 + .../src/main/resources/base/media/icon.png | Bin 0 -> 6790 bytes .../resources/base/profile/main_pages.json | 5 + .../com.ohos.permissionmanager/hvigorfile.js | 2 + .../package-lock.json | 1643 ++++++++++ .../com.ohos.permissionmanager/package.json | 18 + .../permissionmanager/.gitignore | 3 + .../permissionmanager/build-profile.json5 | 28 + .../permissionmanager/hvigorfile.js | 2 + .../permissionmanager/package-lock.json | 5 + .../permissionmanager/package.json | 14 + .../src/main/ets/Application/AbilityStage.ts | 24 + .../src/main/ets/MainAbility/MainAbility.ts | 55 + .../ServiceExtAbility/ServiceExtAbility.ts | 81 + .../common/components/alphabeticalIndex.ets | 77 + .../main/ets/common/components/backBar.ets | 78 + .../src/main/ets/common/components/dialog.ets | 40 + .../src/main/ets/common/components/search.ets | 63 + .../src/main/ets/common/model/bundle.ets | 38 + .../main/ets/common/model/permissionGroup.ets | 512 +++ .../src/main/ets/common/utils/constant.ets | 349 ++ .../src/main/ets/common/utils/utils.ets | 427 +++ .../main/ets/pages/application-secondary.ets | 346 ++ .../main/ets/pages/application-tertiary.ets | 431 +++ .../main/ets/pages/authority-management.ets | 715 ++++ .../main/ets/pages/authority-secondary.ets | 177 + .../ets/pages/authority-tertiary-groups.ets | 403 +++ .../src/main/ets/pages/authority-tertiary.ets | 363 +++ .../src/main/ets/pages/dialogPlus.ets | 344 ++ .../src/main/ets/pages/other-permissions.ets | 170 + .../ets/pages/permission-access-record.ets | 533 +++ .../permissionmanager/src/main/module.json5 | 71 + .../src/main/resources/ar/profile/string.json | 14 + .../main/resources/base/element/color.json | 112 + .../main/resources/base/element/string.json | 92 + .../resources/base/media/gongneng_dian.svg | 1 + .../resources/base/media/ic_call_logs.svg | 15 + .../main/resources/base/media/ic_dropzone.svg | 19 + .../main/resources/base/media/ic_exercise.svg | 15 + .../main/resources/base/media/ic_forward.svg | 13 + .../src/main/resources/base/media/ic_more.svg | 7 + .../base/media/ic_multi_device_vector.svg | 7 + .../main/resources/base/media/ic_nearby.svg | 7 + .../base/media/ic_public_calendar.svg | 13 + .../resources/base/media/ic_public_camera.svg | 13 + .../base/media/ic_public_contacts_group.svg | 13 + .../resources/base/media/ic_public_folder.svg | 13 + .../resources/base/media/ic_public_gps.svg | 13 + .../base/media/ic_public_message.svg | 13 + .../resources/base/media/ic_public_phone.svg | 13 + .../resources/base/media/ic_public_voice.svg | 13 + .../main/resources/base/media/ic_sport.svg | 7 + .../main/resources/base/media/ic_ssensor.svg | 9 + .../src/main/resources/base/media/icon.png | Bin 0 -> 6790 bytes .../base/media/in_app_installations.svg | 13 + .../src/main/resources/base/media/left.png | Bin 0 -> 1070 bytes .../src/main/resources/base/media/loading.gif | Bin 0 -> 3897 bytes .../main/resources/base/media/noRecord.svg | 20 + .../base/media/noinstallationpackage.svg | 17 + .../resources/base/media/nopermission.svg | 16 + .../main/resources/base/media/radioactive.jpg | Bin 0 -> 2217 bytes .../resources/base/media/radiodefault.jpg | Bin 0 -> 1313 bytes .../main/resources/base/media/rightarrow.png | Bin 0 -> 1058 bytes .../src/main/resources/base/media/search.png | Bin 0 -> 1147 bytes .../resources/base/media/searchnoresult.svg | 22 + .../base/media/xiangshangjiantou.svg | 1 + .../resources/base/media/xiangxiajiantou.svg | 1 + .../resources/base/profile/main_pages.json | 13 + .../main/resources/dark/profile/string.json | 7 + .../src/main/resources/en/profile/string.json | 14 + .../main/resources/light/profile/string.json | 7 + .../src/main/resources/zh/profile/string.json | 14 + .../main/resources/zh_CN/element/string.json | 92 + .../frameworks/common/BUILD.gn | 48 + .../common/include/accesstoken_log.h | 69 + .../common/include/constant_common.h | 44 + .../common/include/data_validator.h | 59 + .../frameworks/common/include/parcel_utils.h | 38 + .../frameworks/common/include/random.h | 32 + .../common/include/random_mbedtls.h | 43 + .../frameworks/common/src/constant_common.cpp | 56 + .../frameworks/common/src/data_validator.cpp | 99 + .../frameworks/common/src/random_mbedtls.cpp | 67 + .../frameworks/privacy/BUILD.gn | 41 + .../include/bundle_used_record_parcel.h | 40 + .../include/i_perm_active_status_callback.h | 42 + .../privacy/include/i_privacy_manager.h | 70 + .../include/perm_active_response_parcel.h | 40 + .../include/permission_used_record_parcel.h | 40 + .../include/permission_used_request_parcel.h | 40 + .../include/permission_used_result_parcel.h | 40 + .../include/used_record_detail_parcel.h | 40 + .../privacy/src/bundle_used_record_parcel.cpp | 61 + .../src/perm_active_response_parcel.cpp | 50 + .../src/permission_used_record_parcel.cpp | 80 + .../src/permission_used_request_parcel.cpp | 65 + .../src/permission_used_result_parcel.cpp | 57 + .../privacy/src/used_record_detail_parcel.cpp | 42 + .../tokensync/include/i_token_sync_manager.h | 50 + .../interfaces/innerkits/accesstoken/BUILD.gn | 70 + .../accesstoken/include/access_token.h | 105 + .../accesstoken/include/accesstoken.h | 36 + .../include/accesstoken_death_recipient.h | 35 + .../accesstoken/include/accesstoken_kit.h | 82 + .../accesstoken/include/hap_token_info.h | 69 + .../accesstoken/include/native_token_info.h | 46 + .../perm_state_change_callback_customize.h | 41 + .../accesstoken/include/permission_def.h | 49 + .../accesstoken/include/permission_dlp_mode.h | 33 + .../include/permission_list_state.h | 33 + .../include/permission_state_change_info.h | 44 + .../include/permission_state_full.h | 36 + .../src/accesstoken_death_recipient.cpp | 34 + .../accesstoken/src/accesstoken_kit.cpp | 396 +++ .../src/accesstoken_manager_client.cpp | 561 ++++ .../src/accesstoken_manager_client.h | 103 + .../src/accesstoken_manager_proxy.cpp | 1036 ++++++ .../src/accesstoken_manager_proxy.h | 87 + .../perm_state_change_callback_customize.cpp | 37 + .../src/permission_state_change_callback.cpp | 50 + .../src/permission_state_change_callback.h | 42 + .../permission_state_change_callback_stub.cpp | 59 + .../permission_state_change_callback_stub.h | 38 + .../innerkits/accesstoken/test/BUILD.gn | 55 + .../unittest/src/accesstoken_kit_test.cpp | 2869 +++++++++++++++++ .../test/unittest/src/accesstoken_kit_test.h | 60 + .../interfaces/innerkits/nativetoken/BUILD.gn | 55 + .../nativetoken/include/nativetoken.h | 98 + .../include/nativetoken_json_oper.h | 39 + .../nativetoken/include/nativetoken_kit.h | 45 + .../nativetoken/include/nativetoken_log.h | 49 + .../innerkits/nativetoken/src/nativetoken.c | 666 ++++ .../nativetoken/src/nativetoken_json_oper.c | 296 ++ .../innerkits/nativetoken/test/BUILD.gn | 41 + .../unittest/src/nativetoken_kit_test.cpp | 738 +++++ .../test/unittest/src/nativetoken_kit_test.h | 40 + .../interfaces/innerkits/privacy/BUILD.gn | 67 + .../include/active_change_response_info.h | 43 + .../on_permission_used_record_callback.h | 39 + .../perm_active_status_change_callback.h | 45 + .../perm_active_status_change_callback_stub.h | 38 + .../perm_active_status_customized_cbk.h | 45 + .../privacy/include/permission_used_request.h | 45 + .../privacy/include/permission_used_result.h | 59 + .../innerkits/privacy/include/privacy_kit.h | 48 + .../perm_active_status_change_callback.cpp | 49 + ...erm_active_status_change_callback_stub.cpp | 57 + .../src/perm_active_status_customized_cbk.cpp | 37 + .../privacy/src/privacy_death_recipient.cpp | 36 + .../privacy/src/privacy_death_recipient.h | 35 + .../innerkits/privacy/src/privacy_kit.cpp | 97 + .../privacy/src/privacy_manager_client.cpp | 283 ++ .../privacy/src/privacy_manager_client.h | 70 + .../privacy/src/privacy_manager_proxy.cpp | 340 ++ .../privacy/src/privacy_manager_proxy.h | 53 + .../innerkits/privacy/test/BUILD.gn | 53 + .../test/unittest/src/privacy_kit_test.cpp | 863 +++++ .../test/unittest/src/privacy_kit_test.h | 58 + .../innerkits/token_callback/BUILD.gn | 59 + .../token_callback/include/i_token_callback.h | 38 + .../include/token_callback_proxy.h | 41 + .../include/token_callback_stub.h | 37 + .../src/token_callback_proxy.cpp | 92 + .../src/token_callback_stub.cpp | 79 + .../innerkits/token_setproc/BUILD.gn | 40 + .../token_setproc/include/token_setproc.h | 36 + .../token_setproc/src/token_setproc.c | 115 + .../innerkits/token_setproc/test/BUILD.gn | 38 + .../unittest/src/tokensetproc_kit_test.cpp | 33 + .../test/unittest/src/tokensetproc_kit_test.h | 35 + .../interfaces/innerkits/tokensync/BUILD.gn | 65 + .../tokensync/include/token_sync_kit.h | 38 + .../src/token_sync_death_recipient.cpp | 37 + .../src/token_sync_death_recipient.h | 36 + .../tokensync/src/token_sync_kit.cpp | 54 + .../src/token_sync_load_callback.cpp | 66 + .../tokensync/src/token_sync_load_callback.h | 37 + .../src/token_sync_manager_client.cpp | 196 ++ .../tokensync/src/token_sync_manager_client.h | 65 + .../src/token_sync_manager_proxy.cpp | 128 + .../tokensync/src/token_sync_manager_proxy.h | 45 + .../innerkits/tokensync/test/BUILD.gn | 42 + .../test/unittest/src/token_sync_kit_test.cpp | 36 + .../test/unittest/src/token_sync_kit_test.h | 37 + .../interfaces/kits/BUILD.gn | 25 + .../interfaces/kits/accesstoken/BUILD.gn | 40 + .../accesstoken/napi/include/napi_atmanager.h | 87 + .../accesstoken/napi/src/napi_atmanager.cpp | 588 ++++ .../accesstoken/test/benchmarktest/BUILD.gn | 53 + .../benchmarktest/napi_atmanager_test.cpp | 145 + .../interfaces/kits/common/BUILD.gn | 33 + .../kits/common/include/napi_common.h | 44 + .../kits/common/src/napi_common.cpp | 129 + .../interfaces/kits/privacy/BUILD.gn | 49 + .../napi/include/napi_context_common.h | 36 + .../kits/privacy/napi/include/native_module.h | 36 + .../include/permission_record_manager_napi.h | 50 + .../privacy/napi/src/napi_context_common.cpp | 39 + .../kits/privacy/napi/src/native_module.cpp | 79 + .../src/permission_record_manager_napi.cpp | 553 ++++ security_access_token-yl_0822/ohos.build | 61 + .../services/accesstokenmanager/BUILD.gn | 113 + .../accesstokenmanager/access_token.cfg | 20 + .../accesstokenmanager/access_token.rc | 22 + .../cpp/include/callback/callback_manager.h | 67 + .../perm_state_callback_death_recipient.h | 34 + .../permission_state_change_callback_proxy.h | 40 + .../main/cpp/include/database/data_storage.h | 54 + .../cpp/include/database/data_translator.h | 40 + .../cpp/include/database/sqlite_storage.h | 88 + .../device/atm_device_state_callback.h | 42 + .../permission/dlp_permission_set_manager.h | 53 + .../permission/dlp_permission_set_parser.h | 53 + .../permission/permission_definition_cache.h | 77 + .../include/permission/permission_manager.h | 73 + .../permission/permission_policy_set.h | 73 + .../include/permission/permission_validator.h | 46 + .../service/accesstoken_manager_service.h | 94 + .../service/accesstoken_manager_stub.h | 85 + .../include/token/accesstoken_id_manager.h | 56 + .../include/token/accesstoken_info_manager.h | 107 + .../token/accesstoken_remote_token_manager.h | 61 + .../cpp/include/token/hap_token_info_inner.h | 76 + .../include/token/native_token_info_inner.h | 86 + .../cpp/include/token/native_token_receptor.h | 56 + .../cpp/include/token/token_modify_notifier.h | 55 + .../cpp/src/callback/callback_manager.cpp | 165 + .../perm_state_callback_death_recipient.cpp | 48 + ...permission_state_change_callback_proxy.cpp | 68 + .../main/cpp/src/database/data_storage.cpp | 29 + .../main/cpp/src/database/data_translator.cpp | 117 + .../main/cpp/src/database/sqlite_storage.cpp | 375 +++ .../src/device/atm_device_state_callback.cpp | 85 + .../permission/dlp_permission_set_manager.cpp | 107 + .../permission/dlp_permission_set_parser.cpp | 152 + .../permission_definition_cache.cpp | 167 + .../cpp/src/permission/permission_manager.cpp | 448 +++ .../src/permission/permission_policy_set.cpp | 373 +++ .../src/permission/permission_validator.cpp | 138 + .../service/accesstoken_manager_service.cpp | 466 +++ .../src/service/accesstoken_manager_stub.cpp | 579 ++++ .../cpp/src/token/accesstoken_id_manager.cpp | 130 + .../src/token/accesstoken_info_manager.cpp | 993 ++++++ .../accesstoken_remote_token_manager.cpp | 158 + .../cpp/src/token/hap_token_info_inner.cpp | 267 ++ .../cpp/src/token/native_token_info_inner.cpp | 262 ++ .../cpp/src/token/native_token_receptor.cpp | 228 ++ .../cpp/src/token/token_modify_notifier.cpp | 118 + .../main/sa_profile/3503.xml | 24 + .../main/sa_profile/BUILD.gn | 23 + .../services/accesstokenmanager/test/BUILD.gn | 68 + .../cpp/src/accesstoken_info_manager_test.cpp | 706 ++++ .../cpp/src/accesstoken_info_manager_test.h | 37 + .../cpp/src/native_token_receptor_test.cpp | 706 ++++ .../cpp/src/native_token_receptor_test.h | 38 + .../services/common/database/BUILD.gn | 41 + .../common/database/include/field_const.h | 65 + .../common/database/include/generic_values.h | 58 + .../common/database/include/sqlite_helper.h | 62 + .../common/database/include/statement.h | 59 + .../common/database/include/variant_value.h | 55 + .../common/database/src/generic_values.cpp | 94 + .../common/database/src/sqlite_helper.cpp | 195 ++ .../common/database/src/statement.cpp | 143 + .../common/database/src/variant_value.cpp | 75 + .../services/privacymanager/BUILD.gn | 82 + .../active/active_status_callback_manager.h | 62 + ...m_active_status_callback_death_recipient.h | 35 + ...perm_active_status_change_callback_proxy.h | 40 + .../privacymanager/include/common/constant.h | 76 + .../privacymanager/include/common/time_util.h | 30 + .../privacymanager/include/common/to_string.h | 38 + .../include/database/data_translator.h | 38 + .../database/permission_used_record_db.h | 88 + ...on_permission_used_record_callback_proxy.h | 40 + .../on_permission_used_record_callback_stub.h | 38 + .../include/record/permission_record.h | 41 + .../record/permission_record_manager.h | 81 + .../include/record/permission_record_node.h | 35 + .../record/permission_record_repository.h | 44 + .../record/permission_used_record_cache.h | 78 + .../include/service/privacy_manager_service.h | 61 + .../include/service/privacy_manager_stub.h | 51 + .../services/privacymanager/privacy.cfg | 11 + .../services/privacymanager/privacy.rc | 22 + .../privacymanager/sa_profile/3505.xml | 24 + .../privacymanager/sa_profile/BUILD.gn | 23 + .../active/active_status_callback_manager.cpp | 154 + ...active_status_callback_death_recipient.cpp | 47 + ...rm_active_status_change_callback_proxy.cpp | 67 + .../privacymanager/src/common/constant.cpp | 75 + .../privacymanager/src/common/time_util.cpp | 29 + .../privacymanager/src/common/to_string.cpp | 98 + .../src/database/data_translator.cpp | 104 + .../database/permission_used_record_db.cpp | 414 +++ ..._permission_used_record_callback_proxy.cpp | 71 + ...n_permission_used_record_callback_stub.cpp | 65 + .../src/record/permission_record.cpp | 45 + .../src/record/permission_record_manager.cpp | 412 +++ .../record/permission_record_repository.cpp | 117 + .../record/permission_used_record_cache.cpp | 425 +++ .../src/service/privacy_manager_service.cpp | 138 + .../src/service/privacy_manager_stub.cpp | 223 ++ .../add_permission_used_record_test.cpp | 55 + .../add_permission_used_record_test.h | 37 + .../services/tokensyncmanager/BUILD.gn | 100 + .../include/command/base_remote_command.h | 67 + .../command/delete_remote_token_command.h | 52 + .../command/sync_remote_hap_token_command.h | 59 + .../sync_remote_native_token_command.h | 55 + .../command/update_remote_hap_token_command.h | 56 + .../include/common/constant.h | 76 + .../include/device/device_info.h | 46 + .../include/device/device_info_manager.h | 106 + .../include/device/device_info_repository.h | 77 + .../include/protocol/remote_protocol.h | 38 + .../include/remote/remote_command_executor.h | 158 + .../include/remote/remote_command_factory.h | 58 + .../include/remote/remote_command_manager.h | 165 + .../include/remote/rpc_channel.h | 80 + .../include/remote/soft_bus_channel.h | 354 ++ .../soft_bus_device_connection_listener.h | 71 + .../include/remote/soft_bus_manager.h | 147 + .../remote/soft_bus_session_listener.h | 115 + .../service/token_sync_event_handler.h | 43 + .../service/token_sync_manager_service.h | 60 + .../include/service/token_sync_manager_stub.h | 41 + .../tokensyncmanager/sa_profile/3504.xml | 24 + .../tokensyncmanager/sa_profile/BUILD.gn | 22 + .../src/command/base_remote_command.cpp | 280 ++ .../command/delete_remote_token_command.cpp | 110 + .../command/sync_remote_hap_token_command.cpp | 123 + .../sync_remote_native_token_command.cpp | 121 + .../update_remote_hap_token_command.cpp | 106 + .../tokensyncmanager/src/common/constant.cpp | 28 + .../src/device/device_info_manager.cpp | 164 + .../src/device/device_info_repository.cpp | 191 ++ .../src/remote/remote_command_executor.cpp | 331 ++ .../src/remote/remote_command_factory.cpp | 77 + .../src/remote/remote_command_manager.cpp | 293 ++ .../src/remote/soft_bus_channel.cpp | 454 +++ .../soft_bus_device_connection_listener.cpp | 121 + .../src/remote/soft_bus_manager.cpp | 410 +++ .../src/remote/soft_bus_session_listener.cpp | 137 + .../src/service/token_sync_event_handler.cpp | 54 + .../service/token_sync_manager_service.cpp | 201 ++ .../src/service/token_sync_manager_stub.cpp | 103 + .../test/mock/include/mock_parameter.h | 33 + .../test/mock/include/session.h | 354 ++ .../test/mock/src/constant_mock.cpp | 43 + .../test/mock/src/mock_parameter.c | 26 + .../test/mock/src/soft_bus_center_mock.cpp | 98 + .../test/mock/src/soft_bus_session_mock.cpp | 223 ++ .../test/unittest/token_sync_service/BUILD.gn | 100 + .../token_sync_service_test.cpp | 684 ++++ .../token_sync_service_test.h | 45 + .../services/tokensyncmanager/token_sync.cfg | 13 + .../services/tokensyncmanager/token_sync.rc | 22 + .../test/fuzztest/access_token/BUILD.gn | 37 + .../allochaptoken_fuzzer/BUILD.gn | 46 + .../allochaptoken_fuzzer.cpp | 80 + .../allochaptoken_fuzzer.h | 21 + .../allochaptoken_fuzzer/corpus/init | 14 + .../allochaptoken_fuzzer/project.xml | 25 + .../alloclocaltokenid_fuzzer/BUILD.gn | 46 + .../alloclocaltokenid_fuzzer.cpp | 49 + .../alloclocaltokenid_fuzzer.h | 21 + .../alloclocaltokenid_fuzzer/corpus/init | 14 + .../alloclocaltokenid_fuzzer/project.xml | 25 + .../checknativedcap_fuzzer/BUILD.gn | 46 + .../checknativedcap_fuzzer.cpp | 48 + .../checknativedcap_fuzzer.h | 21 + .../checknativedcap_fuzzer/corpus/init | 14 + .../checknativedcap_fuzzer/project.xml | 25 + .../BUILD.gn | 46 + ...clearusergrantedpermissionstate_fuzzer.cpp | 48 + .../clearusergrantedpermissionstate_fuzzer.h | 21 + .../corpus/init | 14 + .../project.xml | 25 + .../deleteremotedevicetokens_fuzzer/BUILD.gn | 46 + .../corpus/init | 14 + .../deleteremotedevicetokens_fuzzer.cpp | 56 + .../deleteremotedevicetokens_fuzzer.h | 21 + .../project.xml | 25 + .../deleteremotetoken_fuzzer/BUILD.gn | 46 + .../deleteremotetoken_fuzzer/corpus/init | 14 + .../deleteremotetoken_fuzzer.cpp | 55 + .../deleteremotetoken_fuzzer.h | 21 + .../deleteremotetoken_fuzzer/project.xml | 25 + .../access_token/deletetoken_fuzzer/BUILD.gn | 46 + .../deletetoken_fuzzer/corpus/init | 14 + .../deletetoken_fuzzer/deletetoken_fuzzer.cpp | 48 + .../deletetoken_fuzzer/deletetoken_fuzzer.h | 21 + .../deletetoken_fuzzer/project.xml | 25 + .../getdefpermission_fuzzer/BUILD.gn | 46 + .../getdefpermission_fuzzer/corpus/init | 14 + .../getdefpermission_fuzzer.cpp | 62 + .../getdefpermission_fuzzer.h | 21 + .../getdefpermission_fuzzer/project.xml | 25 + .../getpermissionflags_fuzzer/BUILD.gn | 46 + .../getpermissionflags_fuzzer/corpus/init | 14 + .../getpermissionflags_fuzzer.cpp | 48 + .../getpermissionflags_fuzzer.h | 21 + .../getpermissionflags_fuzzer/project.xml | 25 + .../grantpermission_fuzzer/BUILD.gn | 46 + .../grantpermission_fuzzer/corpus/init | 14 + .../grantpermission_fuzzer.cpp | 48 + .../grantpermission_fuzzer.h | 21 + .../grantpermission_fuzzer/project.xml | 25 + .../BUILD.gn | 46 + .../corpus/init | 14 + .../project.xml | 25 + .../revokeusergrantedpermission_fuzzer.cpp | 48 + .../revokeusergrantedpermission_fuzzer.h | 21 + .../setremotehaptokeninfo_fuzzer/BUILD.gn | 46 + .../setremotehaptokeninfo_fuzzer/corpus/init | 14 + .../setremotehaptokeninfo_fuzzer/project.xml | 25 + .../setremotehaptokeninfo_fuzzer.cpp | 77 + .../setremotehaptokeninfo_fuzzer.h | 21 + .../setremotenativetokeninfo_fuzzer/BUILD.gn | 46 + .../corpus/init | 14 + .../project.xml | 25 + .../setremotenativetokeninfo_fuzzer.cpp | 69 + .../setremotenativetokeninfo_fuzzer.h | 21 + .../updatehaptoken_fuzzer/BUILD.gn | 46 + .../updatehaptoken_fuzzer/corpus/init | 14 + .../updatehaptoken_fuzzer/project.xml | 25 + .../updatehaptoken_fuzzer.cpp | 74 + .../updatehaptoken_fuzzer.h | 21 + .../verifyaccesstoken001_fuzzer/BUILD.gn | 46 + .../verifyaccesstoken001_fuzzer/corpus/init | 14 + .../verifyaccesstoken001_fuzzer/project.xml | 25 + .../verifyaccesstoken001_fuzzer.cpp | 48 + .../verifyaccesstoken001_fuzzer.h | 21 + .../verifyaccesstoken_fuzzer/BUILD.gn | 46 + .../verifyaccesstoken_fuzzer/corpus/init | 14 + .../verifyaccesstoken_fuzzer/project.xml | 25 + .../verifyaccesstoken_fuzzer.cpp | 48 + .../verifyaccesstoken_fuzzer.h | 21 + security_access_token-yl_0822/tools/BUILD.gn | 21 + .../tools/accesstoken/BUILD.gn | 63 + .../tools/accesstoken/include/atm_command.h | 81 + .../accesstoken/include/atm_receiver_impl.h | 43 + .../tools/accesstoken/src/atm_command.cpp | 298 ++ .../accesstoken/src/atm_receiver_impl.cpp | 59 + .../tools/accesstoken/src/main.cpp | 24 + 494 files changed, 48927 insertions(+) create mode 100644 security_access_token-yl_0822/.vscode/c_cpp_properties.json create mode 100644 security_access_token-yl_0822/.vscode/settings.json create mode 100644 security_access_token-yl_0822/BUILD.gn create mode 100644 security_access_token-yl_0822/LICENSE create mode 100644 security_access_token-yl_0822/OAT.xml create mode 100644 security_access_token-yl_0822/README.md create mode 100644 security_access_token-yl_0822/README_zh.md create mode 100644 security_access_token-yl_0822/access_token.gni create mode 100644 security_access_token-yl_0822/bundle.json create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/BUILD.gn create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/hap_info_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/hap_policy_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/i_accesstoken_manager.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/i_permission_state_callback.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_for_sync_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/permission_def_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/permission_list_state_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_info_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_scope_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_full_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/hap_info_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/hap_policy_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_for_sync_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/permission_def_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/permission_list_state_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_info_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_full_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/.gitignore create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/app.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/element/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/media/app_icon.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/build-profile.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/.gitignore create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/build-profile.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/hvigorfile.js create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/package-lock.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/package.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/ets/Application/AbilityStage.ts create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/ets/MainAbility/MainAbility.ts create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/ets/pages/index.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/module.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/resources/base/element/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/resources/base/media/icon.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/entry/src/main/resources/base/profile/main_pages.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/hvigorfile.js create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/package-lock.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/package.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/.gitignore create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/build-profile.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/hvigorfile.js create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package-lock.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/Application/AbilityStage.ts create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/MainAbility/MainAbility.ts create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/alphabeticalIndex.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/backBar.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/dialog.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/search.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/bundle.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/permissionGroup.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/utils.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-secondary.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-tertiary.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-management.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-secondary.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary-groups.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/other-permissions.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/permission-access-record.ets create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/module.json5 create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/ar/profile/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/color.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/gongneng_dian.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_call_logs.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_dropzone.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_exercise.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_forward.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_more.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_multi_device_vector.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_nearby.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_calendar.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_camera.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_contacts_group.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_folder.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_gps.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_message.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_phone.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_voice.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_sport.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_ssensor.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/icon.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/in_app_installations.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/left.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/loading.gif create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noRecord.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noinstallationpackage.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/nopermission.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radioactive.jpg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radiodefault.jpg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/rightarrow.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/search.png create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/searchnoresult.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangshangjiantou.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangxiajiantou.svg create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/profile/main_pages.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/dark/profile/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/en/profile/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/light/profile/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh/profile/string.json create mode 100644 security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh_CN/element/string.json create mode 100644 security_access_token-yl_0822/frameworks/common/BUILD.gn create mode 100644 security_access_token-yl_0822/frameworks/common/include/accesstoken_log.h create mode 100644 security_access_token-yl_0822/frameworks/common/include/constant_common.h create mode 100644 security_access_token-yl_0822/frameworks/common/include/data_validator.h create mode 100644 security_access_token-yl_0822/frameworks/common/include/parcel_utils.h create mode 100644 security_access_token-yl_0822/frameworks/common/include/random.h create mode 100644 security_access_token-yl_0822/frameworks/common/include/random_mbedtls.h create mode 100644 security_access_token-yl_0822/frameworks/common/src/constant_common.cpp create mode 100644 security_access_token-yl_0822/frameworks/common/src/data_validator.cpp create mode 100644 security_access_token-yl_0822/frameworks/common/src/random_mbedtls.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/BUILD.gn create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/bundle_used_record_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/i_perm_active_status_callback.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/i_privacy_manager.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/perm_active_response_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/permission_used_record_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/permission_used_request_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/permission_used_result_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/include/used_record_detail_parcel.h create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/bundle_used_record_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/perm_active_response_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/permission_used_record_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/permission_used_request_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/permission_used_result_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/privacy/src/used_record_detail_parcel.cpp create mode 100644 security_access_token-yl_0822/frameworks/tokensync/include/i_token_sync_manager.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/access_token.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_kit.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/hap_token_info.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/native_token_info.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/perm_state_change_callback_customize.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_def.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_dlp_mode.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_list_state.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_change_info.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_full.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/perm_state_change_callback_customize.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_json_oper.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_kit.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_log.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken.c create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/active_change_response_info.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/on_permission_used_record_callback.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback_stub.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_customized_cbk.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_request.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_result.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/include/privacy_kit.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback_stub.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_customized_cbk.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_kit.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/test/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/include/i_token_callback.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_proxy.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_stub.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_proxy.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_stub.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/include/token_setproc.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/src/token_setproc.c create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/include/token_sync_kit.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_kit.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/test/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h create mode 100644 security_access_token-yl_0822/interfaces/kits/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/kits/accesstoken/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/kits/accesstoken/napi/include/napi_atmanager.h create mode 100644 security_access_token-yl_0822/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp create mode 100644 security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/napi_atmanager_test.cpp create mode 100644 security_access_token-yl_0822/interfaces/kits/common/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/kits/common/include/napi_common.h create mode 100644 security_access_token-yl_0822/interfaces/kits/common/src/napi_common.cpp create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/BUILD.gn create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/include/napi_context_common.h create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/include/native_module.h create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/include/permission_record_manager_napi.h create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/src/napi_context_common.cpp create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/src/native_module.cpp create mode 100644 security_access_token-yl_0822/interfaces/kits/privacy/napi/src/permission_record_manager_napi.cpp create mode 100644 security_access_token-yl_0822/ohos.build create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/BUILD.gn create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/access_token.cfg create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/access_token.rc create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/callback_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/perm_state_callback_death_recipient.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/permission_state_change_callback_proxy.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_storage.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_translator.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/device/atm_device_state_callback.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_parser.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_receptor.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/perm_state_callback_death_recipient.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/permission_state_change_callback_proxy.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/device/atm_device_state_callback.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_parser.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/3503.xml create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/BUILD.gn create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/test/BUILD.gn create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp create mode 100644 security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.h create mode 100644 security_access_token-yl_0822/services/common/database/BUILD.gn create mode 100644 security_access_token-yl_0822/services/common/database/include/field_const.h create mode 100644 security_access_token-yl_0822/services/common/database/include/generic_values.h create mode 100644 security_access_token-yl_0822/services/common/database/include/sqlite_helper.h create mode 100644 security_access_token-yl_0822/services/common/database/include/statement.h create mode 100644 security_access_token-yl_0822/services/common/database/include/variant_value.h create mode 100644 security_access_token-yl_0822/services/common/database/src/generic_values.cpp create mode 100644 security_access_token-yl_0822/services/common/database/src/sqlite_helper.cpp create mode 100644 security_access_token-yl_0822/services/common/database/src/statement.cpp create mode 100644 security_access_token-yl_0822/services/common/database/src/variant_value.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/BUILD.gn create mode 100644 security_access_token-yl_0822/services/privacymanager/include/active/active_status_callback_manager.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_callback_death_recipient.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_change_callback_proxy.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/common/constant.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/common/time_util.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/common/to_string.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/database/data_translator.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/database/permission_used_record_db.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_proxy.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_stub.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/permission_record.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/permission_record_manager.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/permission_record_node.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/permission_record_repository.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/record/permission_used_record_cache.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_service.h create mode 100644 security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_stub.h create mode 100644 security_access_token-yl_0822/services/privacymanager/privacy.cfg create mode 100644 security_access_token-yl_0822/services/privacymanager/privacy.rc create mode 100644 security_access_token-yl_0822/services/privacymanager/sa_profile/3505.xml create mode 100644 security_access_token-yl_0822/services/privacymanager/sa_profile/BUILD.gn create mode 100644 security_access_token-yl_0822/services/privacymanager/src/active/active_status_callback_manager.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_callback_death_recipient.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_change_callback_proxy.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/common/constant.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/common/time_util.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/common/to_string.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/database/data_translator.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/database/permission_used_record_db.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_proxy.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_stub.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/permission_record.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/permission_record_manager.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/permission_record_repository.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/record/permission_used_record_cache.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_service.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_stub.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp create mode 100644 security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/BUILD.gn create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/command/base_remote_command.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/command/delete_remote_token_command.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_native_token_command.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/command/update_remote_hap_token_command.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/common/constant.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_manager.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_repository.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/protocol/remote_protocol.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_executor.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_factory.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_manager.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/rpc_channel.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_channel.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_manager.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_session_listener.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_event_handler.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_service.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_stub.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/sa_profile/3504.xml create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/sa_profile/BUILD.gn create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/command/base_remote_command.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/command/delete_remote_token_command.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/common/constant.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_manager.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_repository.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_executor.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_factory.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_manager.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_channel.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_manager.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_event_handler.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_service.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/mock_parameter.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/session.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/constant_mock.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/mock_parameter.c create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/token_sync.cfg create mode 100644 security_access_token-yl_0822/services/tokensyncmanager/token_sync.rc create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.h create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/corpus/init create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/project.xml create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp create mode 100644 security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.h create mode 100644 security_access_token-yl_0822/tools/BUILD.gn create mode 100644 security_access_token-yl_0822/tools/accesstoken/BUILD.gn create mode 100644 security_access_token-yl_0822/tools/accesstoken/include/atm_command.h create mode 100644 security_access_token-yl_0822/tools/accesstoken/include/atm_receiver_impl.h create mode 100644 security_access_token-yl_0822/tools/accesstoken/src/atm_command.cpp create mode 100644 security_access_token-yl_0822/tools/accesstoken/src/atm_receiver_impl.cpp create mode 100644 security_access_token-yl_0822/tools/accesstoken/src/main.cpp diff --git a/security_access_token-yl_0822/.vscode/c_cpp_properties.json b/security_access_token-yl_0822/.vscode/c_cpp_properties.json new file mode 100644 index 000000000..46cf7f48c --- /dev/null +++ b/security_access_token-yl_0822/.vscode/c_cpp_properties.json @@ -0,0 +1,19 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "cStandard": "c17", + "cppStandard": "c++17", + "intelliSenseMode": "windows-msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/security_access_token-yl_0822/.vscode/settings.json b/security_access_token-yl_0822/.vscode/settings.json new file mode 100644 index 000000000..d9ee1745f --- /dev/null +++ b/security_access_token-yl_0822/.vscode/settings.json @@ -0,0 +1,65 @@ +{ + "files.associations": { + "algorithm": "cpp", + "atomic": "cpp", + "bit": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "compare": "cpp", + "concepts": "cpp", + "condition_variable": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "deque": "cpp", + "exception": "cpp", + "fstream": "cpp", + "functional": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "ios": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "iterator": "cpp", + "limits": "cpp", + "list": "cpp", + "map": "cpp", + "memory": "cpp", + "mutex": "cpp", + "new": "cpp", + "ostream": "cpp", + "ratio": "cpp", + "set": "cpp", + "stdexcept": "cpp", + "stop_token": "cpp", + "streambuf": "cpp", + "string": "cpp", + "system_error": "cpp", + "thread": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "typeinfo": "cpp", + "unordered_map": "cpp", + "utility": "cpp", + "variant": "cpp", + "vector": "cpp", + "xfacet": "cpp", + "xhash": "cpp", + "xiosbase": "cpp", + "xlocale": "cpp", + "xlocinfo": "cpp", + "xlocnum": "cpp", + "xmemory": "cpp", + "xstddef": "cpp", + "xstring": "cpp", + "xtr1common": "cpp", + "xtree": "cpp", + "xutility": "cpp" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/BUILD.gn b/security_access_token-yl_0822/BUILD.gn new file mode 100644 index 000000000..f2f0f0bef --- /dev/null +++ b/security_access_token-yl_0822/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") + +group("accesstoken_build_module_test") { + testonly = true + deps = [] + if (is_standard_system) { + deps += [ + "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest", + "//base/security/access_token/interfaces/innerkits/nativetoken/test:unittest", + "//base/security/access_token/interfaces/innerkits/privacy/test:unittest", + "//base/security/access_token/interfaces/innerkits/token_setproc/test:unittest", + "//base/security/access_token/services/accesstokenmanager/test:unittest", + ] + } + if (token_sync_enable == true) { + deps += [ + "//base/security/access_token/interfaces/innerkits/tokensync/test:unittest", + "//base/security/access_token/services/tokensyncmanager/test/unittest/token_sync_service:unittest", + ] + } +} diff --git a/security_access_token-yl_0822/LICENSE b/security_access_token-yl_0822/LICENSE new file mode 100644 index 000000000..4947287f7 --- /dev/null +++ b/security_access_token-yl_0822/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/security_access_token-yl_0822/OAT.xml b/security_access_token-yl_0822/OAT.xml new file mode 100644 index 000000000..efff6e357 --- /dev/null +++ b/security_access_token-yl_0822/OAT.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/security_access_token-yl_0822/README.md b/security_access_token-yl_0822/README.md new file mode 100644 index 000000000..177f40424 --- /dev/null +++ b/security_access_token-yl_0822/README.md @@ -0,0 +1,82 @@ +# Access Control + + - [Introduction](#introduction) + - [Directory Structure](#directory-structure) + - [Usage](#usage) + - [Available APIs](#available-apis) + - [Usage Guidelines](#usage-guidelines) + - [Native Process](#native-process) + - [App HAP](#app-hap) + - [Repositories Involved](#repositories-involved) + +## Introduction + +AccessTokenManager (ATM) provides unified app permission management based on access tokens on OpenHarmony. + +The access token information of an app includes the app identifier (**APPID**), user ID, app twin index, app Ability Privilege Level (APL), and permission information. The access token of each app is identified by a 32-bit token identity (**TokenID**) in the device. + +The ATM module provides the following functions: +- Verifying app permissions based on the token ID before an app accesses sensitive data or calls an API. +- Obtaining access token information (for example, APL) based on the token ID. + +## Directory Structure + +``` +/base/security/access_token +├── frameworks # Stores code of basic functionalities. +│ ├── accesstoken # Stores code of the ATM framework. +│ ├── tokensync # Stores code of the access token synchronization framework. +│ └── common # Stores framework common code. +├── interfaces # Stores the APIs. +│ ├── innerkits # Stores internal APIs. +│ ├── accesstoken # Stores code of access token internal APIs. +│ ├── nativetoken # Stores code of native token APIs. +│ └── tokensync # Stores code of the internal APIs for access token synchronization. +└── services # Services + ├── accesstokenmanager # Stores ATM service code. + └── tokensyncmanager # Stores code of the access token synchronization service. +``` + +## Usage +### Available APIs + +| **API**| **Description**| +| --- | --- | +| AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); | Allocates a token ID to an app.| +| AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); | Allocates a local token ID to the app of a remote device.| +| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); | Updates token information.| +| int DeleteToken(AccessTokenID tokenID); | Deletes the app's token ID and information.| +| int GetTokenType(AccessTokenID tokenID); | Obtains the type of an access token.| +| int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); | Checks whether the native process corresponding to the given token ID has the specified distributed capability.| +| AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); | Obtains the token ID of an app.| +| int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); | Obtains the token information about a HAP.| +| int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); | Obtains information about a native token.| +| int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); | Checks whether an access token has the specified permission.| +| int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); | Obtains definition information about the specified permission.| +| int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); | Obtains the permission definition set of a HAP.| +| int GetReqPermissions(AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); | Obtains the status set of the permission requested by a HAP.| +| int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); | Obtains the permissions of the app with the specified token ID.| +| int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); | Grants the specified permission to the app with the specified token ID.| +| int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); | Revokes the specified permission from the app with the specified token ID.| +| int ClearUserGrantedPermissionState(AccessTokenID tokenID); | Clears the user_grant permission status of the app with the specified token ID.| +| uint64_t GetAccessTokenId(const char *processname, const char **dcap, int32_t dacpNum, const char *aplStr); | Obtains the token ID of a native process.| + +### Usage Guidelines +ATM provides unified access control for apps and allows apps or service abilities to obtain and verify app permissions and APL. The ATM APIs can be called by a service ability started by a native process or an app HAP. + +#### Native Process +- Before a native process starts, it calls **GetAccessTokenId** to obtain a token ID, and then calls **SetSelfTokenID** to set the token ID to the kernel. +- During the running of a native process, it calls **GetNativeTokenInfo** or **CheckNativeDCap** to obtain the token information, including the distributed capability and APL. + +#### App HAP +- When an app is installed, **AllocHapToken** is called to obtain the token ID of the app. +- When an authentication is required during app running, **VerifyAccessToken** or **GetReqPermissions** is called to obtain and verify the app permissions and APL. +- When an app is uninstalled, **DeleteToken** is called to delete the related access token information. + +## Repositories Involved + +[startup\_init\_lite](https://gitee.com/openharmony/startup_init_lite/blob/master/README.md) + +[security\_device\_auth](https://gitee.com/openharmony/security_device_auth/blob/master/README.md) + +[security\_access\_token](https://gitee.com/openharmony/security_access_token/blob/master/README.md) diff --git a/security_access_token-yl_0822/README_zh.md b/security_access_token-yl_0822/README_zh.md new file mode 100644 index 000000000..5405b3aba --- /dev/null +++ b/security_access_token-yl_0822/README_zh.md @@ -0,0 +1,82 @@ +# 访问控制 + + - [简介](#简介) + - [目录](#目录) + - [使用](#使用) + - [接口说明](#接口说明) + - [使用说明](#使用说明) + - [native进程](#native进程) + - [应用hap](#应用hap) + - [相关仓](#相关仓) + +## 简介 + +ATM(AccessTokenManager)是OpenHarmony上基于AccessToken构建的统一的应用权限管理能力。 + +应用的Accesstoken信息主要包括应用身份标识APPID、用户ID,应用分身索引、应用APL(Ability Privilege Level)等级、应用权限信息等。每个应用的Accesstoken信息由一个32bits的设备内唯一标识符TokenID(Token identity)来标识。 + +ATM模块主要提供如下功能: +- 提供基于TokenID的应用权限校验机制,应用访问敏感数据或者API时可以检查是否有对应的权限。 +- 提供基于TokenID的Accesstoken信息查询,应用可以根据TokenID查询自身的APL等级等信息。 + +## 目录 + +``` +/base/security/access_token +├── frameworks # 框架层,基础功能代码存放目录 +│ ├── accesstoken # Accesstoken管理框架代码存放目录 +│ ├── tokensync # Accesstoken信息同步框架代码存放目录 +│ └── common # 框架公共代码存放目录 +├── interfaces # 接口层 +│ └── innerkits # 内部接口层 +│ ├── accesstoken # Accesstoken内部接口代码存放目录 +│ ├── nativetoken # nativetoken内部接口代码存放目录 +│ └── tokensync # Accesstoken信息同步内部接口代码存放目录 +└── services # 服务层 + ├── accesstokenmanager # Accesstoken管理服务代码存放目录 + └── tokensyncmanager # Accesstoken信息同步服务代码存放目录 +``` + +## 使用 +### 接口说明 + +| **接口申明** | **接口描述** | +| --- | --- | +| AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); | 为应用进程分配一个tokenID | +| AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); | 为远端设备的应用进程分配一个本地tokenID | +| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); | 更新tokenId对应的tokenInfo信息 | +| int DeleteToken(AccessTokenID tokenID); | 删除应用tokenID及其对应的tokenInfo信息 | +| int GetTokenType(AccessTokenID tokenID); | 查询指定tokenID的类型 | +| int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); | 检测指定tokenID对应的native进程是否具有指定的分布式能力 | +| AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); | 查询指定应用的tokenId | +| int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); | 查询指定tokenID对应的hap包的tokenInfo信息 | +| int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); | 查询指定tokenID对应的native的tokenInfo信息 | +| int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); | 检查指定tokenID是否具有指定权限 | +| int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); | 查询指定权限的权限定义信息 | +| int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); | 查询指定tokenID对应的hap包的权限定义集合 | +| int GetReqPermissions(AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); | 查询指定tokenID对应的hap包申请的权限状态集合 | +| int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); | 查询指定tokenID的应用的指定权限 | +| int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); | 授予指定tokenID的应用的指定权限 | +| int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); | 撤销指定tokenID的应用的指定权限 | +| int ClearUserGrantedPermissionState(AccessTokenID tokenID); | 清空指定tokenID的应用的user_grant权限状态 | +| uint64_t GetAccessTokenId(const char *processname, const char **dcap, int32_t dacpNum, const char *aplStr); | 创建获取native进程的tokenId | + +### 使用说明 +ATM提供了统一的应用权限访问控制功能,支持应用程序或者SA查询校验应用权限、APL等信息。从使用者角度,可以分为基于native进程启动的SA和应用Hap两类使用者。 + +#### native进程 +- 在native进程拉起前,需要调用GetAccessTokenId函数,获取该native进程的TokenID;再调用SetSelfTokenID将进程TokenID设置到内核中。 +- 在native进程运行过程中,可以通过调用GetNativeTokenInfo、CheckNativeDCap来查验对应进程所具备的token信息,包括分布式能力、APL等级等信息。 + +#### 应用hap +- 在应用安装时,需要调用AllocHapToken创建获取该应用的TokenID。 +- 在应用运行过程中,需要进行鉴权等操作时,可调用VerifyAccessToken、GetReqPermissions等函数查询校验应用权限、APL等信息。 +- 在应用卸载时,需要调用DeleteToken函数删除系统中管理的对应Accesstoken信息。 + +## 相关仓 + +[startup\_init\_lite](https://gitee.com/openharmony/startup_init_lite/blob/master/README_zh.md) + +[security\_device\_auth](https://gitee.com/openharmony/security_device_auth/blob/master/README_zh.md) + +**[security\_access\_token](https://gitee.com/openharmony/security_access_token/blob/master/README_zh.md)** diff --git a/security_access_token-yl_0822/access_token.gni b/security_access_token-yl_0822/access_token.gni new file mode 100644 index 000000000..78eae8f65 --- /dev/null +++ b/security_access_token-yl_0822/access_token.gni @@ -0,0 +1,26 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (!defined(global_parts_info) || + defined(global_parts_info.distributedhardware_device_manager)) { + token_sync_enable = true +} else { + token_sync_enable = false +} + +if (!defined(global_parts_info) || + defined(global_parts_info.security_dlp_permission_service)) { + dlp_permission_enable = true +} else { + dlp_permission_enable = false +} diff --git a/security_access_token-yl_0822/bundle.json b/security_access_token-yl_0822/bundle.json new file mode 100644 index 000000000..49e9ec63e --- /dev/null +++ b/security_access_token-yl_0822/bundle.json @@ -0,0 +1,117 @@ +{ + "name": "@openharmony/access_token", + "description": "access_token", + "version": "3.1.0", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "base/security/access_token" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "access_token", + "subsystem": "security", + "syscap": [ + "SystemCapability.Security.AccessToken" + ], + "adapted_system_type": [ "standard" ], + "rom": "2048KB", + "ram": "5102KB", + "deps": { + "components": [ + "ability_tools", + "bounds_checking_function", + "bundle_framework", + "cjson", + "common", + "device_manager", + "dsoftbus", + "eventhandler", + "hiviewdfx_hilog_native", + "init", + "ipc", + "napi", + "safwk", + "samgr", + "selinux", + "startup_l2", + "zlib" + ], + "third_party": [ + "cJSON", + "sqlite", + "mbedtls" + ] + }, + "build": { + "group_type": { + "base_group": [ + "//base/security/access_token/tools:tools_atm" + ], + "fwk_group": [ + "//base/security/access_token/interfaces/kits:napi_packages" + ], + "service_group": [ + "//base/security/access_token/services/accesstokenmanager:accesstoken_manager_service", + "//base/security/access_token/services/accesstokenmanager/main/sa_profile:accesstoken_sa_profile_standard", + "//base/security/access_token/services/privacymanager:privacy_manager_service", + "//base/security/access_token/services/privacymanager/sa_profile:privacy_sa_profile_standard", + "//base/security/access_token/services/tokensyncmanager:tokensyncmanager" + ] + }, + "inner_kits": [ + { + "name": "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "header": { + "header_files": [ + "accesstoken_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/accesstoken/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "header": { + "header_files": [ + "nativetoken_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/nativetoken/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + "header": { + "header_files": [ + "privacy_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/privacy/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/token_callback:libtoken_callback_sdk", + "header": { + "header_files": [ + "token_callback_stub.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/token_callback/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + "header": { + "header_files": [ + "token_setproc.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/token_setproc/include" + } + } + ], + "test": [ + "//base/security/access_token/interfaces/kits/accesstoken/test/benchmarktest:benchmarktest", + "//base/security/access_token/test/fuzztest/access_token:fuzztest", + "//base/security/access_token:accesstoken_build_module_test" + ] + } + } +} diff --git a/security_access_token-yl_0822/frameworks/accesstoken/BUILD.gn b/security_access_token-yl_0822/frameworks/accesstoken/BUILD.gn new file mode 100644 index 000000000..bdc63b3da --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("accesstoken_communication_adapter_cxx_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] +} + +ohos_shared_library("accesstoken_communication_adapter_cxx") { + subsystem_name = "security" + part_name = "access_token" + + public_configs = [ ":accesstoken_communication_adapter_cxx_public_config" ] + + include_dirs = [ + "include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//commonlibrary/c_utils/base/include", + ] + + sources = [ + "src/hap_info_parcel.cpp", + "src/hap_policy_parcel.cpp", + "src/hap_token_info_for_sync_parcel.cpp", + "src/hap_token_info_parcel.cpp", + "src/native_token_info_for_sync_parcel.cpp", + "src/native_token_info_parcel.cpp", + "src/permission_def_parcel.cpp", + "src/permission_list_state_parcel.cpp", + "src/permission_state_change_info_parcel.cpp", + "src/permission_state_change_scope_parcel.cpp", + "src/permission_state_full_parcel.cpp", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_single", + ] +} diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/hap_info_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_info_parcel.h new file mode 100644 index 000000000..9334fd9eb --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_INFO_PARCEL_H +#define HAP_INFO_PARCEL_H + +#include "hap_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapInfoParcel final : public Parcelable { + HapInfoParcel() = default; + + ~HapInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapInfoParcel *Unmarshalling(Parcel &in); + + HapInfoParams hapInfoParameter; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_INFO_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/hap_policy_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_policy_parcel.h new file mode 100644 index 000000000..e70506e81 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_policy_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_POLICY_PARCEL_H +#define HAP_POLICY_PARCEL_H + +#include "hap_token_info.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapPolicyParcel final : public Parcelable { + HapPolicyParcel() = default; + + ~HapPolicyParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapPolicyParcel *Unmarshalling(Parcel &in); + + HapPolicyParams hapPolicyParameter; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_POLICY_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h new file mode 100644 index 000000000..b0c838402 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H +#define HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H + +#include "hap_token_info.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfoForSyncParcel final : public Parcelable { + HapTokenInfoForSyncParcel() = default; + + ~HapTokenInfoForSyncParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapTokenInfoForSyncParcel *Unmarshalling(Parcel &in); + + HapTokenInfoForSync hapTokenInfoForSyncParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H + diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_parcel.h new file mode 100644 index 000000000..4a83362c5 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/hap_token_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HAP_TOKEN_INFO_PARCEL_H +#define HAP_TOKEN_INFO_PARCEL_H + +#include "hap_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfoParcel final : public Parcelable { + HapTokenInfoParcel() = default; + + ~HapTokenInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapTokenInfoParcel *Unmarshalling(Parcel &in); + + HapTokenInfo hapTokenInfoParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_TOKEN_INFO_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/i_accesstoken_manager.h b/security_access_token-yl_0822/frameworks/accesstoken/include/i_accesstoken_manager.h new file mode 100644 index 000000000..d5216bf64 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/i_accesstoken_manager.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_ACCESSTOKEN_MANAGER_H +#define I_ACCESSTOKEN_MANAGER_H + +#include + +#include "access_token.h" +#include "errors.h" +#include "hap_info_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info_for_sync_parcel.h" +#include "hap_token_info_parcel.h" +#include "iremote_broker.h" +#include "i_permission_state_callback.h" +#include "native_token_info_for_sync_parcel.h" +#include "native_token_info_parcel.h" +#include "permission_def_parcel.h" +#include "permission_list_state_parcel.h" +#include "permission_state_full_parcel.h" +#include "permission_state_change_scope_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class IAccessTokenManager : public IRemoteBroker { +public: + static const int SA_ID_ACCESSTOKEN_MANAGER_SERVICE = 3503; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.IAccessTokenManager"); + + virtual int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) = 0; + virtual int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) = 0; + virtual int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) = 0; + virtual int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual PermissionOper GetSelfPermissionsState( + std::vector& permListParcel) = 0; + virtual int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) = 0; + virtual int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) = 0; + virtual int ClearUserGrantedPermissionState(AccessTokenID tokenID) = 0; + virtual AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) = 0; + virtual int DeleteToken(AccessTokenID tokenID) = 0; + virtual int GetTokenType(AccessTokenID tokenID) = 0; + virtual int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) = 0; + virtual AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) = 0; + virtual AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) = 0; + virtual int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) = 0; + virtual int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) = 0; + virtual int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, + const HapPolicyParcel& policyParcel) = 0; + virtual int32_t RegisterPermStateChangeCallback( + const PermStateChangeScopeParcel& scope, const sptr& callback) = 0; + virtual int32_t UnRegisterPermStateChangeCallback(const sptr& callback) = 0; + +#ifdef TOKEN_SYNC_ENABLE + virtual int GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + virtual int GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) = 0; + virtual int SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + virtual int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoForSyncParcel) = 0; + virtual int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual int DeleteRemoteDeviceTokens(const std::string& deviceID) = 0; +#endif + + virtual void DumpTokenInfo(AccessTokenID tokenID, std::string& tokenInfo) = 0; + + enum class InterfaceCode { + VERIFY_ACCESSTOKEN = 0xff10, + GET_DEF_PERMISSION = 0xff11, + GET_DEF_PERMISSIONS = 0xff12, + GET_REQ_PERMISSIONS = 0xff13, + GET_PERMISSION_FLAG = 0xff14, + GRANT_PERMISSION = 0xff15, + REVOKE_PERMISSION = 0xff16, + CLEAR_USER_GRANT_PERMISSION = 0xff17, + ALLOC_TOKEN_HAP = 0xff18, + TOKEN_DELETE = 0xff19, + GET_TOKEN_TYPE = 0xff20, + CHECK_NATIVE_DCAP = 0xff21, + GET_HAP_TOKEN_ID = 0xff22, + ALLOC_LOCAL_TOKEN_ID = 0xff23, + GET_NATIVE_TOKENINFO = 0xff24, + GET_HAP_TOKENINFO = 0xff25, + UPDATE_HAP_TOKEN = 0xff26, + + GET_HAP_TOKEN_FROM_REMOTE = 0xff27, + GET_ALL_NATIVE_TOKEN_FROM_REMOTE = 0xff28, + SET_REMOTE_HAP_TOKEN_INFO = 0xff29, + SET_REMOTE_NATIVE_TOKEN_INFO = 0xff2a, + DELETE_REMOTE_TOKEN_INFO = 0xff2b, + DELETE_REMOTE_DEVICE_TOKEN = 0xff2c, + VERIFY_NATIVETOKEN = 0xff2d, + GET_NATIVE_REMOTE_TOKEN = 0xff2f, + + DUMP_TOKENINFO = 0xff30, + GET_PERMISSION_OPER_STATE = 0xff31, + REGISTER_PERM_STATE_CHANGE_CALLBACK = 0xff32, + UNREGISTER_PERM_STATE_CHANGE_CALLBACK = 0xff33, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // I_ACCESSTOKEN_MANAGER_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/i_permission_state_callback.h b/security_access_token-yl_0822/frameworks/accesstoken/include/i_permission_state_callback.h new file mode 100644 index 000000000..508f28c1e --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/i_permission_state_callback.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_PERMISSION_STATE_CALLBACK_H +#define I_PERMISSION_STATE_CALLBACK_H + +#include + +#include "access_token.h" +#include "errors.h" +#include "iremote_broker.h" +#include "permission_state_change_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class IPermissionStateCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.IPermissionStateCallback"); + + virtual void PermStateChangeCallback(PermStateChangeInfo& result) = 0; + + enum { + PERMISSION_STATE_CHANGE = 0, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // I_PERMISSION_STATE_CALLBACK_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_for_sync_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_for_sync_parcel.h new file mode 100644 index 000000000..a4b6b397c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_for_sync_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_TOKEN_INFO_FOR_SYNC_PARCEL_H +#define NATIVE_TOKEN_INFO_FOR_SYNC_PARCEL_H + +#include "native_token_info.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct NativeTokenInfoForSyncParcel final : public Parcelable { + NativeTokenInfoForSyncParcel() = default; + + ~NativeTokenInfoForSyncParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static NativeTokenInfoForSyncParcel *Unmarshalling(Parcel &in); + + NativeTokenInfoForSync nativeTokenInfoForSyncParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // NATIVE_TOKEN_INFO_FOR_SYNC_PARCEL_H + diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_parcel.h new file mode 100644 index 000000000..80ec39284 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/native_token_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_TOKEN_INFO_PARCEL_H +#define NATIVE_TOKEN_INFO_PARCEL_H + +#include "native_token_info.h" + +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct NativeTokenInfoParcel final : public Parcelable { + NativeTokenInfoParcel() = default; + + ~NativeTokenInfoParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static NativeTokenInfoParcel *Unmarshalling(Parcel &in); + + NativeTokenInfo nativeTokenInfoParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // NATIVE_TOKEN_INFO_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/permission_def_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_def_parcel.h new file mode 100644 index 000000000..c509deb91 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_def_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_DEF_PARCEL_H +#define PERMISSION_DEF_PARCEL_H + +#include "permission_def.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionDefParcel final : public Parcelable { + PermissionDefParcel() = default; + + ~PermissionDefParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static PermissionDefParcel *Unmarshalling(Parcel &in); + + PermissionDef permissionDef; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_DEF_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/permission_list_state_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_list_state_parcel.h new file mode 100644 index 000000000..c2c180fae --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_list_state_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_LIST_STATE_PARCEL_H +#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_LIST_STATE_PARCEL_H + +#include "permission_list_state.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionListStateParcel final : public Parcelable { + PermissionListStateParcel() = default; + + ~PermissionListStateParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static PermissionListStateParcel *Unmarshalling(Parcel &in); + + PermissionListState permsState; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_LIST_STATE_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_info_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_info_parcel.h new file mode 100644 index 000000000..eb95593c3 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_info_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_INFO_PARCEL_H +#define PERMISSION_STATE_CHANGE_INFO_PARCEL_H + +#include "parcel.h" +#include "permission_state_change_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionStateChangeInfoParcel final : public Parcelable { + PermissionStateChangeInfoParcel() = default; + + ~PermissionStateChangeInfoParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static PermissionStateChangeInfoParcel* Unmarshalling(Parcel& in); + + PermStateChangeInfo changeInfo; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_STATE_CHANGE_INFO_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_scope_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_scope_parcel.h new file mode 100644 index 000000000..e1988a8f2 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_change_scope_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_SCOPE_PARCEL_H +#define PERMISSION_STATE_CHANGE_SCOPE_PARCEL_H + +#include "parcel.h" +#include "permission_state_change_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermStateChangeScopeParcel final : public Parcelable { + PermStateChangeScopeParcel() = default; + + ~PermStateChangeScopeParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static PermStateChangeScopeParcel* Unmarshalling(Parcel& in); + + PermStateChangeScope scope; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_STATE_CHANGE_SCOPE_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_full_parcel.h b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_full_parcel.h new file mode 100644 index 000000000..71e869ed1 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/include/permission_state_full_parcel.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H +#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H + +#include "permission_state_full.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionStateFullParcel final : public Parcelable { + PermissionStateFullParcel() = default; + + ~PermissionStateFullParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static PermissionStateFullParcel *Unmarshalling(Parcel &in); + + PermissionStateFull permStatFull; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_STATE_FULL_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/hap_info_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_info_parcel.cpp new file mode 100644 index 000000000..9a170e196 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_info_parcel.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_info_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool HapInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.userID)); + RETURN_IF_FALSE(out.WriteString(this->hapInfoParameter.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.instIndex)); + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.dlpType)); + RETURN_IF_FALSE(out.WriteString(this->hapInfoParameter.appIDDesc)); + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.apiVersion)); + return true; +} + +HapInfoParcel* HapInfoParcel::Unmarshalling(Parcel& in) +{ + auto* hapInfoParcel = new (std::nothrow) HapInfoParcel(); + RELEASE_IF_FALSE(hapInfoParcel != nullptr, hapInfoParcel); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.userID), hapInfoParcel); + hapInfoParcel->hapInfoParameter.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.instIndex), hapInfoParcel); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.dlpType), hapInfoParcel); + hapInfoParcel->hapInfoParameter.appIDDesc = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.apiVersion), hapInfoParcel); + + return hapInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/hap_policy_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_policy_parcel.cpp new file mode 100644 index 000000000..6bbccf7de --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_policy_parcel.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_policy_parcel.h" +#include "refbase.h" +#include "access_token.h" +#include "parcel_utils.h" +#include "permission_def.h" +#include "permission_def_parcel.h" +#include "permission_state_full.h" +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool HapPolicyParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapPolicyParameter.apl)); + RETURN_IF_FALSE(out.WriteString(this->hapPolicyParameter.domain)); + + const std::vector& permList = this->hapPolicyParameter.permList; + int32_t permListSize = static_cast(permList.size()); + RETURN_IF_FALSE(out.WriteInt32(permListSize)); + + for (int i = 0; i < permListSize; i++) { + PermissionDefParcel permDefParcel; + permDefParcel.permissionDef = permList[i]; + out.WriteParcelable(&permDefParcel); + } + + const std::vector& permStateList = this->hapPolicyParameter.permStateList; + int32_t permStateListSize = static_cast(permStateList.size()); + RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); + + for (int i = 0; i < permStateListSize; i++) { + PermissionStateFullParcel permStateParcel; + permStateParcel.permStatFull = permStateList[i]; + out.WriteParcelable(&permStateParcel); + } + + return true; +} + +HapPolicyParcel* HapPolicyParcel::Unmarshalling(Parcel& in) +{ + auto* hapPolicyParcel = new (std::nothrow) HapPolicyParcel(); + RELEASE_IF_FALSE(hapPolicyParcel != nullptr, hapPolicyParcel); + + int32_t apl; + RELEASE_IF_FALSE(in.ReadInt32(apl), hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.apl = ATokenAplEnum(apl); + + hapPolicyParcel->hapPolicyParameter.domain = in.ReadString(); + + int permListSize; + RELEASE_IF_FALSE(in.ReadInt32(permListSize), hapPolicyParcel); + + for (int i = 0; i < permListSize; i++) { + sptr permDefParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permDefParcel != nullptr, hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.permList.emplace_back(permDefParcel->permissionDef); + } + + int permStateListSize; + RELEASE_IF_FALSE(in.ReadInt32(permStateListSize), hapPolicyParcel); + for (int i = 0; i < permStateListSize; i++) { + sptr permissionStateParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, hapPolicyParcel); + hapPolicyParcel->hapPolicyParameter.permStateList.emplace_back(permissionStateParcel->permStatFull); + } + return hapPolicyParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp new file mode 100644 index 000000000..17b04b3a5 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_token_info_for_sync_parcel.h" +#include "refbase.h" +#include "hap_token_info_parcel.h" +#include "parcel_utils.h" +#include "permission_state_full.h" +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool HapTokenInfoForSyncParcel::Marshalling(Parcel& out) const +{ + HapTokenInfoParcel baseInfoParcel; + baseInfoParcel.hapTokenInfoParams = this->hapTokenInfoForSyncParams.baseInfo; + out.WriteParcelable(&baseInfoParcel); + + const std::vector& permStateList = this->hapTokenInfoForSyncParams.permStateList; + int32_t permStateListSize = static_cast(permStateList.size()); + RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); + RETURN_IF_FALSE((permStateListSize <= MAX_PERMLIST_SIZE)); + for (int i = 0; i < permStateListSize; i++) { + PermissionStateFullParcel permStateParcel; + permStateParcel.permStatFull = permStateList[i]; + out.WriteParcelable(&permStateParcel); + } + + return true; +} + +HapTokenInfoForSyncParcel* HapTokenInfoForSyncParcel::Unmarshalling(Parcel& in) +{ + auto* hapTokenInfoForSyncParcel = new (std::nothrow) HapTokenInfoForSyncParcel(); + RELEASE_IF_FALSE(hapTokenInfoForSyncParcel != nullptr, hapTokenInfoForSyncParcel); + + sptr baseInfoParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(baseInfoParcel != nullptr, hapTokenInfoForSyncParcel); + hapTokenInfoForSyncParcel->hapTokenInfoForSyncParams.baseInfo = baseInfoParcel->hapTokenInfoParams; + + int permStateListSize; + RELEASE_IF_FALSE(in.ReadInt32(permStateListSize), hapTokenInfoForSyncParcel); + for (int i = 0; i < permStateListSize; i++) { + sptr permissionStateParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, hapTokenInfoForSyncParcel); + hapTokenInfoForSyncParcel->hapTokenInfoForSyncParams.permStateList.emplace_back( + permissionStateParcel->permStatFull); + } + return hapTokenInfoForSyncParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_parcel.cpp new file mode 100644 index 000000000..6d209ca4b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/hap_token_info_parcel.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_token_info_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool HapTokenInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.apl)); + RETURN_IF_FALSE(out.WriteUint8(this->hapTokenInfoParams.ver)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.userID)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.apiVersion)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.instIndex)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.dlpType)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.appID)); + RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.deviceID)); + RETURN_IF_FALSE(out.WriteUint32(this->hapTokenInfoParams.tokenID)); + RETURN_IF_FALSE(out.WriteUint32(this->hapTokenInfoParams.tokenAttr)); + return true; +} + +HapTokenInfoParcel* HapTokenInfoParcel::Unmarshalling(Parcel& in) +{ + auto* hapTokenInfoParcel = new (std::nothrow) HapTokenInfoParcel(); + RELEASE_IF_FALSE(hapTokenInfoParcel != nullptr, hapTokenInfoParcel); + int apl; + uint8_t ver; + RELEASE_IF_FALSE(in.ReadInt32(apl), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.apl = ATokenAplEnum(apl); + RELEASE_IF_FALSE(in.ReadUint8(ver), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.ver = ver; + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.userID), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.apiVersion), hapTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.instIndex), hapTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.dlpType), hapTokenInfoParcel); + hapTokenInfoParcel->hapTokenInfoParams.appID = in.ReadString(); + hapTokenInfoParcel->hapTokenInfoParams.deviceID = in.ReadString(); + RELEASE_IF_FALSE(in.ReadUint32(hapTokenInfoParcel->hapTokenInfoParams.tokenID), hapTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadUint32(hapTokenInfoParcel->hapTokenInfoParams.tokenAttr), hapTokenInfoParcel); + return hapTokenInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_for_sync_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_for_sync_parcel.cpp new file mode 100644 index 000000000..6b0f65ed6 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_for_sync_parcel.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_info_for_sync_parcel.h" +#include "refbase.h" +#include "native_token_info_parcel.h" +#include "parcel_utils.h" +#include "permission_state_full.h" +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool NativeTokenInfoForSyncParcel::Marshalling(Parcel& out) const +{ + NativeTokenInfoParcel baseInfoParcel; + baseInfoParcel.nativeTokenInfoParams = this->nativeTokenInfoForSyncParams.baseInfo; + RETURN_IF_FALSE(out.WriteParcelable(&baseInfoParcel)); + + const std::vector& permStateList = this->nativeTokenInfoForSyncParams.permStateList; + int32_t permStateListSize = static_cast(permStateList.size()); + RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); + RETURN_IF_FALSE((permStateListSize <= MAX_PERMLIST_SIZE)); + for (int i = 0; i < permStateListSize; i++) { + PermissionStateFullParcel permStateParcel; + permStateParcel.permStatFull = permStateList[i]; + RETURN_IF_FALSE(out.WriteParcelable(&permStateParcel)); + } + + return true; +} + +NativeTokenInfoForSyncParcel* NativeTokenInfoForSyncParcel::Unmarshalling(Parcel& in) +{ + auto* nativeTokenInfoForSyncParcel = new (std::nothrow) NativeTokenInfoForSyncParcel(); + RELEASE_IF_FALSE(nativeTokenInfoForSyncParcel != nullptr, nativeTokenInfoForSyncParcel); + + sptr baseInfoParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(baseInfoParcel != nullptr, nativeTokenInfoForSyncParcel); + nativeTokenInfoForSyncParcel->nativeTokenInfoForSyncParams.baseInfo = baseInfoParcel->nativeTokenInfoParams; + + int permStateListSize; + RELEASE_IF_FALSE(in.ReadInt32(permStateListSize), nativeTokenInfoForSyncParcel); + for (int i = 0; i < permStateListSize; i++) { + sptr permissionStateParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, nativeTokenInfoForSyncParcel); + nativeTokenInfoForSyncParcel->nativeTokenInfoForSyncParams.permStateList.emplace_back( + permissionStateParcel->permStatFull); + } + return nativeTokenInfoForSyncParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_parcel.cpp new file mode 100644 index 000000000..621ce872c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/native_token_info_parcel.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_info_parcel.h" +#include +#include +#include +#include +#include "access_token.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool NativeTokenInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->nativeTokenInfoParams.apl)); + RETURN_IF_FALSE(out.WriteUint8(this->nativeTokenInfoParams.ver)); + RETURN_IF_FALSE(out.WriteString(this->nativeTokenInfoParams.processName)); + RETURN_IF_FALSE(out.WriteUint32(this->nativeTokenInfoParams.tokenID)); + RETURN_IF_FALSE(out.WriteUint32(this->nativeTokenInfoParams.tokenAttr)); + + if ((this->nativeTokenInfoParams.dcap).size() > INT32_MAX) { + return false; + } + int32_t dcapSize = static_cast((this->nativeTokenInfoParams.dcap).size()); + RETURN_IF_FALSE(out.WriteInt32(dcapSize)); + + for (const auto& dcapItem : this->nativeTokenInfoParams.dcap) { + RETURN_IF_FALSE(out.WriteString(dcapItem)); + } + + if ((this->nativeTokenInfoParams.nativeAcls).size() > INT32_MAX) { + return false; + } + int32_t nativeAclSize = static_cast((this->nativeTokenInfoParams.nativeAcls).size()); + RETURN_IF_FALSE(out.WriteInt32(nativeAclSize)); + + for (const auto& item : this->nativeTokenInfoParams.nativeAcls) { + RETURN_IF_FALSE(out.WriteString(item)); + } + + return true; +} + +NativeTokenInfoParcel* NativeTokenInfoParcel::Unmarshalling(Parcel& in) +{ + auto* nativeTokenInfoParcel = new (std::nothrow) NativeTokenInfoParcel(); + RELEASE_IF_FALSE(nativeTokenInfoParcel != nullptr, nativeTokenInfoParcel); + + int32_t apl; + uint8_t ver; + RELEASE_IF_FALSE(in.ReadInt32(apl), nativeTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadUint8(ver), nativeTokenInfoParcel); + nativeTokenInfoParcel->nativeTokenInfoParams.apl = ATokenAplEnum(apl); + nativeTokenInfoParcel->nativeTokenInfoParams.ver = ver; + + nativeTokenInfoParcel->nativeTokenInfoParams.processName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadUint32(nativeTokenInfoParcel->nativeTokenInfoParams.tokenID), nativeTokenInfoParcel); + RELEASE_IF_FALSE(in.ReadUint32(nativeTokenInfoParcel->nativeTokenInfoParams.tokenAttr), nativeTokenInfoParcel); + + int32_t dcapSize; + RELEASE_IF_FALSE(in.ReadInt32(dcapSize), nativeTokenInfoParcel); + + for (int32_t i = 0; i < dcapSize; i++) { + std::string dcapsItem; + RELEASE_IF_FALSE(in.ReadString(dcapsItem), nativeTokenInfoParcel); + nativeTokenInfoParcel->nativeTokenInfoParams.dcap.emplace_back(dcapsItem); + } + + int32_t nativeAclSize; + RELEASE_IF_FALSE(in.ReadInt32(nativeAclSize), nativeTokenInfoParcel); + + for (int32_t i = 0; i < nativeAclSize; i++) { + std::string item; + RELEASE_IF_FALSE(in.ReadString(item), nativeTokenInfoParcel); + nativeTokenInfoParcel->nativeTokenInfoParams.nativeAcls.emplace_back(item); + } + return nativeTokenInfoParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/permission_def_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_def_parcel.cpp new file mode 100644 index 000000000..4ca7b3d2a --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_def_parcel.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_def_parcel.h" + +#include "access_token.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionDefParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permissionDef.permissionName)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.grantMode)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.availableLevel)); + RETURN_IF_FALSE(out.WriteBool(this->permissionDef.provisionEnable)); + RETURN_IF_FALSE(out.WriteBool(this->permissionDef.distributedSceneEnable)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.label)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.labelId)); + RETURN_IF_FALSE(out.WriteString(this->permissionDef.description)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.descriptionId)); + return true; +} + +PermissionDefParcel* PermissionDefParcel::Unmarshalling(Parcel& in) +{ + auto* permissionDefParcel = new (std::nothrow) PermissionDefParcel(); + RELEASE_IF_FALSE(permissionDefParcel != nullptr, permissionDefParcel); + permissionDefParcel->permissionDef.permissionName = in.ReadString(); + permissionDefParcel->permissionDef.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.grantMode), permissionDefParcel); + + int level; + RELEASE_IF_FALSE(in.ReadInt32(level), permissionDefParcel); + permissionDefParcel->permissionDef.availableLevel = ATokenAplEnum(level); + + RELEASE_IF_FALSE(in.ReadBool(permissionDefParcel->permissionDef.provisionEnable), permissionDefParcel); + RELEASE_IF_FALSE(in.ReadBool(permissionDefParcel->permissionDef.distributedSceneEnable), permissionDefParcel); + permissionDefParcel->permissionDef.label = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.labelId), permissionDefParcel); + permissionDefParcel->permissionDef.description = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.descriptionId), permissionDefParcel); + return permissionDefParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/permission_list_state_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_list_state_parcel.cpp new file mode 100644 index 000000000..5fe05d917 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_list_state_parcel.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_list_state_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionListStateParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permsState.permissionName)); + RETURN_IF_FALSE(out.WriteInt32(this->permsState.state)); + return true; +} + +PermissionListStateParcel* PermissionListStateParcel::Unmarshalling(Parcel& in) +{ + auto* permissionStateParcel = new (std::nothrow) PermissionListStateParcel(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, permissionStateParcel); + + RELEASE_IF_FALSE(in.ReadString(permissionStateParcel->permsState.permissionName), permissionStateParcel); + RELEASE_IF_FALSE(in.ReadInt32(permissionStateParcel->permsState.state), permissionStateParcel); + + return permissionStateParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_info_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_info_parcel.cpp new file mode 100644 index 000000000..173a2d25b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_info_parcel.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_change_info_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionStateChangeInfoParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->changeInfo.PermStateChangeType)); + RETURN_IF_FALSE(out.WriteUint32(this->changeInfo.tokenID)); + RETURN_IF_FALSE(out.WriteString(this->changeInfo.permissionName)); + return true; +} + +PermissionStateChangeInfoParcel* PermissionStateChangeInfoParcel::Unmarshalling(Parcel& in) +{ + auto* permissionStateParcel = new (std::nothrow) PermissionStateChangeInfoParcel(); + if (permissionStateParcel == nullptr) { + return nullptr; + } + RELEASE_IF_FALSE(in.ReadInt32(permissionStateParcel->changeInfo.PermStateChangeType), permissionStateParcel); + RELEASE_IF_FALSE(in.ReadUint32(permissionStateParcel->changeInfo.tokenID), permissionStateParcel); + RELEASE_IF_FALSE(in.ReadString(permissionStateParcel->changeInfo.permissionName), permissionStateParcel); + + return permissionStateParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp new file mode 100644 index 000000000..8555df353 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_change_scope_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermStateChangeScopeParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteUint32((this->scope.tokenIDs.size()))); + for (const auto& tokenID : this->scope.tokenIDs) { + RETURN_IF_FALSE(out.WriteUint32(tokenID)); + } + + RETURN_IF_FALSE(out.WriteUint32((this->scope.permList.size()))); + for (const auto& permissionName : this->scope.permList) { + RETURN_IF_FALSE(out.WriteString(permissionName)); + } + return true; +} + +PermStateChangeScopeParcel* PermStateChangeScopeParcel::Unmarshalling(Parcel& in) +{ + auto* permStateChangeScopeParcel = new (std::nothrow) PermStateChangeScopeParcel(); + if (permStateChangeScopeParcel == nullptr) { + return nullptr; + } + uint32_t tokenIdListSize = 0; + RELEASE_IF_FALSE(in.ReadUint32(tokenIdListSize), permStateChangeScopeParcel); + RELEASE_IF_FALSE(tokenIdListSize <= TOKENIDS_LIST_SIZE_MAX, permStateChangeScopeParcel); + for (uint32_t i = 0; i < tokenIdListSize; i++) { + AccessTokenID tokenID; + RELEASE_IF_FALSE(in.ReadUint32(tokenID), permStateChangeScopeParcel); + permStateChangeScopeParcel->scope.tokenIDs.emplace_back(tokenID); + } + + uint32_t permListSize = 0; + RELEASE_IF_FALSE(in.ReadUint32(permListSize), permStateChangeScopeParcel); + RELEASE_IF_FALSE(permListSize <= PERMS_LIST_SIZE_MAX, permStateChangeScopeParcel); + for (uint32_t i = 0; i < permListSize; i++) { + std::string permName; + RELEASE_IF_FALSE(in.ReadString(permName), permStateChangeScopeParcel); + permStateChangeScopeParcel->scope.permList.emplace_back(permName); + } + return permStateChangeScopeParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_full_parcel.cpp b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_full_parcel.cpp new file mode 100644 index 000000000..1919f9d52 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/accesstoken/src/permission_state_full_parcel.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_full_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionStateFullParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permStatFull.permissionName)); + RETURN_IF_FALSE(out.WriteBool(this->permStatFull.isGeneral)); + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->permStatFull.resDeviceID.size()))); + for (auto devId : this->permStatFull.resDeviceID) { + RETURN_IF_FALSE(out.WriteString(devId)); + } + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->permStatFull.grantStatus.size()))); + for (auto grantStat : this->permStatFull.grantStatus) { + RETURN_IF_FALSE(out.WriteInt32(grantStat)); + } + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->permStatFull.grantFlags.size()))); + for (auto grantFlag : this->permStatFull.grantFlags) { + RETURN_IF_FALSE(out.WriteInt32(grantFlag)); + } + return true; +} + +PermissionStateFullParcel* PermissionStateFullParcel::Unmarshalling(Parcel& in) +{ + auto* permissionStateParcel = new (std::nothrow) PermissionStateFullParcel(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, permissionStateParcel); + + RELEASE_IF_FALSE(in.ReadString(permissionStateParcel->permStatFull.permissionName), permissionStateParcel); + RELEASE_IF_FALSE(in.ReadBool(permissionStateParcel->permStatFull.isGeneral), permissionStateParcel); + + int resIdSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(resIdSize), permissionStateParcel); + for (int i = 0; i < resIdSize; i++) { + std::string resId; + RELEASE_IF_FALSE(in.ReadString(resId), permissionStateParcel); + permissionStateParcel->permStatFull.resDeviceID.emplace_back(resId); + } + + int grantStatsSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(grantStatsSize), permissionStateParcel); + for (int i = 0; i < grantStatsSize; i++) { + int grantStat; + RELEASE_IF_FALSE(in.ReadInt32(grantStat), permissionStateParcel); + permissionStateParcel->permStatFull.grantStatus.emplace_back(grantStat); + } + + int grantFlagSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(grantFlagSize), permissionStateParcel); + for (int i = 0; i < grantFlagSize; i++) { + int flag; + RELEASE_IF_FALSE(in.ReadInt32(flag), permissionStateParcel); + permissionStateParcel->permStatFull.grantFlags.emplace_back(flag); + } + return permissionStateParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/.gitignore b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/.gitignore new file mode 100644 index 000000000..39187ebed --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/.gitignore @@ -0,0 +1,4 @@ +/node_modules +/local.properties +/.idea +**/build \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/app.json5 b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/app.json5 new file mode 100644 index 000000000..22b0ce94e --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/app.json5 @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "app": { + "bundleName": "com.ohos.permissionmanager", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/element/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/element/string.json new file mode 100644 index 000000000..4fe2f8594 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "权限管理" + } + ] +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/media/app_icon.png b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c GIT binary patch literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}yR?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y= 2.1.2 < 3.0.0" + } + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "ini": { + "version": "1.3.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "interpret": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/interpret/-/interpret-1.4.0.tgz", + "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==" + }, + "invert-kv": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/invert-kv/-/invert-kv-1.0.0.tgz", + "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=" + }, + "is-absolute": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "requires": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=" + }, + "is-core-module": { + "version": "2.8.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-core-module/-/is-core-module-2.8.1.tgz", + "integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==", + "requires": { + "has": "^1.0.3" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "is-glob": { + "version": "4.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==" + }, + "is-plain-object": { + "version": "5.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" + }, + "is-relative": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "requires": { + "is-unc-path": "^1.0.0" + } + }, + "is-stream": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==" + }, + "is-unc-path": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "requires": { + "unc-path-regex": "^0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=" + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" + }, + "json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, + "json5": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/json5/-/json5-2.2.0.tgz", + "integrity": "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==", + "requires": { + "minimist": "^1.2.5" + } + }, + "jsonfile": { + "version": "6.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "kind-of": { + "version": "6.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==" + }, + "last-run": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/last-run/-/last-run-1.1.1.tgz", + "integrity": "sha1-RblpQsF7HHnHchmCWbqUO+v4yls=", + "requires": { + "default-resolution": "^2.0.0", + "es6-weak-map": "^2.0.1" + } + }, + "lazystream": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/lazystream/-/lazystream-1.0.1.tgz", + "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", + "requires": { + "readable-stream": "^2.0.5" + }, + "dependencies": { + "readable-stream": { + "version": "2.3.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + } + } + }, + "lcid": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lcid/-/lcid-1.0.0.tgz", + "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", + "requires": { + "invert-kv": "^1.0.0" + } + }, + "liftoff": { + "version": "4.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/liftoff/-/liftoff-4.0.0.tgz", + "integrity": "sha512-rMGwYF8q7g2XhG2ulBmmJgWv25qBsqRbDn5gH0+wnuyeFt7QBJlHJmtg5qEdn4pN6WVAUMgXnIxytMFRX9c1aA==", + "requires": { + "extend": "^3.0.2", + "findup-sync": "^5.0.0", + "fined": "^2.0.0", + "flagged-respawn": "^2.0.0", + "is-plain-object": "^5.0.0", + "object.map": "^1.0.1", + "rechoir": "^0.8.0", + "resolve": "^1.20.0" + } + }, + "load-json-file": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/load-json-file/-/load-json-file-1.1.0.tgz", + "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" + } + }, + "lodash": { + "version": "4.17.21", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "lodash.defaults": { + "version": "4.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=" + }, + "lodash.difference": { + "version": "4.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.difference/-/lodash.difference-4.5.0.tgz", + "integrity": "sha1-nMtOUF1Ia5FlE0V3KIWi3yf9AXw=" + }, + "lodash.flatten": { + "version": "4.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.flatten/-/lodash.flatten-4.4.0.tgz", + "integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.union": { + "version": "4.6.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/lodash.union/-/lodash.union-4.6.0.tgz", + "integrity": "sha1-SLtQiECfFvGCFmZkHETdGqrjzYg=" + }, + "log4js": { + "version": "6.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/log4js/-/log4js-6.4.1.tgz", + "integrity": "sha512-iUiYnXqAmNKiIZ1XSAitQ4TmNs8CdZYTAWINARF3LjnsLN8tY5m0vRwd6uuWj/yNY0YHxeZodnbmxKFUOM2rMg==", + "requires": { + "date-format": "^4.0.3", + "debug": "^4.3.3", + "flatted": "^3.2.4", + "rfdc": "^1.3.0", + "streamroller": "^3.0.2" + } + }, + "make-iterator": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/make-iterator/-/make-iterator-1.0.1.tgz", + "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "requires": { + "kind-of": "^6.0.2" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=" + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "micromatch": { + "version": "4.0.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "requires": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimist/-/minimist-1.2.6.tgz", + "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "mute-stdout": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/mute-stdout/-/mute-stdout-1.0.0.tgz", + "integrity": "sha1-WzLqB+tDyd7WEwQ0z5JvRrKn/U0=" + }, + "next-tick": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/next-tick/-/next-tick-1.1.0.tgz", + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" + }, + "now-and-later": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/now-and-later/-/now-and-later-2.0.1.tgz", + "integrity": "sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ==", + "requires": { + "once": "^1.3.2" + } + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "requires": { + "path-key": "^3.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + }, + "object.defaults": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "requires": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "object.map": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "requires": { + "isobject": "^3.0.1" + } + }, + "object.reduce": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/object.reduce/-/object.reduce-1.0.1.tgz", + "integrity": "sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60=", + "requires": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "os-locale": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/os-locale/-/os-locale-1.4.0.tgz", + "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", + "requires": { + "lcid": "^1.0.0" + } + }, + "parse-filepath": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", + "requires": { + "is-absolute": "^1.0.0", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + } + }, + "parse-json": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/parse-json/-/parse-json-2.2.0.tgz", + "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", + "requires": { + "error-ex": "^1.2.0" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=" + }, + "path-exists": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-exists/-/path-exists-2.1.0.tgz", + "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", + "requires": { + "pinkie-promise": "^2.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" + }, + "path-parse": { + "version": "1.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" + }, + "path-root": { + "version": "0.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "requires": { + "path-root-regex": "^0.1.0" + } + }, + "path-root-regex": { + "version": "0.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=" + }, + "path-type": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/path-type/-/path-type-1.1.0.tgz", + "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", + "requires": { + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" + } + }, + "picomatch": { + "version": "2.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" + }, + "pify": { + "version": "2.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" + }, + "pinkie": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=" + }, + "pinkie-promise": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", + "requires": { + "pinkie": "^2.0.0" + } + }, + "pretty-hrtime": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/pretty-hrtime/-/pretty-hrtime-1.0.0.tgz", + "integrity": "sha1-9ualItPmBwRSK/Db5oVu0g515Nw=" + }, + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" + }, + "read-pkg": { + "version": "1.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/read-pkg/-/read-pkg-1.1.0.tgz", + "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", + "requires": { + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" + } + }, + "read-pkg-up": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/read-pkg-up/-/read-pkg-up-1.0.1.tgz", + "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", + "requires": { + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" + } + }, + "readable-stream": { + "version": "3.6.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/readable-stream/-/readable-stream-3.6.0.tgz", + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "readdir-glob": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/readdir-glob/-/readdir-glob-1.1.1.tgz", + "integrity": "sha512-91/k1EzZwDx6HbERR+zucygRFfiPl2zkIYZtv3Jjr6Mn7SkKcVct8aVO+sSRiGMc6fLf72du3d92/uY63YPdEA==", + "requires": { + "minimatch": "^3.0.4" + } + }, + "rechoir": { + "version": "0.8.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "requires": { + "resolve": "^1.20.0" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" + }, + "require-from-string": { + "version": "2.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==" + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=" + }, + "resolve": { + "version": "1.22.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve/-/resolve-1.22.0.tgz", + "integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==", + "requires": { + "is-core-module": "^2.8.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + } + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-package-path": { + "version": "4.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/resolve-package-path/-/resolve-package-path-4.0.3.tgz", + "integrity": "sha512-SRpNAPW4kewOaNUt8VPqhJ0UMxawMwzJD8V7m1cJfdSTK9ieZwS6K7Dabsm4bmLFM96Z5Y/UznrpG5kt1im8yA==", + "requires": { + "path-root": "^0.1.1" + } + }, + "rfdc": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/rfdc/-/rfdc-1.3.0.tgz", + "integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA==" + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" + }, + "signal-exit": { + "version": "3.0.7", + "resolved": "https://repo.huaweicloud.com/repository/npm/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "spdx-correct": { + "version": "3.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-correct/-/spdx-correct-3.1.1.tgz", + "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", + "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==" + }, + "spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.11", + "resolved": "https://repo.huaweicloud.com/repository/npm/spdx-license-ids/-/spdx-license-ids-3.0.11.tgz", + "integrity": "sha512-Ctl2BrFiM0X3MANYgj3CkygxhRmr9mi6xhejbdO960nF6EDJApTYpn0BQnDKlnNBULKiCN1n3w9EBkHK8ZWg+g==" + }, + "stream-exhaust": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/stream-exhaust/-/stream-exhaust-1.0.2.tgz", + "integrity": "sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw==" + }, + "streamroller": { + "version": "3.0.6", + "resolved": "https://repo.huaweicloud.com/repository/npm/streamroller/-/streamroller-3.0.6.tgz", + "integrity": "sha512-Qz32plKq/MZywYyhEatxyYc8vs994Gz0Hu2MSYXXLD233UyPeIeRBZARIIGwFer4Mdb8r3Y2UqKkgyDghM6QCg==", + "requires": { + "date-format": "^4.0.6", + "debug": "^4.3.4", + "fs-extra": "^10.0.1" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-bom": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-bom/-/strip-bom-2.0.0.tgz", + "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", + "requires": { + "is-utf8": "^0.2.0" + } + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==" + }, + "supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" + }, + "tar-stream": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "requires": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + }, + "dependencies": { + "is-number": { + "version": "7.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + } + } + }, + "type": { + "version": "1.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/type/-/type-1.2.0.tgz", + "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==" + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=" + }, + "undertaker": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/undertaker/-/undertaker-1.2.1.tgz", + "integrity": "sha512-71WxIzDkgYk9ZS+spIB8iZXchFhAdEo2YU8xYqBYJ39DIUIqziK78ftm26eecoIY49X0J2MLhG4hr18Yp6/CMA==", + "requires": { + "arr-flatten": "^1.0.1", + "arr-map": "^2.0.0", + "bach": "^1.0.0", + "collection-map": "^1.0.0", + "es6-weak-map": "^2.0.1", + "last-run": "^1.1.0", + "object.defaults": "^1.0.0", + "object.reduce": "^1.0.0", + "undertaker-registry": "^1.0.0" + } + }, + "undertaker-registry": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/undertaker-registry/-/undertaker-registry-1.0.1.tgz", + "integrity": "sha1-XkvaMI5KiirlhPm5pDWaSZglzFA=" + }, + "universalify": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "requires": { + "punycode": "^2.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "v8flags": { + "version": "3.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/v8flags/-/v8flags-3.2.0.tgz", + "integrity": "sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg==", + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/which-module/-/which-module-1.0.0.tgz", + "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=" + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "y18n": { + "version": "3.2.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/y18n/-/y18n-3.2.2.tgz", + "integrity": "sha512-uGZHXkHnhF0XeeAPgnKfPv1bgKAYyVvmNL1xlKsPYZPaIHxGti2hHqvOCQv71XMsLxu1QjergkqogUnms5D3YQ==" + }, + "yargs": { + "version": "7.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/yargs/-/yargs-7.1.0.tgz", + "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=", + "requires": { + "camelcase": "^3.0.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^1.4.0", + "read-pkg-up": "^1.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^1.0.2", + "which-module": "^1.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^5.0.0" + } + }, + "yargs-parser": { + "version": "5.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/yargs-parser/-/yargs-parser-5.0.1.tgz", + "integrity": "sha512-wpav5XYiddjXxirPoCTUPbqM0PXvJ9hiBMvuJgInvo4/lAOTZzUprArw17q2O1P2+GHhbBr18/iQwjL5Z9BqfA==", + "requires": { + "camelcase": "^3.0.0", + "object.assign": "^4.1.0" + } + }, + "zip-stream": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/zip-stream/-/zip-stream-4.1.0.tgz", + "integrity": "sha512-zshzwQW7gG7hjpBlgeQP9RuyPGNxvJdzR8SUM3QhxCnLjWN2E7j3dOvpeDcQoETfHx0urRS7EtmVToql7YpU4A==", + "requires": { + "archiver-utils": "^2.1.0", + "compress-commons": "^4.1.0", + "readable-stream": "^3.6.0" + } + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/package.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/package.json new file mode 100644 index 000000000..eff7afc86 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/package.json @@ -0,0 +1,18 @@ +{ + "license":"ISC", + "devDependencies":{}, + "name":"permissionmanager", + "ohos":{ + "org":"huawei", + "directoryLevel":"project", + "buildTool":"hvigor" + }, + "description":"example description", + "repository":{}, + "version":"1.0.0", + "dependencies":{ + "@ohos/hvigor-ohos-plugin":"1.0.6", + "hypium":"^1.0.0", + "@ohos/hvigor":"1.0.6" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/.gitignore b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/.gitignore new file mode 100644 index 000000000..4f9a97381 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/.preview +/build \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/build-profile.json5 b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/build-profile.json5 new file mode 100644 index 000000000..8d4191ee3 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/build-profile.json5 @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "apiType": 'stageMode', + "buildOption": { + }, + "targets": [ + { + "name": "default", + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/hvigorfile.js b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/hvigorfile.js new file mode 100644 index 000000000..d7720ee6a --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/hvigorfile.js @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package-lock.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package-lock.json new file mode 100644 index 000000000..af634257b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package-lock.json @@ -0,0 +1,5 @@ +{ + "name": "permissionmanager", + "version": "1.0.0", + "lockfileVersion": 1 +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package.json new file mode 100644 index 000000000..980ccad2b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/package.json @@ -0,0 +1,14 @@ +{ + "license": "ISC", + "devDependencies": {}, + "name": "permissionmanager", + "ohos": { + "org": "huawei", + "directoryLevel": "module", + "buildTool": "hvigor" + }, + "description": "example description", + "repository": {}, + "version": "1.0.0", + "dependencies": {} +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/Application/AbilityStage.ts b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/Application/AbilityStage.ts new file mode 100644 index 000000000..c5840e536 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/Application/AbilityStage.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import AbilityStage from "@ohos.application.AbilityStage" + +var TAG = "PermissionManager_MainAbility:" + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log(TAG + "MyAbilityStage onCreate.") + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/MainAbility/MainAbility.ts b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/MainAbility/MainAbility.ts new file mode 100644 index 000000000..fd4781d89 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/MainAbility/MainAbility.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Ability from '@ohos.application.Ability'; + +var TAG = "PermissionManager_MainAbility:"; + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log(TAG + "MainAbility onCreate, ability name is " + want.abilityName + "."); + globalThis.context = this.context; + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log(TAG + "MainAbility onWindowStageCreate."); + + globalThis.context = this.context; + + windowStage.setUIContent(this.context, "pages/authority-management", null); + } + + onForeground() { + // Ability has brought to foreground + console.log(TAG + "MainAbility onForeground."); + } + + onBackground() { + // Ability has back to background + console.log(TAG + "MainAbility onBackground."); + +// this.context.terminateSelf(); + } + + onDestroy() { + console.log(TAG + "MainAbility onDestroy."); + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log(TAG + "MainAbility onWindowStageDestroy."); + } +}; diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts new file mode 100644 index 000000000..bd3544ad7 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import extension from '@ohos.application.ServiceExtensionAbility'; +import window from '@ohos.window'; +import display from '@ohos.display'; + +var TAG = "PermissionManager_Log:"; +const MAX_WIDTH = 790; +const MAX_HEIGHT = 1100; + +export default class ServiceExtensionAbility extends extension { + /** + * Lifecycle function, called back when a service extension is started for initialization. + */ + onCreate(want) { + console.info(TAG + "ServiceExtensionAbility onCreate, ability name is " + want.abilityName); + + globalThis.extensionContext = this.context; + globalThis.windowNum = 0 + } + + /** + * Lifecycle function, called back when a service extension is started or recall. + */ + onRequest(want, startId) { + globalThis.abilityWant = want + console.info(TAG + "ServiceExtensionAbility onRequest. start id is " + startId); + console.info(TAG + "want: " + JSON.stringify(want)) + + display.getDefaultDisplay().then(dis => { + let navigationBarRect = { + left: (dis.width - MAX_WIDTH)/2, + top: (dis.height - MAX_HEIGHT)/2, + width: MAX_WIDTH, + height: MAX_HEIGHT + } + this.createWindow("permissionDialog" + startId, window.WindowType.TYPE_DIALOG, navigationBarRect) + }) + } + + /** + * Lifecycle function, called back before a service extension is destroyed. + */ + onDestroy() { + console.info(TAG + "ServiceExtensionAbility onDestroy."); + } + + private async createWindow(name: string, windowType: number, rect) { + console.info(TAG + "create window") + try { + const win = await window.create(globalThis.extensionContext, name, windowType) + globalThis.extensionWin = win + await win.bindDialogTarget(globalThis.abilityWant.parameters['ohos.ability.params.token'].value, () => { + win.destroy() + globalThis.windowNum -- + if(globalThis.windowNum == 0) this.context.terminateSelf() + }) + await win.moveTo(rect.left, rect.top) + await win.resetSize(rect.width, rect.height) + await win.loadContent('pages/dialogPlus') + await win.setBackgroundColor('#00000000') + await win.show() + globalThis.windowNum ++ + } catch { + console.info(TAG + "window create failed!") + } + } +}; \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/alphabeticalIndex.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/alphabeticalIndex.ets new file mode 100644 index 000000000..a8270d1ee --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/alphabeticalIndex.ets @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Constants from '../utils/constant'; + +@Component +export struct alphabetIndexerComponent { + private value: string[] = [ + '#', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z' + ]; // Array of alphabetically indexed names + @Link applicationItem: any; // application info array + @Link oldApplicationItem: any; // Original application information array + @State index: number = 0; // alphabetical index + + build() { + AlphabetIndexer({ arrayValue: this.value, selected: this.index }) + .selectedColor($r('app.color.selected_Color')) // selected color + .popupColor($r('app.color.popup_Color')) // popover color + .selectedBackgroundColor($r('app.color.selected_Background_Color')) // Check background color + .popupBackground($r('app.color.popup_Background_Color')) // popover background color + .usingPopup(true) // whether to show a popup + .selectedFont({ size: Constants.ALPHABETINDEXER_SELECTEDFONT_SIZE, weight: FontWeight.Bolder }) // selected style + .popupFont({ size: Constants.ALPHABETINDEXER_POPUPFONT_SIZE, weight: FontWeight.Bolder }) // Demo of the popup + .itemSize(Constants.ALPHABETINDEXER_ITEMSIZE) // size square of each item + .alignStyle(IndexerAlign.Left) // Align left + .onSelected((index: number) => { + this.index = index; + if (this.value[index] === '#' || this.value[index] === '☆') { + this.applicationItem = this.oldApplicationItem; + } else { + this.applicationItem = this.oldApplicationItem.filter((item) => { + return item.alphabeticalIndex.toUpperCase() === this.value[index]; + }) + } + }) + .height(Constants.ALPHABETINDEXER_HEIGHT) + .width(Constants.ALPHABETINDEXER_WIDTH) + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/backBar.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/backBar.ets new file mode 100644 index 000000000..8145d91d7 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/backBar.ets @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import router from '@system.router'; +import Resmgr from '@ohos.resourceManager' +import Constants from '../utils/constant'; + +@Component +export struct backBar { + @Prop title: string; // return title name + @Prop recordable: boolean + @State record: string = '' + + build() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Image($r('app.media.left')) + .objectFit(ImageFit.Contain) + .height(Constants.BACKBAR_IMAGE_HEIGHT) + .width(Constants.BACKBAR_IMAGE_WIDTH) + .margin({ + top: Constants.BACKBAR_IMAGE_MARGIN_TOP, + left: Constants.BACKBAR_IMAGE_MARGIN_LEFT, + right: Constants.BACKBAR_IMAGE_MARGIN_RIGHT + }) + .onClick(() => { + var length = router.getLength() + Number(length) == 1 ? globalThis.context.terminateSelf() : router.back() + }) + Text(JSON.parse(this.title)) + .fontColor($r('app.color.text_color')) + .fontSize(Constants.BACKBAR_TEXT_FONT_SIZE) + .flexGrow(Constants.BACKBAR_TEXT_FLEX_GROW) + .fontWeight(FontWeight.Bold) + .margin({ top: Constants.BACKBAR_TEXT_MARGIN_TOP }) + if(this.recordable) { + Image($r("app.media.gongneng_dian")) + .objectFit(ImageFit.Contain) + .height(Constants.BACKBAR_IMAGE_HEIGHT) + .width(Constants.BACKBAR_IMAGE_WIDTH) + .margin({ top: Constants.BACKBAR_TEXT_MARGIN_TOP, right: Constants.BACKBAR_IMAGE_MARGIN_RIGHT }) + .bindMenu([ + { + value: this.record, + action: () => { + router.push({ uri: 'pages/permission-access-record' }) + } + } + ]) + } + } + } + .height(Constants.BACKBAR_HEIGHT) + .constraintSize({ minHeight: Constants.BACKBAR_MINHEIGHT }) + .alignItems(HorizontalAlign.Start) + .backgroundColor($r('app.color.background_color')) + } + + aboutToAppear() { + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + item.getString($r("app.string.permission_access_record").id, (err, val) => { + this.record = val + }) + }) + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/dialog.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/dialog.ets new file mode 100644 index 000000000..8e86dd6ab --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/dialog.ets @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Constants from '../utils/constant'; + +@CustomDialog +export struct authorizeDialog { + controller: CustomDialogController; + cancel: () => void; + confirm: () => void; + + build() { + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text($r("app.string.Authorization_failed")).fontSize(Constants.DIALOG_TEXT_FONT_SIZE) + .margin({ + top: Constants.DIALOG_TEXT_MARGIN_TOP + }) + } + } + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.DIALOG_BORDER_RADIUS) + .height(Constants.DIALOG_HEIGHT) + .width(Constants.DIALOG_WIDTH) + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/search.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/search.ets new file mode 100644 index 000000000..72fa15f01 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/components/search.ets @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Constants from '../utils/constant'; + +@Component +export struct textInput { + @Prop placeholder: string; // Prompt text when no input + @Link applicationItem: any; // application info array + @Link oldApplicationItem: any; // Original application information array + @Link searchResult: boolean; // search results + + build() { + Column() { + Flex({ alignContent: FlexAlign.Start }) { + TextInput({ placeholder: this.placeholder }) + .backgroundColor($r('app.color.default_background_color')) + .padding({ left: Constants.TEXTINPUT_PADDING_LEFT }) + .type(InputType.Normal) + .border({ width: Constants.TEXTINPUT_BORDER_WIDTH, color: $r("app.color.label_color_20"), radius: Constants.TEXTINPUT_BORDER_RADIUS }) + .placeholderColor(Color.Grey) + .placeholderFont({ size: Constants.TEXTINPUT_PLACEHOLDER_Font_SIZE, weight: FontWeight.Normal, family: "sans-serif", style: FontStyle.Normal }) + .caretColor($r('app.color.secondary_font_color')) + .height(Constants.TEXTINPUT_HEIGHT) + .onChange((value: string) => { + if (value === '' || value === null) { + this.applicationItem = this.oldApplicationItem; + } else { + this.applicationItem = this.oldApplicationItem.filter((item) => { + return item.labelId.indexOf(value) > -1; + }) + } + if (this.applicationItem.length) { + this.searchResult = true; + } else { + this.searchResult = false; + } + }) + .onSubmit((enterKey) => { + }) + .onEditChanged((isEditing) => { + }) + Image($r('app.media.search')) + .objectFit(ImageFit.Contain) + .width(Constants.TEXTINPUT_IMAGE_WIDTH) + .height(Constants.TEXTINPUT_IMAGE_HEIGHT) + .position({ x: Constants.TEXTINPUT_IMAGE_MARGIN_LEFT, y: Constants.TEXTINPUT_IMAGE_MARGIN_TOP }) + } + } + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/bundle.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/bundle.ets new file mode 100644 index 000000000..d5f38e35e --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/bundle.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const BundleFlag = { + GET_BUNDLE_DEFAULT : 0x00000000, + GET_BUNDLE_WITH_ABILITIES : 0x00000001, + GET_ABILITY_INFO_WITH_PERMISSION : 0x00000002, + GET_ABILITY_INFO_WITH_APPLICATION : 0x00000004, + GET_APPLICATION_INFO_WITH_PERMISSION : 0x00000008, + GET_BUNDLE_WITH_REQUESTED_PERMISSION : 0x00000010, + GET_ALL_APPLICATION_INFO : 0xFFFF0000, + /** + * @since 8 + */ + GET_ABILITY_INFO_WITH_METADATA : 0x00000020, + /** + * @since 8 + */ + GET_APPLICATION_INFO_WITH_METADATA : 0x00000040, + /** + * @since 8 + */ + GET_ABILITY_INFO_SYSTEMAPP_ONLY : 0x00000080 +} + +export const USER_ID: number = 100 \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/permissionGroup.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/permissionGroup.ets new file mode 100644 index 000000000..d389c6b59 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/model/permissionGroup.ets @@ -0,0 +1,512 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const permissionGroups: any[] = [ + { + "permissionName": "ohos.permission.LOCATION_IN_BACKGROUND", + "groupName": "LOCATION", + "label": "后台定位权限", + "description": "允许应用在后台运行时获取位置信息。", + "groupId": 0 + }, + { + "permissionName": "ohos.permission.LOCATION", + "groupName": "LOCATION", + "label": "前台定位权限", + "description": "允许应用在前台运行时获取位置信息。", + "groupId": 0 + }, + { + "permissionName": "ohos.permission.CAMERA", + "groupName": "CAMERA", + "label": "拍摄照片和录制视频", + "description": "允许应用拍摄照片和视频。", + "groupId": 1 + }, + { + "permissionName": "ohos.permission.MICROPHONE", + "groupName": "MICROPHONE", + "label": "录制音频", + "description": "允许应用打开或关闭录音通路。", + "groupId": 2 + }, + { + "permissionName": "ohos.permission.ANSWER_CALL", + "groupName": "PHONE", + "label": "接听电话", + "description": "允许应用接听电话。", + "groupId": 3 + }, + { + "permissionName": "ohos.permission.MANAGE_VOICEMAIL", + "groupName": "PHONE", + "label": "语音信箱", + "description": "允许应用管理语音信箱。", + "groupId": 3 + }, + { + "permissionName": "ohos.permission.READ_CELL_MESSAGES", + "groupName": "SMS", + "label": "读取小区广播", + "description": "允许应用读取设备接收的小区广播信息。", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.READ_MESSAGES", + "groupName": "SMS", + "label": "读取短彩信", + "description": "允许应用读取设备接收的短彩信信息。", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.RECEIVE_MMS", + "groupName": "SMS", + "label": "接收彩信", + "description": "允许应用接收彩信。", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.RECEIVE_SMS", + "groupName": "SMS", + "label": "接收短信", + "description": "允许应用接收短信。", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.RECEIVE_WAP_MESSAGES", + "groupName": "SMS", + "label": "接收WAP消息", + "description": "允许应用接收和处理WAP消息。", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.SEND_MESSAGES", + "groupName": "SMS", + "label": "发送短彩信", + "description": "允许应用发送短彩信", + "groupId": 4 + }, + { + "permissionName": "ohos.permission.READ_CONTACTS", + "groupName": "CONTACTS", + "label": "读取通讯录", + "description": "允许应用读取设备上存储的联系人信息。", + "groupId": 5 + }, + { + "permissionName": "ohos.permission.WRITE_CONTACTS", + "groupName": "CONTACTS", + "label": "新建/修改/删除通讯录", + "description": "允许应用新建/修改/删除设备上存储的联系人信息。", + "groupId": 5 + }, + { + "permissionName": "ohos.permission.READ_CALL_LOG", + "groupName": "CALL_LOG", + "label": "读取通话记录", + "description": "允许应用读取设备上的通话记录信息。", + "groupId": 6 + }, + { + "permissionName": "ohos.permission.WRITE_CALL_LOG", + "groupName": "CALL_LOG", + "label": "新建/修改/删除通话记录", + "description": "允许新建/修改/删除设备上的通话记录信息。", + "groupId": 6 + }, + { + "permissionName": "ohos.permission.MEDIA_LOCATION", + "groupName": "MEDIA", + "label": "允许应用访问拍摄位置", + "description": "应用访问用户媒体文件中的拍摄位置信息如经纬度信息。", + "groupId": 7 + }, + { + "permissionName": "ohos.permission.READ_MEDIA", + "groupName": "MEDIA", + "label": "允许应用读取媒体文件", + "description": "允许应用访问户媒体文件,如视频、音频、图片等。", + "groupId": 7 + }, + { + "permissionName": "ohos.permission.WRITE_MEDIA", + "groupName": "MEDIA", + "label": "允许应用读写媒体文件", + "description": "允许应用读写户媒体文件,如视频、音频、图片等。", + "groupId": 7 + }, + { + "permissionName": "ohos.permission.READ_CALENDAR", + "groupName": "CALENDAR", + "label": "读取日历", + "description": "允许应用读取日历。", + "groupId": 8 + }, + { + "permissionName": "ohos.permission.WRITE_CALENDAR", + "groupName": "CALENDAR", + "label": "新建/修改/删除日历", + "description": "允许应用新建/修改/删除日历。", + "groupId": 8 + }, + { + "permissionName": "ohos.permission.ACTIVITY_MOTION", + "groupName": "SPORT", + "label": "读取用户的运动状态", + "description": "允许应用程序读取用户的运动状态。", + "groupId": 9 + }, + { + "permissionName": "ohos.permission.READ_HEALTH_DATA", + "groupName": "HEALTH", + "label": "读取用户的健康数据", + "description": "允许应用程序读取用户的健康数据。", + "groupId": 10 + }, + { + "permissionName": "ohos.permission.DISTRIBUTED_DATASYNC", + "groupName": "OTHER", + "icon": $r("app.media.ic_multi_device_vector"), + "text": "使用多设备协同?", + "label": "多设备协同", + "description": "发现并访问其他设备。", + "groupId": 11 + } +] + +export const groups: any[] = [ + { + "name": "LOCATION", + "groupName": "位置信息", + "icon": $r('app.media.ic_public_gps'), + "description": "", + "label": "访问位置信息?", + "permissions": [ + "ohos.permission.LOCATION_IN_BACKGROUND", + "ohos.permission.LOCATION" + ], + "isShow":true + }, + { + "name": "CAMERA", + "groupName": "相机", + "icon": $r('app.media.ic_public_camera'), + "label": "使用相机?", + "description": "", + "permissions": [ + "ohos.permission.CAMERA" + ], + "isShow":true + }, + { + "name": "MICROPHONE", + "groupName": "麦克风", + "icon": $r('app.media.ic_public_voice'), + "label": "使用麦克风?", + "description": "", + "permissions": [ + "ohos.permission.MICROPHONE" + ], + "isShow":true + }, + { + "name": "PHONE", + "groupName": "电话", + "icon": $r('app.media.ic_public_phone'), + "label": "使用拨打电话?", + "description": "", + "permissions": [ + "ohos.permission.ANSWER_CALL", + "ohos.permission.MANAGE_VOICEMAIL" + ], + "isShow":false + }, + { + "name": "SMS", + "groupName": "信息", + "icon": $r('app.media.ic_public_message'), + "label": "访问信息?", + "description": "", + "permissions": [ + "ohos.permission.READ_CELL_MESSAGES", + "ohos.permission.READ_MESSAGES", + "ohos.permission.RECEIVE_MMS", + "ohos.permission.RECEIVE_SMS", + "ohos.permission.RECEIVE_WAP_MESSAGES", + "ohos.permission.SEND_MESSAGES" + ], + "isShow":false + }, + { + "name": "CONTACTS", + "groupName": "通讯录", + "icon": $r('app.media.ic_public_contacts_group'), + "label": "访问通讯录?", + "description": "", + "permissions": [ + "ohos.permission.READ_CONTACTS", + "ohos.permission.WRITE_CONTACTS" + ], + "isShow":false + }, + { + "name": "CALL_LOG", + "groupName": "通话记录", + "icon": $r('app.media.ic_call_logs'), + "label": "访问通话记录?", + "description": "", + "permissions": [ + "ohos.permission.READ_CALL_LOG", + "ohos.permission.WRITE_CALL_LOG" + ], + "isShow":false + }, + { + "name": "MEDIA", + "groupName": "媒体和文件", + "icon": $r('app.media.ic_public_folder'), + "description": "", + "label": "访问媒体和文件?", + "permissions": [ + "ohos.permission.MEDIA_LOCATION", + "ohos.permission.READ_MEDIA", + "ohos.permission.WRITE_MEDIA" + ], + "isShow":true + }, + { + "name": "CALENDAR", + "groupName": "日历", + "icon": $r('app.media.ic_public_calendar'), + "label": "访问日历?", + "description": "", + "permissions": [ + "ohos.permission.READ_CALENDAR", + "ohos.permission.WRITE_CALENDAR" + ], + "isShow":true + }, + { + "name": "SPORT", + "groupName": "健身运动", + "icon": $r('app.media.ic_sport'), + "label": "访问健身运动?", + "description": "", + "permissions": [ + "ohos.permission.ACTIVITY_MOTION" + ], + "isShow":true + }, + { + "name": "HEALTH", + "groupName": "身体传感器", + "icon": $r('app.media.ic_ssensor'), + "label": "使用身体传感器?", + "description": "", + "permissions": [ + "ohos.permission.READ_HEALTH_DATA" + ], + "isShow":true + }, + { + "name": "OTHER", + "groupName": "其他权限", + "icon": $r('app.media.ic_more'), + "description": "", + "permissions": [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ], + "isShow":false + } +]; + +export const permissionGroupPermissions: object = { + "LOCATION": [ + "ohos.permission.LOCATION_IN_BACKGROUND", + "ohos.permission.LOCATION" + ], + "CAMERA": [ + "ohos.permission.CAMERA" + ], + "MICROPHONE": [ + "ohos.permission.MICROPHONE" + ], + "PHONE": [ + "ohos.permission.ANSWER_CALL", + "ohos.permission.MANAGE_VOICEMAIL" + ], + "SMS": [ + "ohos.permission.READ_CELL_MESSAGES", + "ohos.permission.READ_MESSAGES", + "ohos.permission.RECEIVE_MMS", + "ohos.permission.RECEIVE_SMS", + "ohos.permission.RECEIVE_WAP_MESSAGES", + "ohos.permission.SEND_MESSAGES" + ], + "CONTACTS": [ + "ohos.permission.READ_CONTACTS", + "ohos.permission.WRITE_CONTACTS" + ], + "CALL_LOG": [ + "ohos.permission.READ_CALL_LOG", + "ohos.permission.WRITE_CALL_LOG" + ], + "MEDIA": [ + "ohos.permission.MEDIA_LOCATION", + "ohos.permission.READ_MEDIA", + "ohos.permission.WRITE_MEDIA" + ], + "CALENDAR": [ + "ohos.permission.READ_CALENDAR", + "ohos.permission.WRITE_CALENDAR" + ], + "SPORT": [ + "ohos.permission.ACTIVITY_MOTION" + ], + "HEALTH": [ + "ohos.permission.READ_HEALTH_DATA" + ], + "OTHER": [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ] +}; + + +export const userGrantPermissions: string[] = [ + "ohos.permission.LOCATION_IN_BACKGROUND", + "ohos.permission.LOCATION", + "ohos.permission.CAMERA", + "ohos.permission.MICROPHONE", + "ohos.permission.ANSWER_CALL", + "ohos.permission.MANAGE_VOICEMAIL", + "ohos.permission.READ_CELL_MESSAGES", + "ohos.permission.READ_MESSAGES", + "ohos.permission.RECEIVE_MMS", + "ohos.permission.RECEIVE_SMS", + "ohos.permission.RECEIVE_WAP_MESSAGES", + "ohos.permission.SEND_MESSAGES", + "ohos.permission.READ_CONTACTS", + "ohos.permission.WRITE_CONTACTS", + "ohos.permission.READ_CALL_LOG", + "ohos.permission.WRITE_CALL_LOG", + "ohos.permission.MEDIA_LOCATION", + "ohos.permission.READ_MEDIA", + "ohos.permission.WRITE_MEDIA", + "ohos.permission.READ_CALENDAR", + "ohos.permission.WRITE_CALENDAR", + "ohos.permission.ACTIVITY_MOTION", + "ohos.permission.READ_HEALTH_DATA", + "ohos.permission.DISTRIBUTED_DATASYNC" +]; + +export const permissionDescriptions: object = { + "位置信息": "允许应用在后台运行时获取位置信息。" , + "相机": "允许应用拍摄照片和视频。" , + "麦克风": "允许应用打开或关闭录音通路。" , + "电话": "允许应用接听电话。" , + "信息": "允许应用发送短彩信。" , + "通讯录": "允许应用新建/修改/删除设备上存储的联系人信息。" , + "通话记录": "允许新建/修改/删除设备上的通话记录信息。" , + "媒体和文件": "允许应用访问户媒体文件,如视频、音频、图片等。" , + "日历": "允许应用新建/修改/删除日历。" , + "健身运动": "允许应用程序读取用户的运动状态。" , + "身体传感器": "允许应用程序读取用户的健康数据。" , + "其他权限": "允许应用与远程设备交换用户数据(如图片、音乐、视频、及应用数据等)。" +}; + +export const permissionPermissionGroup: object = { + "ohos.permission.LOCATION_IN_BACKGROUND": "LOCATION", + "ohos.permission.LOCATION": "LOCATION", + "ohos.permission.CAMERA": "CAMERA", + "ohos.permission.MICROPHONE": "MICROPHONE", + "ohos.permission.ANSWER_CALL": "PHONE", + "ohos.permission.MANAGE_VOICEMAIL": "PHONE", + "ohos.permission.READ_CELL_MESSAGES": "SMS", + "ohos.permission.READ_MESSAGES": "SMS", + "ohos.permission.RECEIVE_MMS": "SMS", + "ohos.permission.RECEIVE_SMS": "SMS", + "ohos.permission.RECEIVE_WAP_MESSAGES": "SMS", + "ohos.permission.SEND_MESSAGES": "SMS", + "ohos.permission.READ_CONTACTS": "CONTACTS", + "ohos.permission.WRITE_CONTACTS": "CONTACTS", + "ohos.permission.READ_CALL_LOG": "CALL_LOG", + "ohos.permission.WRITE_CALL_LOG": "CALL_LOG", + "ohos.permission.MEDIA_LOCATION": "MEDIA", + "ohos.permission.READ_MEDIA": "MEDIA", + "ohos.permission.WRITE_MEDIA": "MEDIA", + "ohos.permission.READ_CALENDAR": "CALENDAR", + "ohos.permission.WRITE_CALENDAR": "CALENDAR", + "ohos.permission.ACTIVITY_MOTION": "SPORT", + "ohos.permission.READ_HEALTH_DATA": "HEALTH", + "ohos.permission.DISTRIBUTED_DATASYNC": "OTHER" +}; + +export const permissionGroupIds: object = { + "ohos.permission.LOCATION_IN_BACKGROUND": "0", + "ohos.permission.LOCATION": "0", + "ohos.permission.CAMERA": "1", + "ohos.permission.MICROPHONE": "2", + "ohos.permission.ANSWER_CALL": "3", + "ohos.permission.MANAGE_VOICEMAIL": "3", + "ohos.permission.READ_CELL_MESSAGES": "4", + "ohos.permission.READ_MESSAGES": "4", + "ohos.permission.RECEIVE_MMS": "4", + "ohos.permission.RECEIVE_SMS": "4", + "ohos.permission.RECEIVE_WAP_MESSAGES": "4", + "ohos.permission.SEND_MESSAGES": "4", + "ohos.permission.READ_CONTACTS": "5", + "ohos.permission.WRITE_CONTACTS": "5", + "ohos.permission.READ_CALL_LOG": "6", + "ohos.permission.WRITE_CALL_LOG": "6", + "ohos.permission.MEDIA_LOCATION": "7", + "ohos.permission.READ_MEDIA": "7", + "ohos.permission.WRITE_MEDIA": "7", + "ohos.permission.READ_CALENDAR": "8", + "ohos.permission.WRITE_CALENDAR": "8", + "ohos.permission.ACTIVITY_MOTION": "9", + "ohos.permission.READ_HEALTH_DATA": "10", + "ohos.permission.DISTRIBUTED_DATASYNC": "11" +}; + +export const orderGroup: string[] = [ + "位置信息", + "相机", + "麦克风", + "电话", + "信息", + "通讯录", + "通话记录", + "媒体和文件", + "日历", + "健身运动", + "身体传感器", + "其他权限" +]; + +export const otherPermissionsLabel: object = { + "ohos.permission.DISTRIBUTED_DATASYNC": "多设备协同" +}; + +export const noNeedDisplayApp: string[] = [ + "com.ohos.launcher" +] + +export const showSubpermissionsGrop: string[] = [ + "电话", + "日历", + "信息", + "通讯录", + "通话记录" +]; \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets new file mode 100644 index 000000000..1bfa23125 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets @@ -0,0 +1,349 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default class Constants { + // alphabetIndexer + static ALPHABETINDEXER_SELECTEDFONT_SIZE = 12; + static ALPHABETINDEXER_POPUPFONT_SIZE = 30; + static ALPHABETINDEXER_ITEMSIZE = 16; + static ALPHABETINDEXER_HEIGHT = 448; + static ALPHABETINDEXER_WIDTH = 36; + + // backBar + static BACKBAR_HEIGHT = 56; + static BACKBAR_MINHEIGHT = 56; + + // image of backBar + static BACKBAR_IMAGE_HEIGHT = 24; + static BACKBAR_IMAGE_WIDTH = 24; + static BACKBAR_IMAGE_MARGIN_TOP = 17; + static BACKBAR_IMAGE_MARGIN_LEFT = 12; + static BACKBAR_IMAGE_MARGIN_RIGHT = 15; + + // text of backBar + static BACKBAR_TEXT_FONT_SIZE = 20; + static BACKBAR_TEXT_FLEX_GROW = 1; + static BACKBAR_TEXT_MARGIN_TOP = 17; + + // dialog + static DIALOG_BORDER_RADIUS = 24; + static DIALOG_HEIGHT = 70; + static DIALOG_WIDTH = 336; + + // text of dialog + static DIALOG_TEXT_FONT_SIZE = 20; + static DIALOG_TEXT_MARGIN_TOP = 25; + + // search textInput + static TEXTINPUT_PADDING_LEFT = 36; + static TEXTINPUT_BORDER_RADIUS = 20; + static TEXTINPUT_BORDER_WIDTH = 1.5; + static TEXTINPUT_PLACEHOLDER_Font_SIZE = 16; + static TEXTINPUT_HEIGHT = 40; + static TEXTINPUT_IMAGE_WIDTH = 16; + static TEXTINPUT_IMAGE_HEIGHT = 16; + static TEXTINPUT_IMAGE_MARGIN_LEFT = 12; + static TEXTINPUT_IMAGE_MARGIN_TOP = 12; + + // grid useSizeType + static GRID_MARGIN = '0vp'; + static GUTTER = 0; + static LEFT_XS_SPAN = 0; + static LEFT_XS_OFFSET = 0; + static LEFT_SM_SPAN = 0; + static LEFT_SM_OFFSET = 0; + static LEFT_MD_SPAN = 0; + static LEFT_MD_OFFSET = 0; + static LEFT_LG_SPAN = 2; + static LEFT_LG_OFFSET = 0; + static MIDDLE_XS_SPAN = 2; + static MIDDLE_XS_OFFSET = 0; + static MIDDLE_SM_SPAN = 4; + static MIDDLE_SM_OFFSET = 0; + static MIDDLE_MD_SPAN = 8; + static MIDDLE_MD_OFFSET = 0; + static MIDDLE_LG_SPAN = 8; + static MIDDLE_LG_OFFSET = 2; + static RIGHT_XS_SPAN = 0; + static RIGHT_XS_OFFSET = 2; + static RIGHT_SM_SPAN = 0; + static RIGHT_SM_OFFSET = 4; + static RIGHT_MD_SPAN = 0; + static RIGHT_MD_OFFSET = 8; + static RIGHT_LG_SPAN = 2; + static RIGHT_LG_OFFSET = 10; + + // 100% width,height + static FULL_WIDTH = '100%'; + static FULL_HEIGHT = '100%'; + + // public property style + static PERMISSION = 1; + static APPLICATION = 0; + static LAYOUT_WEIGHT = 1; + static FLEX_GROW = 1; + static TEXT_DECORATION_HEIGHT = 1; + static TEXT_MIDDLE_FONT_SIZE = 16; + static TEXT_SMAL_FONT_SIZE = 14; + static TEXT_SMALLER_FONT_SIZE = 12; + static TEXT_LINE_HEIGHT = 22; + static TEXT_SMALL_LINE_HEIGHT = 19; + static CONSTRAINTSIZE_MINHEIGHT = 48; + static LISTITEM_ROW_HEIGHT = 48; + static LISTITEM_PADDING_LEFT = 24; + static LIST_PADDING_LEFT = 12 + static LISTITEM_PADDING_RIGHT = 24; + static LISTITEM_PADDING_LEFT_RECORD = 32; + static LISTITEM_MARGIN_BOTTOM = 12; + static LISTITEM_MARGIN_BOTTOM_PERMISSION = 14; + static LISTITEM_MARGIN_BOTTOM_APPLICATION = 10; + static LISTITEM_HEIGHT_PERMISSION = 64; + static LISTITEM_HEIGHT_APPLICATION = 72; + static IMAGE_HEIGHT = 24; + static IMAGE_WIDTH = 12; + static IMAGE_HEIGHT_RECORD = 12; + static IMAGE_WIDTH_RECORD = 24; + static IMAGE_HEIGHT_RECORD_APPLICATION = 16; + static IMAGE_WIDTH_RECORD_APPLICATION = 16; + static BORDER_RADIUS = 24; + static TITLE_MARGIN_BOTTOM = 16; + static SUBTITLE_MIN_HEIGHT = 48; + static SUBTITLE_LINE_HEIGHT = 24; + static SUBTITLE_PADDING_TOP = 16; + static SUBTITLE_PADDING_BOTTOM = 8; + static TAB_HEIGHT = 56; + static TAB_DECORATION_HEIGHT = 2; + static TAB_DECORATION_POSITION_Y = 46; + static DEFAULT_PADDING_START = 12; + static DEFAULT_PADDING_END = 12; + + // application-secondary, authority-secondary + static FLEX_MARGIN_TOP = 8; + static FLEX_MARGIN_BOTTOM = 8; + static LIST_PADDING_TOP = 4; + static LIST_PADDING_BOTTOM = 4; + static LIST_MARGIN_BOTTOM = 12; + static ROW_MARGIN_TOP = 9; + static SECONDARY_TEXT_MARGIN_TOP = 19.5; + static SECONDARY_TEXT_MARGIN_LEFT = 24; + static SECONDARY_LIST_PADDING_LEFT = 12; + static SECONDARY_LIST_PADDING_RIGHT = 12; + + // application-tertiary + static TERTIARY_IMAGE_WIDTH = 64; + static TERTIARY_IMAGE_HEIGHT = 64; + static TERTIARY_IMAGE_MARGIN_LEFT = 12; + static TERTIARY_IMAGE_MARGIN_RIGHT = 12; + static TERTIARY_LABEL_MARGIN_BOTTOM = 2; + static TERTIARY_MARGIN_LEFT = 12; + static TERTIARY_TEXT_MARGIN_LEFT = 24; + static TERTIARY_HALF_WIDTH = '50%'; + static TERTIARY_ROW_MARGIN_TOP = 24; + static TERTIARY_PERMISSION_ROW_MARGIN_TOP = 12; + static TERTIARY_RADIO_IMAGE_WIDTH = 24; + static TERTIARY_RADIO_IMAGE_HEIGHT = 24; + static TERTIARY_RADIO_IMAGE_MARGIN_TOP = 4; + static TERTIARY_LISTITEM_PADDING_LEFT = 24; + static TERTIARY_LISTITEM_PADDING_RIGHT = 24; + static TERTIARY_LISTITEM_MARGIN_TOP = 1; + static TERTIARY_LIST_PADDING_LEFT = 12; + static TERTIARY_LIST_PADDING_RIGHT = 12; + static TERTIARY_LIST_PADDING_TOP = 4; + static TERTIARY_LIST_PADDING_BOTTOM = 4; + + // authority-tertiary + static AUTHORITY_IMAGE_WIDTH = 40; + static AUTHORITY_IMAGE_HEIGHT = 40; + static AUTHORITY_IMAGE_MARGIN_RIGHT = 16; + static AUTHORITY_TOGGLE_WIDTH = 36; + static AUTHORITY_TOGGLE_HEIGHT = 20; + static AUTHORITY_ROW_HEIGHT = 72; + static AUTHORITY_CONSTRAINTSIZE_MINHEIGHT = 72; + static AUTHORITY_LISTITEM_PADDING_LEFT = 12; + static AUTHORITY_LISTITEM_PADDING_RIGHT = 12; + static AUTHORITY_TEXTINPUT_PADDING_LEFT = 12; + static AUTHORITY_TEXTINPUT_PADDING_RIGHT = 24; + static AUTHORITY_TEXT_MARGIN_TOP = 24; + static AUTHORITY_TEXT_MARGIN_LEFT = 0; + static AUTHORITY_ROW_MARGIN_TOP = 24; + static NORECORD_IMAGE_WIDTH = 120; + static NORECORD_IMAGE_HEIGHT = 120; + static NORECORD_IMAGE_MARGIN_LEFT = 40; + static SEARCHNORESULT_IMAGE_WIDTH = 200; + static SEARCHNORESULT_IMAGE_HEIGHT = 200; + static AUTHORITY_COLUMN_HEIGHT = '95%'; + static AUTHORITY_ALPHABETINDEX_WIDTH = 24; + static AUTHORITY_ALPHABETINDEX_PADDING_TOP = 16; + static AUTHORITY_TEXT_DECORATION_WIDTH = '86%'; + static AUTHORITY_TEXT_DECORATION_MARGIN_LEFT = 53; + + // authority-management + static MANAGEMENT_IMAGE_WIDTH = 24; + static MANAGEMENT_IMAGE_HEIGHT = 24; + static MANAGEMENT_IMAGE_MARGIN_RIGHT = 16; + static MANAGEMENT_IMAGE_MARGIN_RIGHT_RECORD = 24; + static MANAGEMENT_IMAGE_MARGIN_LEFT = 8; + static MANAGEMENT_ROW_HEIGHT = 56; + static MANAGEMENT_TEXT_DECORATION_WIDTH = '95%'; + static MANAGEMENT_TEXT_DECORATION_MARGIN_LEFT = 40; + static MANAGEMENT_LODING_IMAGE_WIDTH = 48; + static MANAGEMENT_LODING_IMAGE_HEIGHT = 48; + static MANAGEMENT_LODING_ROW_HEIGHT = '90%'; + static MANAGEMENT_ROW_PADDING_LEFT = 12; + static MANAGEMENT_ROW_PADDING_RIGHT = 12; + static MANAGEMENT_ROW_PADDING_TOP = 8; + static MANAGEMENT_ROW_MARGIN_TOP = 12; + static MANAGEMENT_TRANSPARENCY = 0.8; + static APPLICATION_IMAGE_WIDTH = 40; + static APPLICATION_IMAGE_HEIGHT = 40; + static APPLICATION_IMAGE_MARGIN_RIGHT = 16; + static APPLICATION_TEXT_MARGIN_RIGHT = 4; + static APPLICATION_LIST_PADDING_LEFT = 12; + static APPLICATION_LIST_PADDING_RIGHT = 12; + static APPLICATION_LIST_MARGIN_BOTTOM = 50; + static APPLICATION_LISTITEM_PADDING_LEFT = 12; + static APPLICATION_LISTITEM_PADDING_RIGHT = 12; + static APPLICATION_TEXTINPUT_PADDING_LEFT = 12; + static APPLICATION_TEXTINPUT_PADDING_TOP = 8; + static APPLICATION_TEXTINPUT_PADDING_RIGHT = 24; + static APPLICATION_COLUMN_HEIGHT = '93%'; + static APPLICATION_ALPHABETINDEX_MARGIN_TOP = 12; + static APPLICATION_ALPHABETINDEX_WIDTH = 24; + static APPLICATION_TEXT_DECORATION_WIDTH = '90%'; + static APPLICATION_TEXT_DECORATION_MARGIN_LEFT = 56; + static LOADING_WIDTH = 100; + + // slice + static SLICE_START = 0; + static SLICE_END = -1; + static SLICE_START_INDEX = 0; + static SLICE_END_INDEX = 1; + + //group number + static FIXED_GROUP = 1; + static CHANGE_GROUP = 2; + static OTHER_GROUP = 3; + + // tabBar + static BAR_WIDTH = 285; + + // setTimeout + static DELAY_TIME = 1000; + static DELAY_TIME_MAX = 2000; + + // radio + static RADIO_ALLOW_NAME = '允许'; + static RADIO_ALLOW_INDEX = 0; + static RADIO_ALLOW_GROUP_NAME = 'radio'; + static RADIO_BAN_NAME = '禁止'; + static RADIO_BAN_INDEX = 1; + static RADIO_BAN_GROUP_NAME = 'radio'; + + //shape + static SHAPE_DIA = 24; + static SHAPE_BAN_DIA = 23; + static SHAPE_BIG_DIA = 48; + static SHAPE_OFFSET_X = -24; + static SHAPE_BAN_OFFSET = .5; + static SHAPE_ALLOW_DIA = 16; + static SHAPE_ALLOW_OFFSET = 4; + static SHAPE_ZINDEX = 10; + + // utils + static CHAR_CODE = 0; + static UNI_MAX = 40869; + static UNI_MIN = 19968; + + static PARMETER_BUNDLE_FLAG = 16; + static USERID = 100; + + static PERMISSION_INDEX = 0; + + static PERMISSION_NUM = 0; + + static PERMISSION_FLAG = 2; + static API_VERSION_SUPPORT_STAGE = 9; + + static PRE_AUTHORIZATION_NOT_MODIFIED = 4; + + static BUNDLE_NAME = 'com.ohos.permissionmanager' + + static START_SUBSCRIPT = 0 + static END_SUBSCRIPT = 500 + + static RECORD_PADDING_BOTTOM = '20%' + + + + + //////////////////////////////////////////// + // icon of dialog + static DIALOG_ICON_WIDTH = 24; + static DIALOG_ICON_HEIGHT = 24; + static DIALOG_ICON_MARGIN_TOP = 23; + + // label text of dialog + static DIALOG_LABEL_FONT_SIZE = 10; + static DIALOG_LABEL_MARGIN_TOP = 2; + static DIALOG_LABEL_LINE_HEIGHT = 14; + + // request text of dialog + static DIALOG_REQ_FONT_SIZE = 16; + static DIALOG_REQ_MARGIN_TOP = 16; + static DIALOG_REQ_MARGIN_LEFT = 24; + static DIALOG_REQ_LINE_HEIGHT = 22; + + // description text of dialog + static DIALOG_DESP_FONT_SIZE = 14; + static DIALOG_DESP_MARGIN_TOP = 2; + static DIALOG_DESP_MARGIN_LEFT = 24; + static DIALOG_DESP_MARGIN_RIGHT = 24; + static DIALOG_DESP_MARGIN_BOTTOM = 8; + static DIALOG_DESP_LINE_HEIGHT = 19; + + static BUTTON_FONT_SIZE = 16; + static BUTTON_DIVIDER_FONT_SIZE = 24; + static BUTTON_MARGIN_TOP = 8; + static BUTTON_MARGIN_BOTTOM = 16; + static BUTTON_MARGIN_LEFT = 16; + static BUTTON_MARGIN_RIGHT = 16; + static BUTTON_HEIGHT = 40; + static BUTTON_WIDTH = 177; + + static DIALOG_PRIVACY_BORDER_RADIUS = 32; + static DIALOG_PRIVACY_WIDTH = 395; + static DIALOG_PADDING_BOTTOM = 16; + + // initial check status + static INIT_NEED_TO_WAIT = 0 + static INIT_NEED_TO_VERIFY = 1 + static INIT_NEED_TO_TERMINATED = 2 + static INIT_NEED_TO_REFRESH = 3 + + static RESULT_SUCCESS = 1 + static RESULT_FAILURE = 0 + static RESULT_CODE = 0 + + // + static SETTING_OPER = -1 + static PASS_OPER = 0 + static DYNAMIC_OPER = 1 + static INVALID_OPER = 2 + + // + static INITIAL_INDEX = 10 + static ACCESS_TOKEN = 'ohos.security.accesstoken.tokencallback' + +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/utils.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/utils.ets new file mode 100644 index 000000000..8caae47c6 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/utils.ets @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Resmgr from '@ohos.resourceManager'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +import { permissionGroups, groups } from "../model/permissionGroup"; +import Constants from '../utils/constant'; + +/** + * Get app name resource + * @param {Number} labelId app name id + * @param {String} bundleName Package names + */ +export function getAppLabel(labelId, bundleName) { + return new Promise((resolve) => { + Resmgr.getResourceManager(globalThis.context, bundleName).then(item => { + item.getString(labelId, (error, value) => { + resolve(value); + }) + }).catch(error => { + console.error('Resmgr.getResourceManager failed. Cause: ' + JSON.stringify(error)); + }) + }) +} + +/** + * Get app icon resources + * @param {Number} iconId app icon id + * @param {String} bundleName Package names + */ +export function getAppIcon(iconId, bundleName) { + return new Promise((resolve) => { + Resmgr.getResourceManager(globalThis.context, bundleName).then(item => { + item.getMediaBase64(iconId, (error, value) => { + resolve(value); + }) + }).catch(error => { + console.error('Resmgr.getResourceManager failed. Cause: ' + JSON.stringify(error)); + }) + }) +} + +/** + * verify permission + * @param {Number} accessTokenId + * @param {String} permission permission name + */ +export function verifyAccessToken(accessTokenId, permission) { + return new Promise((resolve) => { + abilityAccessCtrl.createAtManager().verifyAccessToken(accessTokenId, permission).then((res) => { + return resolve(res); + }) + .catch((error) => { + console.error('verifyAccessToken failed. Cause: ' + JSON.stringify(error)); + }) + }) +} + +/** +* Let arkui detect changes in array index assignments。 +*/ +export function changeIndexValue(stateList, changeItem){ + // copy array + let result = stateList.slice(0); + for (let i = 0 ; i < changeItem.length; i++) { + let item = changeItem[i]; + if (!Array.isArray(item)) { + throw new Error("error"); + } + let index = item[0]; + let value = item[1]; + if (index == undefined || value == undefined) { + throw new Error("error"); + } + if (index < 0 || index > stateList.length - 1) { + continue; + } + let start = result.slice(0, index); + start = start.concat([value]); + result = start.concat(result.slice(index + 1)); + } + return result; +} + +// List of Chinese Pinyin Initials +let strChineseFirstPY = "YDYQSXMWZSSXJBYMGCCZQPSSQBYCDSCDQLDYLYBSSJGYZZJJFKCCLZDHWDWZJLJPFYYNWJJTMYHZWZHFLZPPQHGSC" + +"YYYNJQYXXGJHHSDSJNKKTMOMLCRXYPSNQSECCQZGGLLYJLMYZZSECYKYYHQWJSSGGYXYZYJWWKDJHYCHMYXJTLXJYQBYXZLDWRDJRWYSRLDZJPCBZ" + +"JJBRCFTLECZSTZFXXZHTRQHYBDLYCZSSYMMRFMYQZPWWJJYFCRWFDFZQPYDDWYXKYJAWJFFXYPSFTZYHHYZYSWCJYXSCLCXXWZZXNBGNNXBXLZSZS" + +"BSGPYSYZDHMDZBQBZCWDZZYYTZHBTSYYBZGNTNXQYWQSKBPHHLXGYBFMJEBJHHGQTJCYSXSTKZHLYCKGLYSMZXYALMELDCCXGZYRJXSDLTYZCQKCN" + +"NJWHJTZZCQLJSTSTBNXBTYXCEQXGKWJYFLZQLYHYXSPSFXLMPBYSXXXYDJCZYLLLSJXFHJXPJBTFFYABYXBHZZBJYZLWLCZGGBTSSMDTJZXPTHYQT" + +"GLJSCQFZKJZJQNLZWLSLHDZBWJNCJZYZSQQYCQYRZCJJWYBRTWPYFTWEXCSKDZCTBZHYZZYYJXZCFFZZMJYXXSDZZOTTBZLQWFCKSZSXFYRLNYJMB" + +"DTHJXSQQCCSBXYYTSYFBXDZTGBCNSLCYZZPSAZYZZSCJCSHZQYDXLBPJLLMQXTYDZXSQJTZPXLCGLQTZWJBHCTSYJSFXYEJJTLBGXSXJMYJQQPFZA" + +"SYJNTYDJXKJCDJSZCBARTDCLYJQMWNQNCLLLKBYBZZSYHQQLTWLCCXTXLLZNTYLNEWYZYXCZXXGRKRMTCNDNJTSYYSSDQDGHSDBJGHRWRQLYBGLXH" + +"LGTGXBQJDZPYJSJYJCTMRNYMGRZJCZGJMZMGXMPRYXKJNYMSGMZJYMKMFXMLDTGFBHCJHKYLPFMDXLQJJSMTQGZSJLQDLDGJYCALCMZCSDJLLNXDJ" + +"FFFFJCZFMZFFPFKHKGDPSXKTACJDHHZDDCRRCFQYJKQCCWJDXHWJLYLLZGCFCQDSMLZPBJJPLSBCJGGDCKKDEZSQCCKJGCGKDJTJDLZYCXKLQSCGJ" + +"CLTFPCQCZGWPJDQYZJJBYJHSJDZWGFSJGZKQCCZLLPSPKJGQJHZZLJPLGJGJJTHJJYJZCZMLZLYQBGJWMLJKXZDZNJQSYZMLJLLJKYWXMKJLHSKJG" + +"BMCLYYMKXJQLBMLLKMDXXKWYXYSLMLPSJQQJQXYXFJTJDXMXXLLCXQBSYJBGWYMBGGBCYXPJYGPEPFGDJGBHBNSQJYZJKJKHXQFGQZKFHYGKHDKLL" + +"SDJQXPQYKYBNQSXQNSZSWHBSXWHXWBZZXDMNSJBSBKBBZKLYLXGWXDRWYQZMYWSJQLCJXXJXKJEQXSCYETLZHLYYYSDZPAQYZCMTLSHTZCFYZYXYL" + +"JSDCJQAGYSLCQLYYYSHMRQQKLDXZSCSSSYDYCJYSFSJBFRSSZQSBXXPXJYSDRCKGJLGDKZJZBDKTCSYQPYHSTCLDJDHMXMCGXYZHJDDTMHLTXZXYL" + +"YMOHYJCLTYFBQQXPFBDFHHTKSQHZYYWCNXXCRWHOWGYJLEGWDQCWGFJYCSNTMYTOLBYGWQWESJPWNMLRYDZSZTXYQPZGCWXHNGPYXSHMYQJXZTDPP" + +"BFYHZHTJYFDZWKGKZBLDNTSXHQEEGZZYLZMMZYJZGXZXKHKSTXNXXWYLYAPSTHXDWHZYMPXAGKYDXBHNHXKDPJNMYHYLPMGOCSLNZHKXXLPZZLBML" + +"SFBHHGYGYYGGBHSCYAQTYWLXTZQCEZYDQDQMMHTKLLSZHLSJZWFYHQSWSCWLQAZYNYTLSXTHAZNKZZSZZLAXXZWWCTGQQTDDYZTCCHYQZFLXPSLZY" + +"GPZSZNGLNDQTBDLXGTCTAJDKYWNSYZLJHHZZCWNYYZYWMHYCHHYXHJKZWSXHZYXLYSKQYSPSLYZWMYPPKBYGLKZHTYXAXQSYSHXASMCHKDSCRSWJP" + +"WXSGZJLWWSCHSJHSQNHCSEGNDAQTBAALZZMSSTDQJCJKTSCJAXPLGGXHHGXXZCXPDMMHLDGTYBYSJMXHMRCPXXJZCKZXSHMLQXXTTHXWZFKHCCZDY" + +"TCJYXQHLXDHYPJQXYLSYYDZOZJNYXQEZYSQYAYXWYPDGXDDXSPPYZNDLTWRHXYDXZZJHTCXMCZLHPYYYYMHZLLHNXMYLLLMDCPPXHMXDKYCYRDLTX" + +"JCHHZZXZLCCLYLNZSHZJZZLNNRLWHYQSNJHXYNTTTKYJPYCHHYEGKCTTWLGQRLGGTGTYGYHPYHYLQYQGCWYQKPYYYTTTTLHYHLLTYTTSPLKYZXGZW" + +"GPYDSSZZDQXSKCQNMJJZZBXYQMJRTFFBTKHZKBXLJJKDXJTLBWFZPPTKQTZTGPDGNTPJYFALQMKGXBDCLZFHZCLLLLADPMXDJHLCCLGYHDZFGYDDG" + +"CYYFGYDXKSSEBDHYKDKDKHNAXXYBPBYYHXZQGAFFQYJXDMLJCSQZLLPCHBSXGJYNDYBYQSPZWJLZKSDDTACTBXZDYZYPJZQSJNKKTKNJDJGYYPGTL" + +"FYQKASDNTCYHBLWDZHBBYDWJRYGKZYHEYYFJMSDTYFZJJHGCXPLXHLDWXXJKYTCYKSSSMTWCTTQZLPBSZDZWZXGZAGYKTYWXLHLSPBCLLOQMMZSSL" + +"CMBJCSZZKYDCZJGQQDSMCYTZQQLWZQZXSSFPTTFQMDDZDSHDTDWFHTDYZJYQJQKYPBDJYYXTLJHDRQXXXHAYDHRJLKLYTWHLLRLLRCXYLBWSRSZZS" + +"YMKZZHHKYHXKSMDSYDYCJPBZBSQLFCXXXNXKXWYWSDZYQOGGQMMYHCDZTTFJYYBGSTTTYBYKJDHKYXBELHTYPJQNFXFDYKZHQKZBYJTZBXHFDXKDA" + +"SWTAWAJLDYJSFHBLDNNTNQJTJNCHXFJSRFWHZFMDRYJYJWZPDJKZYJYMPCYZNYNXFBYTFYFWYGDBNZZZDNYTXZEMMQBSQEHXFZMBMFLZZSRXYMJGS" + +"XWZJSPRYDJSJGXHJJGLJJYNZZJXHGXKYMLPYYYCXYTWQZSWHWLYRJLPXSLSXMFSWWKLCTNXNYNPSJSZHDZEPTXMYYWXYYSYWLXJQZQXZDCLEEELMC" + +"PJPCLWBXSQHFWWTFFJTNQJHJQDXHWLBYZNFJLALKYYJLDXHHYCSTYYWNRJYXYWTRMDRQHWQCMFJDYZMHMYYXJWMYZQZXTLMRSPWWCHAQBXYGZYPXY" + +"YRRCLMPYMGKSJSZYSRMYJSNXTPLNBAPPYPYLXYYZKYNLDZYJZCZNNLMZHHARQMPGWQTZMXXMLLHGDZXYHXKYXYCJMFFYYHJFSBSSQLXXNDYCANNMT" + +"CJCYPRRNYTYQNYYMBMSXNDLYLYSLJRLXYSXQMLLYZLZJJJKYZZCSFBZXXMSTBJGNXYZHLXNMCWSCYZYFZLXBRNNNYLBNRTGZQYSATSWRYHYJZMZDH" + +"ZGZDWYBSSCSKXSYHYTXXGCQGXZZSHYXJSCRHMKKBXCZJYJYMKQHZJFNBHMQHYSNJNZYBKNQMCLGQHWLZNZSWXKHLJHYYBQLBFCDSXDLDSPFZPSKJY" + +"ZWZXZDDXJSMMEGJSCSSMGCLXXKYYYLNYPWWWGYDKZJGGGZGGSYCKNJWNJPCXBJJTQTJWDSSPJXZXNZXUMELPXFSXTLLXCLJXJJLJZXCTPSWXLYDHL" + +"YQRWHSYCSQYYBYAYWJJJQFWQCQQCJQGXALDBZZYJGKGXPLTZYFXJLTPADKYQHPMATLCPDCKBMTXYBHKLENXDLEEGQDYMSAWHZMLJTWYGXLYQZLJEE" + +"YYBQQFFNLYXRDSCTGJGXYYNKLLYQKCCTLHJLQMKKZGCYYGLLLJDZGYDHZWXPYSJBZKDZGYZZHYWYFQYTYZSZYEZZLYMHJJHTSMQWYZLKYYWZCSRKQ" + +"YTLTDXWCTYJKLWSQZWBDCQYNCJSRSZJLKCDCDTLZZZACQQZZDDXYPLXZBQJYLZLLLQDDZQJYJYJZYXNYYYNYJXKXDAZWYRDLJYYYRJLXLLDYXJCYW" + +"YWNQCCLDDNYYYNYCKCZHXXCCLGZQJGKWPPCQQJYSBZZXYJSQPXJPZBSBDSFNSFPZXHDWZTDWPPTFLZZBZDMYYPQJRSDZSQZSQXBDGCPZSWDWCSQZG" + +"MDHZXMWWFYBPDGPHTMJTHZSMMBGZMBZJCFZWFZBBZMQCFMBDMCJXLGPNJBBXGYHYYJGPTZGZMQBQTCGYXJXLWZKYDPDYMGCFTPFXYZTZXDZXTGKMT" + +"YBBCLBJASKYTSSQYYMSZXFJEWLXLLSZBQJJJAKLYLXLYCCTSXMCWFKKKBSXLLLLJYXTYLTJYYTDPJHNHNNKBYQNFQYYZBYYESSESSGDYHFHWTCJBS" + +"DZZTFDMXHCNJZYMQWSRYJDZJQPDQBBSTJGGFBKJBXTGQHNGWJXJGDLLTHZHHYYYYYYSXWTYYYCCBDBPYPZYCCZYJPZYWCBDLFWZCWJDXXHYHLHWZZ" + +"XJTCZLCDPXUJCZZZLYXJJTXPHFXWPYWXZPTDZZBDZCYHJHMLXBQXSBYLRDTGJRRCTTTHYTCZWMXFYTWWZCWJWXJYWCSKYBZSCCTZQNHXNWXXKHKFH" + +"TSWOCCJYBCMPZZYKBNNZPBZHHZDLSYDDYTYFJPXYNGFXBYQXCBHXCPSXTYZDMKYSNXSXLHKMZXLYHDHKWHXXSSKQYHHCJYXGLHZXCSNHEKDTGZXQY" + +"PKDHEXTYKCNYMYYYPKQYYYKXZLTHJQTBYQHXBMYHSQCKWWYLLHCYYLNNEQXQWMCFBDCCMLJGGXDQKTLXKGNQCDGZJWYJJLYHHQTTTNWCHMXCXWHWS" + +"ZJYDJCCDBQCDGDNYXZTHCQRXCBHZTQCBXWGQWYYBXHMBYMYQTYEXMQKYAQYRGYZSLFYKKQHYSSQYSHJGJCNXKZYCXSBXYXHYYLSTYCXQTHYSMGSCP" + +"MMGCCCCCMTZTASMGQZJHKLOSQYLSWTMXSYQKDZLJQQYPLSYCZTCQQPBBQJZCLPKHQZYYXXDTDDTSJCXFFLLCHQXMJLWCJCXTSPYCXNDTJSHJWXDQQ" + +"JSKXYAMYLSJHMLALYKXCYYDMNMDQMXMCZNNCYBZKKYFLMCHCMLHXRCJJHSYLNMTJZGZGYWJXSRXCWJGJQHQZDQJDCJJZKJKGDZQGJJYJYLXZXXCDQ" + +"HHHEYTMHLFSBDJSYYSHFYSTCZQLPBDRFRZTZYKYWHSZYQKWDQZRKMSYNBCRXQBJYFAZPZZEDZCJYWBCJWHYJBQSZYWRYSZPTDKZPFPBNZTKLQYHBB" + +"ZPNPPTYZZYBQNYDCPJMMCYCQMCYFZZDCMNLFPBPLNGQJTBTTNJZPZBBZNJKLJQYLNBZQHKSJZNGGQSZZKYXSHPZSNBCGZKDDZQANZHJKDRTLZLSWJ" + +"LJZLYWTJNDJZJHXYAYNCBGTZCSSQMNJPJYTYSWXZFKWJQTKHTZPLBHSNJZSYZBWZZZZLSYLSBJHDWWQPSLMMFBJDWAQYZTCJTBNNWZXQXCDSLQGDS" + +"DPDZHJTQQPSWLYYJZLGYXYZLCTCBJTKTYCZJTQKBSJLGMGZDMCSGPYNJZYQYYKNXRPWSZXMTNCSZZYXYBYHYZAXYWQCJTLLCKJJTJHGDXDXYQYZZB" + +"YWDLWQCGLZGJGQRQZCZSSBCRPCSKYDZNXJSQGXSSJMYDNSTZTPBDLTKZWXQWQTZEXNQCZGWEZKSSBYBRTSSSLCCGBPSZQSZLCCGLLLZXHZQTHCZMQ" + +"GYZQZNMCOCSZJMMZSQPJYGQLJYJPPLDXRGZYXCCSXHSHGTZNLZWZKJCXTCFCJXLBMQBCZZWPQDNHXLJCTHYZLGYLNLSZZPCXDSCQQHJQKSXZPBAJY" + +"EMSMJTZDXLCJYRYYNWJBNGZZTMJXLTBSLYRZPYLSSCNXPHLLHYLLQQZQLXYMRSYCXZLMMCZLTZSDWTJJLLNZGGQXPFSKYGYGHBFZPDKMWGHCXMSGD" + +"XJMCJZDYCABXJDLNBCDQYGSKYDQTXDJJYXMSZQAZDZFSLQXYJSJZYLBTXXWXQQZBJZUFBBLYLWDSLJHXJYZJWTDJCZFQZQZZDZSXZZQLZCDZFJHYS" + +"PYMPQZMLPPLFFXJJNZZYLSJEYQZFPFZKSYWJJJHRDJZZXTXXGLGHYDXCSKYSWMMZCWYBAZBJKSHFHJCXMHFQHYXXYZFTSJYZFXYXPZLCHMZMBXHZZ" + +"SXYFYMNCWDABAZLXKTCSHHXKXJJZJSTHYGXSXYYHHHJWXKZXSSBZZWHHHCWTZZZPJXSNXQQJGZYZYWLLCWXZFXXYXYHXMKYYSWSQMNLNAYCYSPMJK" + +"HWCQHYLAJJMZXHMMCNZHBHXCLXTJPLTXYJHDYYLTTXFSZHYXXSJBJYAYRSMXYPLCKDUYHLXRLNLLSTYZYYQYGYHHSCCSMZCTZQXKYQFPYYRPFFLKQ" + +"UNTSZLLZMWWTCQQYZWTLLMLMPWMBZSSTZRBPDDTLQJJBXZCSRZQQYGWCSXFWZLXCCRSZDZMCYGGDZQSGTJSWLJMYMMZYHFBJDGYXCCPSHXNZCSBSJ" + +"YJGJMPPWAFFYFNXHYZXZYLREMZGZCYZSSZDLLJCSQFNXZKPTXZGXJJGFMYYYSNBTYLBNLHPFZDCYFBMGQRRSSSZXYSGTZRNYDZZCDGPJAFJFZKNZB" + +"LCZSZPSGCYCJSZLMLRSZBZZLDLSLLYSXSQZQLYXZLSKKBRXBRBZCYCXZZZEEYFGKLZLYYHGZSGZLFJHGTGWKRAAJYZKZQTSSHJJXDCYZUYJLZYRZD" + +"QQHGJZXSSZBYKJPBFRTJXLLFQWJHYLQTYMBLPZDXTZYGBDHZZRBGXHWNJTJXLKSCFSMWLSDQYSJTXKZSCFWJLBXFTZLLJZLLQBLSQMQQCGCZFPBPH" + +"ZCZJLPYYGGDTGWDCFCZQYYYQYSSCLXZSKLZZZGFFCQNWGLHQYZJJCZLQZZYJPJZZBPDCCMHJGXDQDGDLZQMFGPSYTSDYFWWDJZJYSXYYCZCYHZWPB" + +"YKXRYLYBHKJKSFXTZJMMCKHLLTNYYMSYXYZPYJQYCSYCWMTJJKQYRHLLQXPSGTLYYCLJSCPXJYZFNMLRGJJTYZBXYZMSJYJHHFZQMSYXRSZCWTLRT" + +"QZSSTKXGQKGSPTGCZNJSJCQCXHMXGGZTQYDJKZDLBZSXJLHYQGGGTHQSZPYHJHHGYYGKGGCWJZZYLCZLXQSFTGZSLLLMLJSKCTBLLZZSZMMNYTPZS" + +"XQHJCJYQXYZXZQZCPSHKZZYSXCDFGMWQRLLQXRFZTLYSTCTMJCXJJXHJNXTNRZTZFQYHQGLLGCXSZSJDJLJCYDSJTLNYXHSZXCGJZYQPYLFHDJSBP" + +"CCZHJJJQZJQDYBSSLLCMYTTMQTBHJQNNYGKYRQYQMZGCJKPDCGMYZHQLLSLLCLMHOLZGDYYFZSLJCQZLYLZQJESHNYLLJXGJXLYSYYYXNBZLJSSZC" + +"QQCJYLLZLTJYLLZLLBNYLGQCHXYYXOXCXQKYJXXXYKLXSXXYQXCYKQXQCSGYXXYQXYGYTQOHXHXPYXXXULCYEYCHZZCBWQBBWJQZSCSZSSLZYLKDE" + +"SJZWMYMCYTSDSXXSCJPQQSQYLYYZYCMDJDZYWCBTJSYDJKCYDDJLBDJJSODZYSYXQQYXDHHGQQYQHDYXWGMMMAJDYBBBPPBCMUUPLJZSMTXERXJMH" + +"QNUTPJDCBSSMSSSTKJTSSMMTRCPLZSZMLQDSDMJMQPNQDXCFYNBFSDQXYXHYAYKQYDDLQYYYSSZBYDSLNTFQTZQPZMCHDHCZCWFDXTMYQSPHQYYXS" + +"RGJCWTJTZZQMGWJJTJHTQJBBHWZPXXHYQFXXQYWYYHYSCDYDHHQMNMTMWCPBSZPPZZGLMZFOLLCFWHMMSJZTTDHZZYFFYTZZGZYSKYJXQYJZQBHMB" + +"ZZLYGHGFMSHPZFZSNCLPBQSNJXZSLXXFPMTYJYGBXLLDLXPZJYZJYHHZCYWHJYLSJEXFSZZYWXKZJLUYDTMLYMQJPWXYHXSKTQJEZRPXXZHHMHWQP" + +"WQLYJJQJJZSZCPHJLCHHNXJLQWZJHBMZYXBDHHYPZLHLHLGFWLCHYYTLHJXCJMSCPXSTKPNHQXSRTYXXTESYJCTLSSLSTDLLLWWYHDHRJZSFGXTSY" + +"CZYNYHTDHWJSLHTZDQDJZXXQHGYLTZPHCSQFCLNJTCLZPFSTPDYNYLGMJLLYCQHYSSHCHYLHQYQTMZYPBYWRFQYKQSYSLZDQJMPXYYSSRHZJNYWTQ" + +"DFZBWWTWWRXCWHGYHXMKMYYYQMSMZHNGCEPMLQQMTCWCTMMPXJPJJHFXYYZSXZHTYBMSTSYJTTQQQYYLHYNPYQZLCYZHZWSMYLKFJXLWGXYPJYTYS" + +"YXYMZCKTTWLKSMZSYLMPWLZWXWQZSSAQSYXYRHSSNTSRAPXCPWCMGDXHXZDZYFJHGZTTSBJHGYZSZYSMYCLLLXBTYXHBBZJKSSDMALXHYCFYGMQYP" + +"JYCQXJLLLJGSLZGQLYCJCCZOTYXMTMTTLLWTGPXYMZMKLPSZZZXHKQYSXCTYJZYHXSHYXZKXLZWPSQPYHJWPJPWXQQYLXSDHMRSLZZYZWTTCYXYSZ" + +"ZSHBSCCSTPLWSSCJCHNLCGCHSSPHYLHFHHXJSXYLLNYLSZDHZXYLSXLWZYKCLDYAXZCMDDYSPJTQJZLNWQPSSSWCTSTSZLBLNXSMNYYMJQBQHRZWT" + +"YYDCHQLXKPZWBGQYBKFCMZWPZLLYYLSZYDWHXPSBCMLJBSCGBHXLQHYRLJXYSWXWXZSLDFHLSLYNJLZYFLYJYCDRJLFSYZFSLLCQYQFGJYHYXZLYL" + +"MSTDJCYHBZLLNWLXXYGYYHSMGDHXXHHLZZJZXCZZZCYQZFNGWPYLCPKPYYPMCLQKDGXZGGWQBDXZZKZFBXXLZXJTPJPTTBYTSZZDWSLCHZHSLTYXH" + +"QLHYXXXYYZYSWTXZKHLXZXZPYHGCHKCFSYHUTJRLXFJXPTZTWHPLYXFCRHXSHXKYXXYHZQDXQWULHYHMJTBFLKHTXCWHJFWJCFPQRYQXCYYYQYGRP" + +"YWSGSUNGWCHKZDXYFLXXHJJBYZWTSXXNCYJJYMSWZJQRMHXZWFQSYLZJZGBHYNSLBGTTCSYBYXXWXYHXYYXNSQYXMQYWRGYQLXBBZLJSYLPSYTJZY" + +"HYZAWLRORJMKSCZJXXXYXCHDYXRYXXJDTSQFXLYLTSFFYXLMTYJMJUYYYXLTZCSXQZQHZXLYYXZHDNBRXXXJCTYHLBRLMBRLLAXKYLLLJLYXXLYCR" + +"YLCJTGJCMTLZLLCYZZPZPCYAWHJJFYBDYYZSMPCKZDQYQPBPCJPDCYZMDPBCYYDYCNNPLMTMLRMFMMGWYZBSJGYGSMZQQQZTXMKQWGXLLPJGZBQCD" + +"JJJFPKJKCXBLJMSWMDTQJXLDLPPBXCWRCQFBFQJCZAHZGMYKPHYYHZYKNDKZMBPJYXPXYHLFPNYYGXJDBKXNXHJMZJXSTRSTLDXSKZYSYBZXJLXYS" + +"LBZYSLHXJPFXPQNBYLLJQKYGZMCYZZYMCCSLCLHZFWFWYXZMWSXTYNXJHPYYMCYSPMHYSMYDYSHQYZCHMJJMZCAAGCFJBBHPLYZYLXXSDJGXDHKXX" + +"TXXNBHRMLYJSLTXMRHNLXQJXYZLLYSWQGDLBJHDCGJYQYCMHWFMJYBMBYJYJWYMDPWHXQLDYGPDFXXBCGJSPCKRSSYZJMSLBZZJFLJJJLGXZGYXYX" + +"LSZQYXBEXYXHGCXBPLDYHWETTWWCJMBTXCHXYQXLLXFLYXLLJLSSFWDPZSMYJCLMWYTCZPCHQEKCQBWLCQYDPLQPPQZQFJQDJHYMMCXTXDRMJWRHX" + +"CJZYLQXDYYNHYYHRSLSRSYWWZJYMTLTLLGTQCJZYABTCKZCJYCCQLJZQXALMZYHYWLWDXZXQDLLQSHGPJFJLJHJABCQZDJGTKHSSTCYJLPSWZLXZX" + +"RWGLDLZRLZXTGSLLLLZLYXXWGDZYGBDPHZPBRLWSXQBPFDWOFMWHLYPCBJCCLDMBZPBZZLCYQXLDOMZBLZWPDWYYGDSTTHCSQSCCRSSSYSLFYBFNT" + +"YJSZDFNDPDHDZZMBBLSLCMYFFGTJJQWFTMTPJWFNLBZCMMJTGBDZLQLPYFHYYMJYLSDCHDZJWJCCTLJCLDTLJJCPDDSQDSSZYBNDBJLGGJZXSXNLY" + +"CYBJXQYCBYLZCFZPPGKCXZDZFZTJJFJSJXZBNZYJQTTYJYHTYCZHYMDJXTTMPXSPLZCDWSLSHXYPZGTFMLCJTYCBPMGDKWYCYZCDSZZYHFLYCTYGW" + +"HKJYYLSJCXGYWJCBLLCSNDDBTZBSCLYZCZZSSQDLLMQYYHFSLQLLXFTYHABXGWNYWYYPLLSDLDLLBJCYXJZMLHLJDXYYQYTDLLLBUGBFDFBBQJZZM" + +"DPJHGCLGMJJPGAEHHBWCQXAXHHHZCHXYPHJAXHLPHJPGPZJQCQZGJJZZUZDMQYYBZZPHYHYBWHAZYJHYKFGDPFQSDLZMLJXKXGALXZDAGLMDGXMWZ" + +"QYXXDXXPFDMMSSYMPFMDMMKXKSYZYSHDZKXSYSMMZZZMSYDNZZCZXFPLSTMZDNMXCKJMZTYYMZMZZMSXHHDCZJEMXXKLJSTLWLSQLYJZLLZJSSDPP" + +"MHNLZJCZYHMXXHGZCJMDHXTKGRMXFWMCGMWKDTKSXQMMMFZZYDKMSCLCMPCGMHSPXQPZDSSLCXKYXTWLWJYAHZJGZQMCSNXYYMMPMLKJXMHLMLQMX" + +"CTKZMJQYSZJSYSZHSYJZJCDAJZYBSDQJZGWZQQXFKDMSDJLFWEHKZQKJPEYPZYSZCDWYJFFMZZYLTTDZZEFMZLBNPPLPLPEPSZALLTYLKCKQZKGEN" + +"QLWAGYXYDPXLHSXQQWQCQXQCLHYXXMLYCCWLYMQYSKGCHLCJNSZKPYZKCQZQLJPDMDZHLASXLBYDWQLWDNBQCRYDDZTJYBKBWSZDXDTNPJDTCTQDF" + +"XQQMGNXECLTTBKPWSLCTYQLPWYZZKLPYGZCQQPLLKCCYLPQMZCZQCLJSLQZDJXLDDHPZQDLJJXZQDXYZQKZLJCYQDYJPPYPQYKJYRMPCBYMCXKLLZ" + +"LLFQPYLLLMBSGLCYSSLRSYSQTMXYXZQZFDZUYSYZTFFMZZSMZQHZSSCCMLYXWTPZGXZJGZGSJSGKDDHTQGGZLLBJDZLCBCHYXYZHZFYWXYZYMSDBZ" + +"ZYJGTSMTFXQYXQSTDGSLNXDLRYZZLRYYLXQHTXSRTZNGZXBNQQZFMYKMZJBZYMKBPNLYZPBLMCNQYZZZSJZHJCTZKHYZZJRDYZHNPXGLFZTLKGJTC" + +"TSSYLLGZRZBBQZZKLPKLCZYSSUYXBJFPNJZZXCDWXZYJXZZDJJKGGRSRJKMSMZJLSJYWQSKYHQJSXPJZZZLSNSHRNYPZTWCHKLPSRZLZXYJQXQKYS" + +"JYCZTLQZYBBYBWZPQDWWYZCYTJCJXCKCWDKKZXSGKDZXWWYYJQYYTCYTDLLXWKCZKKLCCLZCQQDZLQLCSFQCHQHSFSMQZZLNBJJZBSJHTSZDYSJQJ" + +"PDLZCDCWJKJZZLPYCGMZWDJJBSJQZSYZYHHXJPBJYDSSXDZNCGLQMBTSFSBPDZDLZNFGFJGFSMPXJQLMBLGQCYYXBQKDJJQYRFKZTJDHCZKLBSDZC" + +"FJTPLLJGXHYXZCSSZZXSTJYGKGCKGYOQXJPLZPBPGTGYJZGHZQZZLBJLSQFZGKQQJZGYCZBZQTLDXRJXBSXXPZXHYZYCLWDXJJHXMFDZPFZHQHQMQ" + +"GKSLYHTYCGFRZGNQXCLPDLBZCSCZQLLJBLHBZCYPZZPPDYMZZSGYHCKCPZJGSLJLNSCDSLDLXBMSTLDDFJMKDJDHZLZXLSZQPQPGJLLYBDSZGQLBZ" + +"LSLKYYHZTTNTJYQTZZPSZQZTLLJTYYLLQLLQYZQLBDZLSLYYZYMDFSZSNHLXZNCZQZPBWSKRFBSYZMTHBLGJPMCZZLSTLXSHTCSYZLZBLFEQHLXFL" + +"CJLYLJQCBZLZJHHSSTBRMHXZHJZCLXFNBGXGTQJCZTMSFZKJMSSNXLJKBHSJXNTNLZDNTLMSJXGZJYJCZXYJYJWRWWQNZTNFJSZPZSHZJFYRDJSFS" + +"ZJZBJFZQZZHZLXFYSBZQLZSGYFTZDCSZXZJBQMSZKJRHYJZCKMJKHCHGTXKXQGLXPXFXTRTYLXJXHDTSJXHJZJXZWZLCQSBTXWXGXTXXHXFTSDKFJ" + +"HZYJFJXRZSDLLLTQSQQZQWZXSYQTWGWBZCGZLLYZBCLMQQTZHZXZXLJFRMYZFLXYSQXXJKXRMQDZDMMYYBSQBHGZMWFWXGMXLZPYYTGZYCCDXYZXY" + +"WGSYJYZNBHPZJSQSYXSXRTFYZGRHZTXSZZTHCBFCLSYXZLZQMZLMPLMXZJXSFLBYZMYQHXJSXRXSQZZZSSLYFRCZJRCRXHHZXQYDYHXSJJHZCXZBT" + +"YNSYSXJBQLPXZQPYMLXZKYXLXCJLCYSXXZZLXDLLLJJYHZXGYJWKJRWYHCPSGNRZLFZWFZZNSXGXFLZSXZZZBFCSYJDBRJKRDHHGXJLJJTGXJXXST" + +"JTJXLYXQFCSGSWMSBCTLQZZWLZZKXJMLTMJYHSDDBXGZHDLBMYJFRZFSGCLYJBPMLYSMSXLSZJQQHJZFXGFQFQBPXZGYYQXGZTCQWYLTLGWSGWHRL" + +"FSFGZJMGMGBGTJFSYZZGZYZAFLSSPMLPFLCWBJZCLJJMZLPJJLYMQDMYYYFBGYGYZMLYZDXQYXRQQQHSYYYQXYLJTYXFSFSLLGNQCYHYCWFHCCCFX" + +"PYLYPLLZYXXXXXKQHHXSHJZCFZSCZJXCPZWHHHHHAPYLQALPQAFYHXDYLUKMZQGGGDDESRNNZLTZGCHYPPYSQJJHCLLJTOLNJPZLJLHYMHEYDYDSQ" + +"YCDDHGZUNDZCLZYZLLZNTNYZGSLHSLPJJBDGWXPCDUTJCKLKCLWKLLCASSTKZZDNQNTTLYYZSSYSSZZRYLJQKCQDHHCRXRZYDGRGCWCGZQFFFPPJF" + +"ZYNAKRGYWYQPQXXFKJTSZZXSWZDDFBBXTBGTZKZNPZZPZXZPJSZBMQHKCYXYLDKLJNYPKYGHGDZJXXEAHPNZKZTZCMXCXMMJXNKSZQNMNLWBWWXJK" + +"YHCPSTMCSQTZJYXTPCTPDTNNPGLLLZSJLSPBLPLQHDTNJNLYYRSZFFJFQWDPHZDWMRZCCLODAXNSSNYZRESTYJWJYJDBCFXNMWTTBYLWSTSZGYBLJ" + +"PXGLBOCLHPCBJLTMXZLJYLZXCLTPNCLCKXTPZJSWCYXSFYSZDKNTLBYJCYJLLSTGQCBXRYZXBXKLYLHZLQZLNZCXWJZLJZJNCJHXMNZZGJZZXTZJX" + +"YCYYCXXJYYXJJXSSSJSTSSTTPPGQTCSXWZDCSYFPTFBFHFBBLZJCLZZDBXGCXLQPXKFZFLSYLTUWBMQJHSZBMDDBCYSCCLDXYCDDQLYJJWMQLLCSG" + +"LJJSYFPYYCCYLTJANTJJPWYCMMGQYYSXDXQMZHSZXPFTWWZQSWQRFKJLZJQQYFBRXJHHFWJJZYQAZMYFRHCYYBYQWLPEXCCZSTYRLTTDMQLYKMBBG" + +"MYYJPRKZNPBSXYXBHYZDJDNGHPMFSGMWFZMFQMMBCMZZCJJLCNUXYQLMLRYGQZCYXZLWJGCJCGGMCJNFYZZJHYCPRRCMTZQZXHFQGTJXCCJEAQCRJ" + +"YHPLQLSZDJRBCQHQDYRHYLYXJSYMHZYDWLDFRYHBPYDTSSCNWBXGLPZMLZZTQSSCPJMXXYCSJYTYCGHYCJWYRXXLFEMWJNMKLLSWTXHYYYNCMMCWJ" + +"DQDJZGLLJWJRKHPZGGFLCCSCZMCBLTBHBQJXQDSPDJZZGKGLFQYWBZYZJLTSTDHQHCTCBCHFLQMPWDSHYYTQWCNZZJTLBYMBPDYYYXSQKXWYYFLXX" + +"NCWCXYPMAELYKKJMZZZBRXYYQJFLJPFHHHYTZZXSGQQMHSPGDZQWBWPJHZJDYSCQWZKTXXSQLZYYMYSDZGRXCKKUJLWPYSYSCSYZLRMLQSYLJXBCX" + +"TLWDQZPCYCYKPPPNSXFYZJJRCEMHSZMSXLXGLRWGCSTLRSXBZGBZGZTCPLUJLSLYLYMTXMTZPALZXPXJTJWTCYYZLBLXBZLQMYLXPGHDSLSSDMXMB" + +"DZZSXWHAMLCZCPJMCNHJYSNSYGCHSKQMZZQDLLKABLWJXSFMOCDXJRRLYQZKJMYBYQLYHETFJZFRFKSRYXFJTWDSXXSYSQJYSLYXWJHSNLXYYXHBH" + +"AWHHJZXWMYLJCSSLKYDZTXBZSYFDXGXZJKHSXXYBSSXDPYNZWRPTQZCZENYGCXQFJYKJBZMLJCMQQXUOXSLYXXLYLLJDZBTYMHPFSTTQQWLHOKYBL" + +"ZZALZXQLHZWRRQHLSTMYPYXJJXMQSJFNBXYXYJXXYQYLTHYLQYFMLKLJTMLLHSZWKZHLJMLHLJKLJSTLQXYLMBHHLNLZXQJHXCFXXLHYHJJGBYZZK" + +"BXSCQDJQDSUJZYYHZHHMGSXCSYMXFEBCQWWRBPYYJQTYZCYQYQQZYHMWFFHGZFRJFCDPXNTQYZPDYKHJLFRZXPPXZDBBGZQSTLGDGYLCQMLCHHMFY" + +"WLZYXKJLYPQHSYWMQQGQZMLZJNSQXJQSYJYCBEHSXFSZPXZWFLLBCYYJDYTDTHWZSFJMQQYJLMQXXLLDTTKHHYBFPWTYYSQQWNQWLGWDEBZWCMYGC" + +"ULKJXTMXMYJSXHYBRWFYMWFRXYQMXYSZTZZTFYKMLDHQDXWYYNLCRYJBLPSXCXYWLSPRRJWXHQYPHTYDNXHHMMYWYTZCSQMTSSCCDALWZTCPQPYJL" + +"LQZYJSWXMZZMMYLMXCLMXCZMXMZSQTZPPQQBLPGXQZHFLJJHYTJSRXWZXSCCDLXTYJDCQJXSLQYCLZXLZZXMXQRJMHRHZJBHMFLJLMLCLQNLDXZLL" + +"LPYPSYJYSXCQQDCMQJZZXHNPNXZMEKMXHYKYQLXSXTXJYYHWDCWDZHQYYBGYBCYSCFGPSJNZDYZZJZXRZRQJJYMCANYRJTLDPPYZBSTJKXXZYPFDW" + +"FGZZRPYMTNGXZQBYXNBUFNQKRJQZMJEGRZGYCLKXZDSKKNSXKCLJSPJYYZLQQJYBZSSQLLLKJXTBKTYLCCDDBLSPPFYLGYDTZJYQGGKQTTFZXBDKT" + +"YYHYBBFYTYYBCLPDYTGDHRYRNJSPTCSNYJQHKLLLZSLYDXXWBCJQSPXBPJZJCJDZFFXXBRMLAZHCSNDLBJDSZBLPRZTSWSBXBCLLXXLZDJZSJPYLY" + +"XXYFTFFFBHJJXGBYXJPMMMPSSJZJMTLYZJXSWXTYLEDQPJMYGQZJGDJLQJWJQLLSJGJGYGMSCLJJXDTYGJQJQJCJZCJGDZZSXQGSJGGCXHQXSNQLZ" + +"ZBXHSGZXCXYLJXYXYYDFQQJHJFXDHCTXJYRXYSQTJXYEFYYSSYYJXNCYZXFXMSYSZXYYSCHSHXZZZGZZZGFJDLTYLNPZGYJYZYYQZPBXQBDZTZCZY" + +"XXYHHSQXSHDHGQHJHGYWSZTMZMLHYXGEBTYLZKQWYTJZRCLEKYSTDBCYKQQSAYXCJXWWGSBHJYZYDHCSJKQCXSWXFLTYNYZPZCCZJQTZWJQDZZZQZ" + +"LJJXLSBHPYXXPSXSHHEZTXFPTLQYZZXHYTXNCFZYYHXGNXMYWXTZSJPTHHGYMXMXQZXTSBCZYJYXXTYYZYPCQLMMSZMJZZLLZXGXZAAJZYXJMZXWD" + +"XZSXZDZXLEYJJZQBHZWZZZQTZPSXZTDSXJJJZNYAZPHXYYSRNQDTHZHYYKYJHDZXZLSWCLYBZYECWCYCRYLCXNHZYDZYDYJDFRJJHTRSQTXYXJRJH" + +"OJYNXELXSFSFJZGHPZSXZSZDZCQZBYYKLSGSJHCZSHDGQGXYZGXCHXZJWYQWGYHKSSEQZZNDZFKWYSSTCLZSTSYMCDHJXXYWEYXCZAYDMPXMDSXYB" + +"SQMJMZJMTZQLPJYQZCGQHXJHHLXXHLHDLDJQCLDWBSXFZZYYSCHTYTYYBHECXHYKGJPXHHYZJFXHWHBDZFYZBCAPNPGNYDMSXHMMMMAMYNBYJTMPX" + +"YYMCTHJBZYFCGTYHWPHFTWZZEZSBZEGPFMTSKFTYCMHFLLHGPZJXZJGZJYXZSBBQSCZZLZCCSTPGXMJSFTCCZJZDJXCYBZLFCJSYZFGSZLYBCWZZB" + +"YZDZYPSWYJZXZBDSYUXLZZBZFYGCZXBZHZFTPBGZGEJBSTGKDMFHYZZJHZLLZZGJQZLSFDJSSCBZGPDLFZFZSZYZYZSYGCXSNXXCHCZXTZZLJFZGQ" + +"SQYXZJQDCCZTQCDXZJYQJQCHXZTDLGSCXZSYQJQTZWLQDQZTQCHQQJZYEZZZPBWKDJFCJPZTYPQYQTTYNLMBDKTJZPQZQZZFPZSBNJLGYJDXJDZZK" + +"ZGQKXDLPZJTCJDQBXDJQJSTCKNXBXZMSLYJCQMTJQWWCJQNJNLLLHJCWQTBZQYDZCZPZZDZYDDCYZZZCCJTTJFZDPRRTZTJDCQTQZDTJNPLZBCLLC" + +"TZSXKJZQZPZLBZRBTJDCXFCZDBCCJJLTQQPLDCGZDBBZJCQDCJWYNLLZYZCCDWLLXWZLXRXNTQQCZXKQLSGDFQTDDGLRLAJJTKUYMKQLLTZYTDYYC" + +"ZGJWYXDXFRSKSTQTENQMRKQZHHQKDLDAZFKYPBGGPZREBZZYKZZSPEGJXGYKQZZZSLYSYYYZWFQZYLZZLZHWCHKYPQGNPGBLPLRRJYXCCSYYHSFZF" + +"YBZYYTGZXYLXCZWXXZJZBLFFLGSKHYJZEYJHLPLLLLCZGXDRZELRHGKLZZYHZLYQSZZJZQLJZFLNBHGWLCZCFJYSPYXZLZLXGCCPZBLLCYBBBBUBB" + +"CBPCRNNZCZYRBFSRLDCGQYYQXYGMQZWTZYTYJXYFWTEHZZJYWLCCNTZYJJZDEDPZDZTSYQJHDYMBJNYJZLXTSSTPHNDJXXBYXQTZQDDTJTDYYTGWS" + +"CSZQFLSHLGLBCZPHDLYZJYCKWTYTYLBNYTSDSYCCTYSZYYEBHEXHQDTWNYGYCLXTSZYSTQMYGZAZCCSZZDSLZCLZRQXYYELJSBYMXSXZTEMBBLLYY" + +"LLYTDQYSHYMRQWKFKBFXNXSBYCHXBWJYHTQBPBSBWDZYLKGZSKYHXQZJXHXJXGNLJKZLYYCDXLFYFGHLJGJYBXQLYBXQPQGZTZPLNCYPXDJYQYDYM" + +"RBESJYYHKXXSTMXRCZZYWXYQYBMCLLYZHQYZWQXDBXBZWZMSLPDMYSKFMZKLZCYQYCZLQXFZZYDQZPZYGYJYZMZXDZFYFYTTQTZHGSPCZMLCCYTZX" + +"JCYTJMKSLPZHYSNZLLYTPZCTZZCKTXDHXXTQCYFKSMQCCYYAZHTJPCYLZLYJBJXTPNYLJYYNRXSYLMMNXJSMYBCSYSYLZYLXJJQYLDZLPQBFZZBLF" + +"NDXQKCZFYWHGQMRDSXYCYTXNQQJZYYPFZXDYZFPRXEJDGYQBXRCNFYYQPGHYJDYZXGRHTKYLNWDZNTSMPKLBTHBPYSZBZTJZSZZJTYYXZPHSSZZBZ" + +"CZPTQFZMYFLYPYBBJQXZMXXDJMTSYSKKBJZXHJCKLPSMKYJZCXTMLJYXRZZQSLXXQPYZXMKYXXXJCLJPRMYYGADYSKQLSNDHYZKQXZYZTCGHZTLML" + +"WZYBWSYCTBHJHJFCWZTXWYTKZLXQSHLYJZJXTMPLPYCGLTBZZTLZJCYJGDTCLKLPLLQPJMZPAPXYZLKKTKDZCZZBNZDYDYQZJYJGMCTXLTGXSZLML" + +"HBGLKFWNWZHDXUHLFMKYSLGXDTWWFRJEJZTZHYDXYKSHWFZCQSHKTMQQHTZHYMJDJSKHXZJZBZZXYMPAGQMSTPXLSKLZYNWRTSQLSZBPSPSGZWYHT" + +"LKSSSWHZZLYYTNXJGMJSZSUFWNLSOZTXGXLSAMMLBWLDSZYLAKQCQCTMYCFJBSLXCLZZCLXXKSBZQCLHJPSQPLSXXCKSLNHPSFQQYTXYJZLQLDXZQ" + +"JZDYYDJNZPTUZDSKJFSLJHYLZSQZLBTXYDGTQFDBYAZXDZHZJNHHQBYKNXJJQCZMLLJZKSPLDYCLBBLXKLELXJLBQYCXJXGCNLCQPLZLZYJTZLJGY" + +"ZDZPLTQCSXFDMNYCXGBTJDCZNBGBQYQJWGKFHTNPYQZQGBKPBBYZMTJDYTBLSQMPSXTBNPDXKLEMYYCJYNZCTLDYKZZXDDXHQSHDGMZSJYCCTAYRZ" + +"LPYLTLKXSLZCGGEXCLFXLKJRTLQJAQZNCMBYDKKCXGLCZJZXJHPTDJJMZQYKQSECQZDSHHADMLZFMMZBGNTJNNLGBYJBRBTMLBYJDZXLCJLPLDLPC" + +"QDHLXZLYCBLCXZZJADJLNZMMSSSMYBHBSQKBHRSXXJMXSDZNZPXLGBRHWGGFCXGMSKLLTSJYYCQLTSKYWYYHYWXBXQYWPYWYKQLSQPTNTKHQCWDQK" + +"TWPXXHCPTHTWUMSSYHBWCRWXHJMKMZNGWTMLKFGHKJYLSYYCXWHYECLQHKQHTTQKHFZLDXQWYZYYDESBPKYRZPJFYYZJCEQDZZDLATZBBFJLLCXDL" + +"MJSSXEGYGSJQXCWBXSSZPDYZCXDNYXPPZYDLYJCZPLTXLSXYZYRXCYYYDYLWWNZSAHJSYQYHGYWWAXTJZDAXYSRLTDPSSYYFNEJDXYZHLXLLLZQZS" + +"JNYQYQQXYJGHZGZCYJCHZLYCDSHWSHJZYJXCLLNXZJJYYXNFXMWFPYLCYLLABWDDHWDXJMCXZTZPMLQZHSFHZYNZTLLDYWLSLXHYMMYLMBWWKYXYA" + +"DTXYLLDJPYBPWUXJMWMLLSAFDLLYFLBHHHBQQLTZJCQJLDJTFFKMMMBYTHYGDCQRDDWRQJXNBYSNWZDBYYTBJHPYBYTTJXAAHGQDQTMYSTQXKBTZP" + +"KJLZRBEQQSSMJJBDJOTGTBXPGBKTLHQXJJJCTHXQDWJLWRFWQGWSHCKRYSWGFTGYGBXSDWDWRFHWYTJJXXXJYZYSLPYYYPAYXHYDQKXSHXYXGSKQH" + +"YWFDDDPPLCJLQQEEWXKSYYKDYPLTJTHKJLTCYYHHJTTPLTZZCDLTHQKZXQYSTEEYWYYZYXXYYSTTJKLLPZMCYHQGXYHSRMBXPLLNQYDQHXSXXWGDQ" + +"BSHYLLPJJJTHYJKYPPTHYYKTYEZYENMDSHLCRPQFDGFXZPSFTLJXXJBSWYYSKSFLXLPPLBBBLBSFXFYZBSJSSYLPBBFFFFSSCJDSTZSXZRYYSYFFS" + +"YZYZBJTBCTSBSDHRTJJBYTCXYJEYLXCBNEBJDSYXYKGSJZBXBYTFZWGENYHHTHZHHXFWGCSTBGXKLSXYWMTMBYXJSTZSCDYQRCYTWXZFHMYMCXLZN" + +"SDJTTTXRYCFYJSBSDYERXJLJXBBDEYNJGHXGCKGSCYMBLXJMSZNSKGXFBNBPTHFJAAFXYXFPXMYPQDTZCXZZPXRSYWZDLYBBKTYQPQJPZYPZJZNJP" + +"ZJLZZFYSBTTSLMPTZRTDXQSJEHBZYLZDHLJSQMLHTXTJECXSLZZSPKTLZKQQYFSYGYWPCPQFHQHYTQXZKRSGTTSQCZLPTXCDYYZXSQZSLXLZMYCPC" + +"QBZYXHBSXLZDLTCDXTYLZJYYZPZYZLTXJSJXHLPMYTXCQRBLZSSFJZZTNJYTXMYJHLHPPLCYXQJQQKZZSCPZKSWALQSBLCCZJSXGWWWYGYKTJBBZT" + +"DKHXHKGTGPBKQYSLPXPJCKBMLLXDZSTBKLGGQKQLSBKKTFXRMDKBFTPZFRTBBRFERQGXYJPZSSTLBZTPSZQZSJDHLJQLZBPMSMMSXLQQNHKNBLRDD" + +"NXXDHDDJCYYGYLXGZLXSYGMQQGKHBPMXYXLYTQWLWGCPBMQXCYZYDRJBHTDJYHQSHTMJSBYPLWHLZFFNYPMHXXHPLTBQPFBJWQDBYGPNZTPFZJGSD" + +"DTQSHZEAWZZYLLTYYBWJKXXGHLFKXDJTMSZSQYNZGGSWQSPHTLSSKMCLZXYSZQZXNCJDQGZDLFNYKLJCJLLZLMZZNHYDSSHTHZZLZZBBHQZWWYCRZ" + +"HLYQQJBEYFXXXWHSRXWQHWPSLMSSKZTTYGYQQWRSLALHMJTQJSMXQBJJZJXZYZKXBYQXBJXSHZTSFJLXMXZXFGHKZSZGGYLCLSARJYHSLLLMZXELG" + +"LXYDJYTLFBHBPNLYZFBBHPTGJKWETZHKJJXZXXGLLJLSTGSHJJYQLQZFKCGNNDJSSZFDBCTWWSEQFHQJBSAQTGYPQLBXBMMYWXGSLZHGLZGQYFLZB" + +"YFZJFRYSFMBYZHQGFWZSYFYJJPHZBYYZFFWODGRLMFTWLBZGYCQXCDJYGZYYYYTYTYDWEGAZYHXJLZYYHLRMGRXXZCLHNELJJTJTPWJYBJJBXJJTJ" + +"TEEKHWSLJPLPSFYZPQQBDLQJJTYYQLYZKDKSQJYYQZLDQTGJQYZJSUCMRYQTHTEJMFCTYHYPKMHYZWJDQFHYYXWSHCTXRLJHQXHCCYYYJLTKTTYTM" + +"XGTCJTZAYYOCZLYLBSZYWJYTSJYHBYSHFJLYGJXXTMZYYLTXXYPZLXYJZYZYYPNHMYMDYYLBLHLSYYQQLLNJJYMSOYQBZGDLYXYLCQYXTSZEGXHZG" + +"LHWBLJHEYXTWQMAKBPQCGYSHHEGQCMWYYWLJYJHYYZLLJJYLHZYHMGSLJLJXCJJYCLYCJPCPZJZJMMYLCQLNQLJQJSXYJMLSZLJQLYCMMHCFMMFPQ" + +"QMFYLQMCFFQMMMMHMZNFHHJGTTHHKHSLNCHHYQDXTMMQDCYZYXYQMYQYLTDCYYYZAZZCYMZYDLZFFFMMYCQZWZZMABTBYZTDMNZZGGDFTYPCGQYTT" + +"SSFFWFDTZQSSYSTWXJHXYTSXXYLBYQHWWKXHZXWZNNZZJZJJQJCCCHYYXBZXZCYZTLLCQXYNJYCYYCYNZZQYYYEWYCZDCJYCCHYJLBTZYYCQWMPWP" + +"YMLGKDLDLGKQQBGYCHJXY"; +// 375 polyphonic words are included here +let oMultiDiff = { "19969": "DZ", "19975": "WM", "19988": "QJ", "20048": "YL", "20056": "SC", "20060": "NM", + "20094": "QG", "20127": "QJ", "20167": "QC", "20193": "YG", "20250": "KH", "20256": "ZC", "20282": "SC", + "20285": "QJG", "20291": "TD", "20314": "YD", "20340": "NE", "20375": "TD", "20389": "YJ", "20391": "CZ", + "20415": "PB", "20446": "YS", "20447": "SQ", "20504": "TC", "20608": "KG", "20854": "QJ", "20857": "ZC", + "20911": "PF", "20985": "AW", "21032": "PB", "21048": "XQ", "21049": "SC", "21089": "YS", "21119": "JC", + "21242": "SB", "21273": "SC", "21305": "YP", "21306": "QO", "21330": "ZC", "21333": "SDC", "21345": "QK", + "21378": "CA", "21397": "SC", "21414": "XS", "21442": "SC", "21477": "JG", "21480": "TD", "21484": "ZS", + "21494": "YX", "21505": "YX", "21512": "HG", "21523": "XH", "21537": "PB", "21542": "PF", "21549": "KH", + "21571": "E", "21574": "DA", "21588": "TD", "21589": "O", "21618": "ZC", "21621": "KHA", "21632": "ZJ", + "21654": "KG", "21679": "LKG", "21683": "KH", "21710": "A", "21719": "YH", "21734": "WOE", "21769": "A", + "21780": "WN", "21804": "XH", "21834": "A", "21899": "ZD", "21903": "RN", "21908": "WO", "21939": "ZC", + "21956": "SA", "21964": "YA", "21970": "TD", "22003": "A", "22031": "JG", "22040": "XS", "22060": "ZC", + "22066": "ZC", "22079": "MH", "22129": "XJ", "22179": "XA", "22237": "NJ", "22244": "TD", "22280": "JQ", + "22300": "YH", "22313": "XW", "22331": "YQ", "22343": "YJ", "22351": "PH", "22395": "DC", "22412": "TD", + "22484": "PB", "22500": "PB", "22534": "ZD", "22549": "DH", "22561": "PB", "22612": "TD", "22771": "KQ", + "22831": "HB", "22841": "JG", "22855": "QJ", "22865": "XQ", "23013": "ML", "23081": "WM", "23487": "SX", + "23558": "QJ", "23561": "YW", "23586": "YW", "23614": "YW", "23615": "SN", "23631": "PB", "23646": "ZS", + "23663": "ZT", "23673": "YG", "23762": "TD", "23769": "ZS", "23780": "QJ", "23884": "QK", "24055": "XH", + "24113": "DC", "24162": "ZC", "24191": "GA", "24273": "QJ", "24324": "NL", "24377": "TD", "24378": "QJ", + "24439": "PF", "24554": "ZS", "24683": "TD", "24694": "WE", "24733": "LK", "24925": "TN", "25094": "ZG", + "25100": "XQ", "25103": "XH", "25153": "PB", "25170": "PB", "25179": "KG", "25203": "PB", "25240": "ZS", + "25282": "FB", "25303": "NA", "25324": "KG", "25341": "ZY", "25373": "WZ", "25375": "XJ", "25384": "A", + "25457": "A", "25528": "SD", "25530": "SC", "25552": "TD", "25774": "ZC", "25874": "ZC", "26044": "YW", + "26080": "WM", "26292": "PB", "26333": "PB", "26355": "ZY", "26366": "CZ", "26397": "ZC", "26399": "QJ", + "26415": "ZS", "26451": "SB", "26526": "ZC", "26552": "JG", "26561": "TD", "26588": "JG", "26597": "CZ", + "26629": "ZS", "26638": "YL", "26646": "XQ", "26653": "KG", "26657": "XJ", "26727": "HG", "26894": "ZC", + "26937": "ZS", "26946": "ZC", "26999": "KJ", "27099": "KJ", "27449": "YQ", "27481": "XS", "27542": "ZS", + "27663": "ZS", "27748": "TS", "27784": "SC", "27788": "ZD", "27795": "TD", "27812": "O", "27850": "PB", + "27852": "MB", "27895": "SL", "27898": "PL", "27973": "QJ", "27981": "KH", "27986": "HX", "27994": "XJ", + "28044": "YC", "28065": "WG", "28177": "SM", "28267": "QJ", "28291": "KH", "28337": "ZQ", "28463": "TL", + "28548": "DC", "28601": "TD", "28689": "PB", "28805": "JG", "28820": "QG", "28846": "PB", "28952": "TD", + "28975": "ZC", "29100": "A", "29325": "QJ", "29575": "SL", "29602": "FB", "30010": "TD", "30044": "CX", + "30058": "PF", "30091": "YSP", "30111": "YN", "30229": "XJ", "30427": "SC", "30465": "SX", "30631": "YQ", + "30655": "QJ", "30684": "QJG", "30707": "SD", "30729": "XH", "30796": "LG", "30917": "PB", "31074": "NM", + "31085": "JZ", "31109": "SC", "31181": "ZC", "31192": "MLB", "31293": "JQ", "31400": "YX", "31584": "YJ", + "31896": "ZN", "31909": "ZY", "31995": "XJ", "32321": "PF", "32327": "ZY", "32418": "HG", "32420": "XQ", + "32421": "HG", "32438": "LG", "32473": "GJ", "32488": "TD", "32521": "QJ", "32527": "PB", "32562": "ZSQ", + "32564": "JZ", "32735": "ZD", "32793": "PB", "33071": "PF", "33098": "XL", "33100": "YA", "33152": "PB", + "33261": "CX", "33324": "BP", "33333": "TD", "33406": "YA", "33426": "WM", "33432": "PB", "33445": "JG", + "33486": "ZN", "33493": "TS", "33507": "QJ", "33540": "QJ", "33544": "ZC", "33564": "XQ", "33617": "YT", + "33632": "QJ", "33636": "XH", "33637": "YX", "33694": "WG", "33705": "PF", "33728": "YW", "33882": "SR", + "34067": "WM", "34074": "YW", "34121": "QJ", "34255": "ZC", "34259": "XL", "34425": "JH", "34430": "XH", + "34485": "KH", "34503": "YS", "34532": "HG", "34552": "XS", "34558": "YE", "34593": "ZL", "34660": "YQ", + "34892": "XH", "34928": "SC", "34999": "QJ", "35048": "PB", "35059": "SC", "35098": "ZC", "35203": "TQ", + "35265": "JX", "35299": "JX", "35782": "SZ", "35828": "YS", "35830": "E", "35843": "TD", "35895": "YG", + "35977": "MH", "36158": "JG", "36228": "QJ", "36426": "XQ", "36466": "DC", "36710": "JC", "36711": "ZYG", + "36767": "PB", "36866": "SK", "36951": "YW", "37034": "YX", "37063": "XH", "37218": "ZC", "37325": "ZC", + "38063": "PB", "38079": "TD", "38085": "QY", "38107": "DC", "38116": "TD", "38123": "YD", "38224": "HG", + "38241": "XTC", "38271": "ZC", "38415": "YE", "38426": "KH", "38461": "YD", "38463": "AE", "38466": "PB", + "38477": "XJ", "38518": "YT", "38551": "WK", "38585": "ZC", "38704": "XS", "38739": "LJ", "38761": "GJ", + "38808": "SQ", "39048": "JG", "39049": "XJ", "39052": "HG", "39076": "CZ", "39271": "XT", "39534": "TD", + "39552": "TD", "39584": "PB", "39647": "SB", "39730": "LG", "39748": "TPB", "40109": "ZQ", "40479": "ND", + "40516": "HG", "40536": "HG", "40583": "QJ", "40765": "YQ", "40784": "QJ", "40840": "YK", "40863": "QJG" }; + +// Program that returns the first letter array of Chinese characters +export function makePy(str) { + if (typeof(str) != "string") + throw new Error("函数makePy需要字符串类型参数!"); + var arrResult = []; + // Convert string to array + for (var i = 0, len = str.length; i < len; i++) { + var ch = str.charAt(i); + arrResult.push(checkCh(ch)); + } + return mkRslt(arrResult); +} + +// Check processing Chinese characters +function checkCh(ch) { + var uni = ch.charCodeAt(Constants.CHAR_CODE); + // If it is not within the scope of Chinese character processing, return the original character, and you can also call your own processing function + if (uni > Constants.UNI_MAX || uni < Constants.UNI_MIN) + return ch; //dealWithOthers(ch); + // Check whether it is a polyphonic word, it is processed as a polyphonic word, if not, just find the corresponding first letter in the strChineseFirstPY string. + return (oMultiDiff[uni] ? oMultiDiff[uni] : (strChineseFirstPY.charAt(uni - Constants.UNI_MIN))); +} + +// Process the characters and return an array of letters +function mkRslt(arr) { + var arrRslt = [""]; + for (var i = 0, len = arr.length; i < len; i++) { + var str = arr[i]; + var strlen = str.length; + if (strlen == 1) { + for (var k = 0; k < arrRslt.length; k++) { + arrRslt[k] += str; + } + } else { + var tmpArr = arrRslt.slice(0); + arrRslt = []; + for (k = 0; k < strlen; k++) { + // Copy an identical arrRslt + var tmp = tmpArr.slice(0); + // Add the current character str[k] to the end of each element + for (var j = 0; j < tmp.length; j++) { + tmp[j] += str.charAt(k); + } + // Concatenate the copied and modified array to arrRslt + arrRslt = arrRslt.concat(tmp); + } + } + } + return arrRslt; +} + +/** + * Get the corresponding permission group id according to the permission + * @param {String} permission app name id + * @return {Number} groupId + */ +export function getPermissionGroup(permission: string) { + for (var i = 0; i < permissionGroups.length; i++) { + if (permissionGroups[i].permissionName == permission) { + if(permissionGroups[i].groupName == 'OTHER') { + return { + "name": permissionGroups[i].groupName, + "groupName": permissionGroups[i].label, + "label": permissionGroups[i].text, + "icon": permissionGroups[i].icon, + "description": '', + "permissions": [ + permissionGroups[i].permissionName + ] + } + }else { + return groups[permissionGroups[i].groupId] + } + } + } +} + +const TAG = 'PermissionManager_Log'; + +export class Log { + static info(log) { + console.info(`Info: ${TAG} ${log}`) + } + + static error(log) { + console.error(`Error: ${TAG} ${log}`) + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-secondary.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-secondary.ets new file mode 100644 index 000000000..6ff3deb72 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-secondary.ets @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import router from '@system.router'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { groups } from "../common/model/permissionGroup"; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +const allowedStatus = 0; // Status: Allowed +const bannedStatus = 1; // Status: Banned + +class AllowedObj { + groupName: string; + permission: string[]; + constructor(groupName: string, permission: string[]) { + this.groupName = groupName; + this.permission = permission; + } +} // Class Allowed +class BannedObj { + groupName: string; + permission: string[]; + constructor(groupName: string, permission: string[]) { + this.groupName = groupName; + this.permission = permission; + } +} // Class Banned + +@Entry +@Component +struct appNamePlusPage { + @State allowedListItem: AllowedObj[] = []; // Array of allowed permissions + @State bannedListItem: BannedObj[] = []; // array of forbidden permissions + private routerData = router.getParams().routerData; // Routing jump data + + @Builder ListItemLayout(item, index, status) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Text(item.groupName) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.text_color')) + .fontWeight(FontWeight.Medium) + .flexGrow(Constants.FLEX_GROW) + Image($r('app.media.rightarrow')) + .objectFit(ImageFit.Contain) + .height(Constants.IMAGE_HEIGHT) + .width(Constants.IMAGE_WIDTH) + } + .width(Constants.FULL_WIDTH) + .height(Constants.LISTITEM_ROW_HEIGHT) + } + if (!index) { + Row() { + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .width(Constants.FULL_WIDTH) + .height(Constants.TEXT_DECORATION_HEIGHT) + } + } + }.onClick(() => { + if (status === 'allow') { + if (item.groupName == "其他权限") { + router.push({ + uri: 'pages/other-permissions', + params: { + routerData: this.routerData.bundleName, + backTitle: item.groupName, + permission: item.permission, + status: allowedStatus, + tokenId: this.routerData.tokenId + } + }); + } else { + router.push({ + uri: 'pages/application-tertiary', + params: { + routerData: this.routerData.bundleName, + backTitle: item.groupName, + permission: item.permission, + status: allowedStatus + } + }); + } + } + else if (status === 'banned') { + if (item.groupName == "其他权限") { + router.push({ + uri: 'pages/other-permissions', + params: { + routerData: this.routerData.bundleName, + backTitle: item.groupName, + permission: item.permission, + status: bannedStatus, + tokenId: this.routerData.tokenId + } + }); + } else { + router.push({ + uri: 'pages/application-tertiary', + params: { + routerData: this.routerData.bundleName, + backTitle: item.groupName, + permission: item.permission, + status: bannedStatus + } + }); + } + } + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + /** + * Initialize permission status information and group permission information + */ + async initialPermissions() { + var reqPermissions = this.routerData.permissions; + var reqGroupIds = this.routerData.groupId; + + if (!reqGroupIds.length) { + this.allowedListItem = []; + this.bannedListItem = []; + return; + } + + for (let i = 0; i < reqGroupIds.length; i++) { + let id = reqGroupIds[i]; + let groupName = groups[id].groupName; + let groupReqPermissons = []; + for (let j = 0; j < reqPermissions.length; j++) { + let permission = reqPermissions[j]; + if (groups[id].permissions.indexOf(permission) != -1) { + groupReqPermissons.push(permission) + } + } + let isGranted = true; + for (let i = 0; i < groupReqPermissons.length; i++) { + let permission = groupReqPermissons[i] + let res = await abilityAccessCtrl.createAtManager().verifyAccessToken( + this.routerData.tokenId, permission); + if (res != 0) { + isGranted = false; + } + } + + if (isGranted) { + this.allowedListItem.push(new AllowedObj(groupName, groupReqPermissons)); + } else { + this.bannedListItem.push(new BannedObj(groupName, groupReqPermissons)); + } + } + } + + /** + * Lifecycle function, triggered once when this page is displayed + */ + onPageShow() { + console.log(TAG + 'onPageShow application-secondary') + this.initialPermissions(); + } + + /** + * Lifecycle function, triggered once when this page disappears + */ + onPageHide() { + console.log(TAG + 'onPageHide application-secondary') + setTimeout(()=> { + this.allowedListItem = []; + this.bannedListItem = []; + }, Constants.DELAY_TIME) + } + + build() { + Column(){ + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row({}) { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(this.routerData.labelId), recordable: false }) + } + Row() { + Column() { + if (!this.allowedListItem.length && !this.bannedListItem.length) { + Row() { + List() { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Text($r('app.string.no_permission')) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.text_color')) + }.margin({ top: Constants.FLEX_MARGIN_TOP, bottom: Constants.FLEX_MARGIN_BOTTOM }) + }.height(Constants.FULL_HEIGHT) + }.flexGrow(Constants.FLEX_GROW) + .constraintSize({minHeight: Constants.CONSTRAINTSIZE_MINHEIGHT }) + } + .width(Constants.FULL_WIDTH) + .height(Constants.LISTITEM_ROW_HEIGHT) + } + } + } + }.padding({ left: Constants.LISTITEM_PADDING_LEFT, right: Constants.LISTITEM_PADDING_RIGHT }) + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.ROW_MARGIN_TOP }) + .padding({ left: Constants.SECONDARY_LIST_PADDING_LEFT, right: Constants.SECONDARY_LIST_PADDING_RIGHT }) + } else { + Scroll() { + List() { + if (this.allowedListItem.length) { + ListItem() { + Row() { + Text($r('app.string.allowed')) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .fontWeight(FontWeight.Medium) + .lineHeight(Constants.SUBTITLE_LINE_HEIGHT) + }.constraintSize({ minHeight: Constants.SUBTITLE_MIN_HEIGHT }) + .padding({ top: Constants.SUBTITLE_PADDING_TOP, bottom: Constants.SUBTITLE_PADDING_BOTTOM, + left: Constants.SECONDARY_TEXT_MARGIN_LEFT}) + } + + ListItem() { + Row() { + List() { + ForEach(this.allowedListItem.slice(Constants.SLICE_START, this.allowedListItem.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX, 'allow') + }, item => item.toString()) + ForEach(this.allowedListItem.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX, 'allow') + }, item => item.toString()) + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.ROW_MARGIN_TOP }) + .padding({ + left: Constants.SECONDARY_LIST_PADDING_LEFT, + right: Constants.SECONDARY_LIST_PADDING_RIGHT + }) + } + } + if (this.bannedListItem.length) { + ListItem() { + Row() { + Text($r('app.string.banned')) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .fontWeight(FontWeight.Medium) + .lineHeight(Constants.SUBTITLE_LINE_HEIGHT) + }.constraintSize({ minHeight: Constants.SUBTITLE_MIN_HEIGHT }) + .padding({ top: Constants.SUBTITLE_PADDING_TOP, bottom: Constants.SUBTITLE_PADDING_BOTTOM, + left: Constants.SECONDARY_TEXT_MARGIN_LEFT}) + } + + ListItem() { + Row() { + List() { + ForEach(this.bannedListItem.slice(Constants.SLICE_START, this.bannedListItem.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX, 'banned') + }, item => item.toString()) + ForEach(this.bannedListItem.slice(Constants.SLICE_END), (item) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX, 'banned') + }, item => item.toString()) + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.ROW_MARGIN_TOP }) + .padding({ + left: Constants.SECONDARY_LIST_PADDING_LEFT, + right: Constants.SECONDARY_LIST_PADDING_RIGHT + }) + } + } + } + }.scrollBar(BarState.Off) + } + } + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-tertiary.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-tertiary.ets new file mode 100644 index 000000000..e4d4e0c52 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/application-tertiary.ets @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import router from '@system.router'; +import bundle from "@ohos.bundle"; +import { getAppLabel, getAppIcon, verifyAccessToken } from "../common/utils/utils"; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import Resmgr from '@ohos.resourceManager' +import { authorizeDialog } from "../common/components/dialog"; +import { permissionDescriptions, permissionGroups, showSubpermissionsGrop } from "../common/model/permissionGroup"; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +let routerData = router.getParams().routerData; // Routing jump data +let backTitle = router.getParams().backTitle; // return title name +let status = router.getParams().status; // Status: Allowed, Forbidden +let permissions = router.getParams().permission; // permissions name +let nowGrantResult = Constants.PERMISSION_NUM; // Authorization results now +let nowRevokeResult = Constants.PERMISSION_NUM; // Now deauthorize results +let GrantResultFlag = []; // Authorization result Flag +let RevokeResultFlag = []; // Cancel authorization result Flag +let reason = null // Authorized reason +class MeidaDocObj { + name: string + index: number + groupName: string + accessTokenId: string + permissions: [] + constructor( + name: string, + index: number, + groupName: string, + accessTokenId: string, + permissions: [] + ) { + this.name = name + this.index = index + this.groupName = groupName + this.accessTokenId = accessTokenId + this.permissions = permissions + } +}; // permission information class +class MediaListObj { + labelId: string + iconId: string + versionName: string + description: string + constructor( + labelId: string, + iconId: string, + versionName: string, + description: string + ) { + this.labelId = labelId + this.iconId = iconId + this.versionName = versionName + this.description = description + } +}; // Permission application information class + +@Entry +@Component +struct mediaDocumentPage { + build() { + Column() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(backTitle), recordable: false }) + } + Row() { + Column() { + mediaDocumentItem() + }.width(Constants.FULL_WIDTH) + } + .margin({ top: Constants.TITLE_MARGIN_BOTTOM }) + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } + } +} + +@Component +struct mediaDocumentItem { + @State mediaDocListItem: MeidaDocObj[] = []; // Permission information array + @State mediaListItem: MediaListObj = { + labelId: '', + iconId: '', + versionName: '', + description: '' + }; // application info array + @State isCheckList: boolean[] = []; // Permission status array + + authorizeDialogController: CustomDialogController = new CustomDialogController({ + builder: authorizeDialog({ }), + autoCancel: true, + alignment: DialogAlignment.Center + }); + + /** + * Grant permissions to the app + * @param {Number} accessTokenId + * @param {String} permission permission name + */ + grantUserGrantedPermission(accessTokenId, permission) { + abilityAccessCtrl.createAtManager().grantUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then((result) => { + nowGrantResult = result; + }) + .catch((error) => { + console.error(TAG + 'grantUserGrantedPermission failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Deauthorize the app + * @param {Number} accessTokenId + * @param {String} permission permission name + */ + revokeUserGrantedPermission(accessTokenId, permission) { + abilityAccessCtrl.createAtManager().revokeUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then((result) => { + nowRevokeResult = result; + }) + .catch((error) => { + console.error(TAG + 'revokeUserGrantedPermission failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Lifecycle function, executed when the page is initialized + */ + aboutToAppear() { + let permissionDescription = permissionDescriptions[backTitle]; + if(showSubpermissionsGrop.indexOf(backTitle) != -1) { + reason = [] + permissions.forEach(permission => { + permissionGroups.forEach(permissionGroup => { + if(permissionGroup.permissionName == permission) { + reason.push(permissionGroup.label) + } + }) + }) + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + Promise.all([item.getString($r("app.string.separator").id), + item.getString($r("app.string.reason_suffix").id)]) + .then(values => { + reason = reason.join(values[0]) + reason += values[1] + }) + }) + }else { + reason = '' + } + let hasReason = false + bundle.getBundleInfo(routerData, Constants.PARMETER_BUNDLE_FLAG).then(res => { + permissions.forEach(permission => { + res.reqPermissionDetails.forEach(reqPermissionDetail => { + if(reqPermissionDetail.name == permission) { + Resmgr.getResourceManager(globalThis.context, routerData).then(item => { + item.getString(reqPermissionDetail.reasonId, (err, value) => { + if (value !== undefined && !hasReason) { + reason += value.slice(Constants.START_SUBSCRIPT, Constants.END_SUBSCRIPT) + hasReason = true + } + }) + }) + } + }) + }) + Promise.all([getAppLabel(res.appInfo.labelId, res.name), + getAppIcon(res.appInfo.iconId, res.name)]) + .then((values) => { + this.mediaListItem = new MediaListObj( + String(values[0]), String(values[1]), res.versionName, permissionDescription); + }) + this.mediaDocListItem.push( + new MeidaDocObj( + Constants.RADIO_ALLOW_NAME, + Constants.RADIO_ALLOW_INDEX, + Constants.RADIO_ALLOW_GROUP_NAME, + res.appInfo.accessTokenId, + permissions + ) + ); + this.mediaDocListItem.push( + new MeidaDocObj( + Constants.RADIO_BAN_NAME, + Constants.RADIO_BAN_INDEX, + Constants.RADIO_BAN_GROUP_NAME, + res.appInfo.accessTokenId, + permissions + ) + ); + }).catch((error) => { + console.error(TAG + 'bundle.getBundleInfo failed. Cause: ' + JSON.stringify(error)); + this.mediaListItem = new MediaListObj('', '', '', permissionDescription); + this.mediaDocListItem.push( + new MeidaDocObj(Constants.RADIO_ALLOW_NAME, Constants.RADIO_ALLOW_INDEX, + Constants.RADIO_ALLOW_GROUP_NAME, '', permissions) + ); + this.mediaDocListItem.push( + new MeidaDocObj(Constants.RADIO_BAN_NAME, Constants.RADIO_BAN_INDEX, + Constants.RADIO_BAN_GROUP_NAME, '', permissions) + ); + }) + // Get permission status + if (!status) { + this.isCheckList = [true, false]; + } else { + this.isCheckList = [false, true]; + } + } + + build(){ + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Image(this.mediaListItem.iconId) + .width(Constants.TERTIARY_IMAGE_WIDTH) + .height(Constants.TERTIARY_IMAGE_HEIGHT) + .margin({ left: Constants.TERTIARY_IMAGE_MARGIN_LEFT, right: Constants.TERTIARY_IMAGE_MARGIN_RIGHT }) + Column() { + Row() { + Text(this.mediaListItem.labelId) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.label_color')) + .fontWeight(FontWeight.Bold) + .textAlign(TextAlign.Start) + } + .width(Constants.TERTIARY_HALF_WIDTH) + .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM }) + Row() { + Text(this.mediaListItem.versionName) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .textAlign(TextAlign.Start) + } + .width(Constants.TERTIARY_HALF_WIDTH) + } + }.margin({ left: Constants.TERTIARY_MARGIN_LEFT }) + } + if(reason) { + Row() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Text(reason) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .textAlign(TextAlign.Start) + }.margin({ left: Constants.TERTIARY_IMAGE_MARGIN_LEFT, right: Constants.TERTIARY_IMAGE_MARGIN_RIGHT }) + } + } + .margin({ top: Constants.TERTIARY_ROW_MARGIN_TOP, left: Constants.TERTIARY_MARGIN_LEFT }) + } + Row() { + Text(backTitle) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .fontWeight(FontWeight.Medium) + .textAlign(TextAlign.Start) + .lineHeight(Constants.SUBTITLE_LINE_HEIGHT) + Text($r('app.string.access_permission')) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .fontWeight(FontWeight.Medium) + .textAlign(TextAlign.Start) + .lineHeight(Constants.SUBTITLE_LINE_HEIGHT) + }.width(Constants.FULL_WIDTH) + .constraintSize({ minHeight: Constants.SUBTITLE_MIN_HEIGHT }) + .padding({ top: Constants.SUBTITLE_PADDING_TOP, bottom: Constants.SUBTITLE_PADDING_BOTTOM, + left: Constants.TERTIARY_TEXT_MARGIN_LEFT, right: Constants.TERTIARY_IMAGE_MARGIN_RIGHT}) + .margin({ top: Constants.TERTIARY_PERMISSION_ROW_MARGIN_TOP }) + Column() { + List() { + ForEach(this.mediaDocListItem, (item) => { + ListItem() { + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Text(item.name) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.label_color')) + .fontWeight(FontWeight.Medium) + .flexGrow(Constants.FLEX_GROW) + if (this.isCheckList[item.index] === true) { + Shape() { + Circle().width(Constants.SHAPE_DIA).height(Constants.SHAPE_DIA) + .fill($r("app.color.shape_allow_color")).offset({ x: 0, y: 0 }) + Circle().width(Constants.SHAPE_ALLOW_DIA).height(Constants.SHAPE_ALLOW_DIA) + .fill($r("app.color.default_background_color")) + .offset({ x: Constants.SHAPE_ALLOW_OFFSET, y: Constants.SHAPE_ALLOW_OFFSET }) + } + } else if (this.isCheckList[item.index] === false) { + Shape() { + Circle().width(Constants.SHAPE_DIA).height(Constants.SHAPE_DIA) + .fill($r("app.color.shape_ban_color")).offset({ x: 0, y: 0 }) + Circle().width(Constants.SHAPE_BAN_DIA).height(Constants.SHAPE_BAN_DIA) + .fill($r("app.color.default_background_color")) + .offset({ x: Constants.SHAPE_BAN_OFFSET, y: Constants.SHAPE_BAN_OFFSET }) + } + } + } + .width(Constants.FULL_WIDTH) + .height(Constants.LISTITEM_ROW_HEIGHT) + .onClick(() => { + item.permissions.forEach((permission) => { + if (!item.index) { + this.grantUserGrantedPermission(item.accessTokenId, permission) + if (nowGrantResult != Constants.PERMISSION_INDEX) { + GrantResultFlag.push(-1) + }else{ + GrantResultFlag.push(0) + } + } else { + this.revokeUserGrantedPermission(item.accessTokenId, permission) + if (nowRevokeResult != Constants.PERMISSION_INDEX) { + RevokeResultFlag.push(-1) + this.authorizeDialogController.open(); + setTimeout(()=> { + this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + }else{ + RevokeResultFlag.push(0) + } + } + }) + if (!item.index) { + if(GrantResultFlag.indexOf(-1) > -1){ + this.authorizeDialogController.open(); + setTimeout(()=> { + this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + }else{ + this.isCheckList = [true, false]; + } + }else{ + if (RevokeResultFlag.indexOf(-1) > -1){ + this.authorizeDialogController.open(); + setTimeout(()=> { + this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + }else{ + this.isCheckList = [false, true]; + } + } + }) + } + } + if (!item.index) { + Row() { + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .width(Constants.FULL_WIDTH) + .height(Constants.TEXT_DECORATION_HEIGHT) + } + } + } + .onClick(() => { + }) + } + .padding({ + left: Constants.DEFAULT_PADDING_START, + right: Constants.DEFAULT_PADDING_END + }) + .margin({ top: Constants.TERTIARY_LISTITEM_MARGIN_TOP }) + }, item => item.toString()) + } + .borderRadius(Constants.BORDER_RADIUS) + .backgroundColor($r('app.color.default_background_color')) + .padding({ + top: Constants.TERTIARY_LIST_PADDING_TOP, bottom: Constants.TERTIARY_LIST_PADDING_BOTTOM + }) + } + .padding({ + left: Constants.LIST_PADDING_LEFT, + right: Constants.LIST_PADDING_LEFT + }) + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + .width(Constants.FULL_WIDTH) + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-management.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-management.ets new file mode 100644 index 000000000..a1e253562 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-management.ets @@ -0,0 +1,715 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import { alphabetIndexerComponent } from "../common/components/alphabeticalIndex"; +import { textInput } from "../common/components/search"; +import router from '@system.router'; +import bundle from "@ohos.bundle"; +import Resmgr from '@ohos.resourceManager'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { groups, userGrantPermissions, permissionGroupPermissions, noNeedDisplayApp } from "../common/model/permissionGroup"; +import { permissionGroups, permissionPermissionGroup, permissionGroupIds } from "../common/model/permissionGroup"; +import { makePy } from "../common/utils/utils"; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +@Extend(Image) function customizeImage(width: number, height: number) { + .objectFit(ImageFit.Contain) + .width(width) + .height(height) +}; + +interface applicationPermissions { + 'bundleName': string, + 'iconId': string, + 'permissions': string[], + 'labelId': string, + 'tokenId': number, + 'groupId': number[] +}; + +interface permissionApplications { + 'permission': string, + 'groupName': string, + 'bundleNames': string[], + 'icon': string +}; + +interface groupPermission { + 'group': string, + 'permissions': string[], + 'groupName': string, + 'icon': string, + 'isShow':boolean +}; + +let bundleInfosList: any[] = []; // Permission information array +let textInput_placeholder: any = '' + +@Entry +@Component +struct authorityManagementPage { + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(item.icon) + .customizeImage(Constants.MANAGEMENT_IMAGE_WIDTH, Constants.MANAGEMENT_IMAGE_HEIGHT) + .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT }) + Text(item.groupName) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .flexGrow(Constants.FLEX_GROW) + Image($r('app.media.rightarrow')) + .customizeImage(Constants.IMAGE_WIDTH, Constants.IMAGE_HEIGHT) + } + .width(Constants.FULL_WIDTH) + .height(Constants.MANAGEMENT_ROW_HEIGHT) + } + if (!index) { + Row() { + Flex() { + Column().width(Constants.MANAGEMENT_TEXT_DECORATION_MARGIN_LEFT) + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .height(Constants.TEXT_DECORATION_HEIGHT) + .flexGrow(Constants.FLEX_GROW) + } + } + } + }.onClick(() => { + if (item.groupName === '其他权限' || item.groupName === '电话' || item.groupName === '通讯录' || item.groupName === '信息' + || item.groupName === '通话记录' || item.groupName === '日历') { + router.push({ + uri: 'pages/authority-secondary', + params: { routerData: this.allPermissionApplications, backTitle: item.groupName } + }) + } else { + var dataList = this.allPermissionApplications.filter((ele) => { + return ele.groupName === item.group + }) + + router.push({ + uri: 'pages/authority-tertiary-groups', + params: { routerData: dataList, backTitle: item.groupName } + }) + } + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + @State allApplicationPermissions: applicationPermissions[] = []; // All permissions apply + @State allPermissions: string[] = []; // All permissions + @State allSystemPermissions: string[] = []; // All system permissions + @State allUserPermissions: string[] = []; // All user rights + @State allPermissionApplications: permissionApplications [] = [] // All app permissions + @State allGroups: string[] = [] // All groups + @State allGroupPermission: groupPermission[] = [] // All group permissions + @State currentIndex: number = 0 + @Builder TabBuilder(index: number) { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(index ? $r('app.string.application') : $r('app.string.authority')) + .fontColor(this.currentIndex == index ? $r('app.color.button_color') : $r('app.color.label_color')) + .fontWeight(this.currentIndex == index ? FontWeight.Bold : FontWeight.Regular) + .lineHeight(Constants.TEXT_LINE_HEIGHT) + if(this.currentIndex == index) { + Row().width(Constants.FULL_WIDTH).height(Constants.TAB_DECORATION_HEIGHT) + .backgroundColor($r('app.color.button_color')) + .position({ y: Constants.TAB_DECORATION_POSITION_Y }) + } + }.height(Constants.TAB_HEIGHT) + } + + /** + * Convert the permission array into key, value key-value objects for easy sorting + * @param {Array} order User rights + * @return {Object} return the processed object + */ + orderDict(order) { + let result = {}; + for (let i = 0; i < order.length; i++) { + let key = order[i]; + result[key] = i; + } + return result; + } + + /** + * Compare and sort the permission array according to the permission key value + * @param {String} prop Sort by permission + * @param {Object} orderSort objects to be sorted + * @return {Array} Returns a sorted array of permissions + */ + compare(prop, orderSort) { + return function(a, b) { + let aSortValue = orderSort[a[prop]]; + let bSortValue = orderSort[b[prop]]; + if (aSortValue == undefined) { + throw new Error('当前的字段不在排序列表里:' + a[prop]); + } + if (bSortValue == undefined) { + throw new Error('当前的字段不在排序列表里:' + b[prop]); + } + return aSortValue - bSortValue; + } + } + + /** + * Get all app permission information + * @param {Array} allPermissions All permissions + * @param {Object} allApplicationPermissions All app permissions + */ + getAllBundlePermissions(allPermissions: string[], allApplicationPermissions: applicationPermissions[]) { + bundle.getAllBundleInfo(Constants.PARMETER_BUNDLE_FLAG).then(async(res) => { + const bundleInfos = res; + var count = bundleInfos.length; + if (count <= 0) { + console.info(TAG + 'bundle.getAllBundleInfo result.length less than or equal to zero'); + return; + } + var infoIndex = 0; + for (let i = 0; i < count; i++) { + var info = bundleInfos[i]; + // Filter blank icon icon and text label resources + try { + const ret = await bundle.queryAbilityByWant({ + bundleName: info.name, + action: "action.system.home", + entities: ["entity.system.home"] + }, bundle.BundleFlag.GET_ABILITY_INFO_WITH_APPLICATION, Constants.USERID); + } catch(e) { + console.log(TAG + 'queryAbilityByWant catch error: ' + JSON.stringify(e)) + continue; + } + + if (noNeedDisplayApp.indexOf(info.name) != -1) { + continue; + } + await this.deduplicationPermissions(info, allPermissions, allApplicationPermissions); + this.updateAppLabel(infoIndex, info.name, info.appInfo.label); + this.updateAppIcon(infoIndex, info.name); + infoIndex = infoIndex + 1; + } + this.getAllPermissionApplications(); + let orderSort = this.orderDict(userGrantPermissions); + this.allPermissionApplications.sort(this.compare('permission', orderSort)); + this.getAllGroupPermission(); + bundleInfosList = this.allApplicationPermissions; + bundleInfosList.forEach((item) => { + if (!isNaN(item.labelId)) { + item.alphabeticalIndex = ''; + } else { + item.alphabeticalIndex = makePy(item.labelId)[0].slice(0, 1); // Get the first letter in the returned initials array + } + }) + }) + .catch((error) => { + console.error(TAG + 'bundle.getAllBundleInfo failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Get the corresponding permission group id according to the permission + * @param {String} permission app name id + * @return {Number} groupId + */ + getPermissionGroupByPermission(permission: string) { + for (let i = 0; i < permissionGroups.length; i++) { + if (permissionGroups[i].permissionName == permission) { + return groups[permissionGroups[i].groupId]; + } + } + } + + /** + * Get all app permission information + */ + getAllPermissionApplications() { + const this_ = this; + var leng = this_.allPermissions.length; + if (leng > 0) { + for (let i = 0; i < leng; i++) { + if (userGrantPermissions.indexOf(this_.allPermissions[i]) == -1) { + this_.allSystemPermissions.push(this_.allPermissions[i]); + } else { + this_.allUserPermissions.push(this_.allPermissions[i]); + } + } + } + for (let i = 0; i < this_.allUserPermissions.length; i++) { + var permissionGroup = this_.getPermissionGroupByPermission(this_.allUserPermissions[i]); + var icon: string = permissionGroup.icon; + var bundleNames: string[] = []; + for (let j = 0; j < this_.allApplicationPermissions.length; j++) { + if (this_.allApplicationPermissions[j].permissions.indexOf(this_.allUserPermissions[i]) != -1) { + bundleNames.push(this_.allApplicationPermissions[j].bundleName); + } + } + var pa: permissionApplications = { + 'permission': this_.allUserPermissions[i], + 'groupName': permissionGroup.name, + 'bundleNames': bundleNames, + 'icon': icon + }; + this_.allPermissionApplications.push(pa); + } + } + + /** + * Get permission group information + */ + getAllGroupPermission() { + const this_ = this; + var temp1 = []; + temp1 = ["LOCATION","CAMERA","MICROPHONE","MEDIA","CALENDAR","SPORT","HEALTH"]; + groups.forEach((item) => { + if (temp1.indexOf(item.name) > -1) { + var gp: groupPermission = { + "group": item.name, + "permissions": item.permissions, + 'groupName': item.groupName, + 'icon': item.icon, + 'isShow': item.isShow + }; + this_.allGroupPermission.push(gp); + } + }) + let temp2 = []; + groups.forEach((item) => { + if (item.isShow && temp1.indexOf(item.name) === -1) { + var gp: groupPermission = { + "group": item.name, + "permissions": item.permissions, + 'groupName': item.groupName, + 'icon': item.icon, + 'isShow': item.isShow + }; + temp2.push(item.name); + this_.allGroupPermission.push(gp); + } + }) + for (let i = 0; i < this_.allPermissionApplications.length; i++) { + if (this_.allGroups.indexOf(this_.allPermissionApplications[i].groupName) == -1 + && temp1.indexOf(this_.allPermissionApplications[i].groupName) == -1) { + this_.allGroups.push(this_.allPermissionApplications[i].groupName); + } + } + // Permission layout + var temp = this_.allGroups; + temp = temp.filter(function(item) { + return temp1.indexOf(item) == -1 && temp2.indexOf(item) == -1; + }); + if (temp.indexOf("OTHER") > -1) { + temp.splice(temp.indexOf("OTHER"),1); + temp.push("OTHER"); + }else { + temp.push("OTHER"); + } + this_.allGroups = temp; + for (let i = 0; i < this_.allGroups.length; i++) { + var permissions: string[] = permissionGroupPermissions[this_.allGroups[i]]; + var gp: groupPermission = { + "group": this_.allGroups[i], + "permissions": permissions, + 'groupName': '', + 'icon': '', + 'isShow': false + }; + this_.allGroupPermission.push(gp); + } + this.allGroupPermission.forEach((ele) => { + groups.forEach((item) => { + if (ele.group === item.name) { + ele.groupName = item.groupName; + ele.icon = item.icon; + ele.isShow = item.isShow; + } + }); + }) + } + + /** + * Deduplicate permission information and permission group information + * @param {Object} info bundleInfos Application Information + * @param {Array} allPermissions All permissions + * @param {Array} allApplicationPermissions All permissions apply + */ + async deduplicationPermissions(info, allPermissions, allApplicationPermissions) { + var reqPermissionsLen = info.reqPermissions.length; + var reqUserPermissions: string[] = []; + var acManager = abilityAccessCtrl.createAtManager() + if (reqPermissionsLen > 0) { + for (let j = 0; j < info.reqPermissions.length; j++) { + var permission = info.reqPermissions[j]; + var flag = await acManager.getPermissionFlags(info.appInfo.accessTokenId, permission) + if(flag == Constants.PRE_AUTHORIZATION_NOT_MODIFIED) { + continue + } + if (allPermissions.indexOf(permission) == -1) { + allPermissions.push(permission); + } + if (userGrantPermissions.indexOf(permission) != -1) { + reqUserPermissions.push(permission); + } + } + } + let dePermissions = []; + let groupIds = []; + for (let i = 0; i < reqUserPermissions.length; i++) { + if(dePermissions.indexOf(permissionPermissionGroup[reqUserPermissions[i]]) == -1){ + dePermissions.push(permissionPermissionGroup[reqUserPermissions[i]]); + } + if(groupIds.indexOf(permissionGroupIds[reqUserPermissions[i]]) == -1){ + groupIds.push(permissionGroupIds[reqUserPermissions[i]]); + } + } + + // adapt different api + if (info.compatibleVersion >= Constants.API_VERSION_SUPPORT_STAGE) { + info.appInfo.iconId = info.hapModuleInfos[0].abilityInfo[0].iconId; + } + + var ap: applicationPermissions = { + 'bundleName': info.name, + 'tokenId': info.appInfo.accessTokenId, + 'iconId': info.appInfo.iconId, + 'labelId': info.appInfo.labelId, + 'permissions': reqUserPermissions, + 'groupId': groupIds + }; + allApplicationPermissions.push(ap); + } + + /** + * Get app name resource + * @param {Number} index index of all app permissions array + * @param {String} bundleName Package names + * @param {String} labelName Application Name + */ + updateAppLabel(index, bundleName, labelName) { + Resmgr.getResourceManager(globalThis.context, bundleName).then(item => { + if (index >= this.allApplicationPermissions.length) { + return; + } + var info = this.allApplicationPermissions[index]; + item.getString(info['labelId'], (error, value) => { + if (value == undefined) { + info['labelId'] = labelName; + } else { + info['labelId'] = value; + } + }) + }).catch(error => { + console.error(TAG + 'Resmgr.getResourceManager failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Get app icon resources + * @param {Number} index index of all app permissions array + * @param {String} bundleName Package names + */ + updateAppIcon(index, bundleName) { + Resmgr.getResourceManager(globalThis.context, bundleName).then(item => { + if (index >= this.allApplicationPermissions.length) { + return; + } + var info = this.allApplicationPermissions[index]; + item.getMediaBase64(info['iconId'], (error, value) => { + info['iconId'] = value; + }) + }).catch(error => { + console.error(TAG + 'Resmgr.getResourceManager failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Lifecycle function, executed when the page is initialized + */ + aboutToAppear() { + console.log(TAG + 'on aboutToAppear, version 1.01'); + this.getAllBundlePermissions(this.allPermissions, this.allApplicationPermissions); + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + item.getString($r("app.string.textInput_placeholder").id, (err, val) => { + textInput_placeholder = val + }) + }) + } + + getPermissionGroup(allGroup, order) { + var fixedName: string[] = ['LOCATION', 'CAMERA', 'MICROPHONE'] + var fixedGroup: any[] = [] + var changeGroup: any[] = [] + var otherGroup: any[] = [] + + allGroup.forEach(group => { + if(fixedName.indexOf(group.group) !== -1) { + fixedGroup.push(group) + }else if(group.group == 'OTHER') { + otherGroup.push(group) + }else { + changeGroup.push(group) + } + }) + + if(order == Constants.FIXED_GROUP){ + return fixedGroup + }else if(order == Constants.CHANGE_GROUP) { + return changeGroup + }else if(order == Constants.OTHER_GROUP) { + return otherGroup + } + } + + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar( { title: JSON.stringify($r('app.string.authority_management')), recordable: true }) + } + Row() { + Column() { + Column() { + Stack() { + if(this.allGroupPermission.length) { + Tabs() { + TabContent() { + Row() { + Column() { + Scroll() { + Column() { + List() { + ListItem() { + List() { + ForEach(this.getPermissionGroup(this.allGroupPermission, Constants.FIXED_GROUP).slice(Constants.SLICE_START, + this.getPermissionGroup(this.allGroupPermission, Constants.FIXED_GROUP).length - 1), (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.getPermissionGroup(this.allGroupPermission, Constants.FIXED_GROUP).slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + .margin({ bottom: Constants.LIST_MARGIN_BOTTOM }) + } + + ListItem() { + List() { + ForEach(this.getPermissionGroup(this.allGroupPermission, Constants.CHANGE_GROUP).slice(Constants.SLICE_START, + this.getPermissionGroup(this.allGroupPermission, Constants.CHANGE_GROUP).length - 1), (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.getPermissionGroup(this.allGroupPermission, Constants.CHANGE_GROUP).slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + .margin({ bottom: Constants.LIST_MARGIN_BOTTOM }) + } + + ListItem() { + List() { + ForEach(this.getPermissionGroup(this.allGroupPermission, Constants.OTHER_GROUP), (item) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + } + }.height(Constants.FULL_HEIGHT) + .borderRadius(Constants.BORDER_RADIUS) + .clip(true) + }.padding({ + left: Constants.MANAGEMENT_ROW_PADDING_LEFT, + right: Constants.MANAGEMENT_ROW_PADDING_RIGHT, + }) + }.scrollBar(BarState.Off) + .margin({ top: Constants.MANAGEMENT_ROW_PADDING_TOP }) + }.width(Constants.FULL_WIDTH) + } + }.tabBar(this.TabBuilder(0)) + TabContent() { + applicationItem() + }.tabBar(this.TabBuilder(1)) + } + .barWidth(Constants.BAR_WIDTH) + .barMode(BarMode.Fixed) + .onChange((index) => { + this.currentIndex = index + }) + }else { + LoadingProgress().width(Constants.LOADING_WIDTH) + } + }.height(Constants.FULL_HEIGHT) + } + } + } + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } +} + +@Component +struct applicationItem { + @State applicationItem: any[] = bundleInfosList // application info array + @State oldApplicationItem: any[] = bundleInfosList // Original application information array + @State searchResult: boolean = true // search results + + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(item.iconId) + .customizeImage(Constants.APPLICATION_IMAGE_WIDTH, Constants.APPLICATION_IMAGE_HEIGHT) + .margin({ right: Constants.APPLICATION_IMAGE_MARGIN_RIGHT }) + Text(item.labelId) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .flexGrow(Constants.FLEX_GROW) + Text(item.groupId.length + '项权限') + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_lighter')) + .margin({ right: Constants.APPLICATION_TEXT_MARGIN_RIGHT }) + Image($r('app.media.rightarrow')) + .customizeImage(Constants.IMAGE_WIDTH, Constants.IMAGE_HEIGHT) + } + .width(Constants.FULL_WIDTH) + .height(Constants.AUTHORITY_ROW_HEIGHT) + .constraintSize({ minHeight: Constants.AUTHORITY_CONSTRAINTSIZE_MINHEIGHT }) + } + if (!index) { + Row() { + Flex() { + Column().width(Constants.APPLICATION_TEXT_DECORATION_MARGIN_LEFT) + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .height(Constants.TEXT_DECORATION_HEIGHT) + .flexGrow(Constants.FLEX_GROW) + } + } + } + }.onClick(() => { + router.push({ + uri: 'pages/application-secondary', + params: { routerData: item } + }); + }) + } + }.padding({ + left: Constants.DEFAULT_PADDING_START, + right: Constants.DEFAULT_PADDING_END + }) + } + + build() { + Column() { + Row() { + textInput({ + placeholder: textInput_placeholder, + applicationItem: $applicationItem, + oldApplicationItem: $oldApplicationItem, + searchResult: $searchResult + }) + }.padding({ + left: Constants.APPLICATION_TEXTINPUT_PADDING_LEFT, + top: Constants.APPLICATION_TEXTINPUT_PADDING_TOP, + right: Constants.APPLICATION_TEXTINPUT_PADDING_RIGHT + }) + Row() { + Flex({ alignItems: ItemAlign.Start }) { + Column() { + Column() { + if (!this.applicationItem.length) { + Row() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Image($r('app.media.searchnoresult')) + .customizeImage(Constants.SEARCHNORESULT_IMAGE_WIDTH, Constants.SEARCHNORESULT_IMAGE_HEIGHT) + } + }.margin({ top: Constants.MANAGEMENT_ROW_MARGIN_TOP }) + .padding({ left: Constants.MANAGEMENT_ROW_PADDING_LEFT }) + } else { + Row() { + Scroll() { + List() { + ForEach(this.applicationItem.slice(Constants.SLICE_START, this.applicationItem.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.applicationItem.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.scrollBar(BarState.Off) + }.margin({ left: Constants.MANAGEMENT_ROW_PADDING_LEFT }) + .borderRadius(Constants.BORDER_RADIUS) + .clip(true) + } + }.backgroundColor($r('app.color.background_color')) + .height(Constants.FULL_HEIGHT) + }.margin({ top: Constants.MANAGEMENT_ROW_MARGIN_TOP, bottom: Constants.APPLICATION_LIST_MARGIN_BOTTOM }) + Column() { + alphabetIndexerComponent({ applicationItem: $applicationItem, oldApplicationItem: $oldApplicationItem }) + }.margin({ top: Constants.APPLICATION_ALPHABETINDEX_MARGIN_TOP }) + .width(Constants.APPLICATION_ALPHABETINDEX_WIDTH) + } + } + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-secondary.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-secondary.ets new file mode 100644 index 000000000..21480ad4c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-secondary.ets @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import { permissionGroups, groups } from "../common/model/permissionGroup"; +import router from '@system.router'; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +class CalendarObj { + permissionName: string + groupName: string + description: string + label: string + index: number + constructor(permissionName: string, groupName: string, description: string, label: string, index: number) { + this.permissionName = permissionName + this.groupName = groupName + this.description = description + this.label = label + this.index = index + } +} // Permission management secondary interface data class + +@Entry +@Component +struct appNamePage { + private backTitle = router.getParams().backTitle; // return title name + + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(this.backTitle), recordable: false }) + } + Row() { + Column() { + Scroll() { + appNameItem() + } + } + }.layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } +} + +@Component +struct appNameItem { + @State calendarListItem: CalendarObj[] = []; // Permission management secondary interface data array + private routerData = router.getParams().routerData; // Routing jump data + private backTitle = router.getParams().backTitle; // return title name + private allPermissionApplications = router.getParams().allPermissionApplications; // Array of all app permission names + + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Text(item.label) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.label_color')) + .fontWeight(FontWeight.Medium) + .flexGrow(Constants.FLEX_GROW) + Image($r('app.media.rightarrow')) + .objectFit(ImageFit.Contain) + .height(Constants.IMAGE_HEIGHT) + .width(Constants.IMAGE_WIDTH) + } + .width(Constants.FULL_WIDTH) + .height(Constants.LISTITEM_ROW_HEIGHT) + } + if (!index) { + Row() { + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .width(Constants.FULL_WIDTH) + .height(Constants.TEXT_DECORATION_HEIGHT) + } + } + }.onClick(() => { + var dataList = this.routerData.filter((ele) => { + return ele.groupName === item.groupName; + }) + router.push({ + uri: 'pages/authority-tertiary', + params: { routerData: [dataList[item.index]], backTitle: item.label } + }); + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + /** + * Lifecycle function, executed when the page is initialized + */ + aboutToAppear() { + var permissionsList = groups.filter((item) => { + return item.groupName === this.backTitle + }) + for (let i = 0; i < permissionsList[0].permissions.length; i++) { + permissionGroups.forEach((item) => { + if (item.permissionName === permissionsList[0].permissions[i]) { + this.calendarListItem.push( + new CalendarObj(item.permissionName, item.groupName, item.description, item.label, i) + ) + } + }) + } + } + + build() { + Row() { + Column() { + Row() { + List() { + ForEach(this.calendarListItem.slice(Constants.SLICE_START, this.calendarListItem.length - 1), (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.calendarListItem.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')).borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.ROW_MARGIN_TOP }) + .padding({ left: Constants.LIST_PADDING_LEFT, right: Constants.LISTITEM_PADDING_RIGHT }) + } + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary-groups.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary-groups.ets new file mode 100644 index 000000000..44cd9224d --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary-groups.ets @@ -0,0 +1,403 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import { alphabetIndexerComponent } from "../common/components/alphabeticalIndex"; +import { textInput } from "../common/components/search"; +import router from '@system.router'; +import bundle from "@ohos.bundle"; +import Resmgr from '@ohos.resourceManager'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { getAppLabel, getAppIcon, verifyAccessToken} from "../common/utils/utils"; +import { makePy } from "../common/utils/utils"; +import { authorizeDialog } from "../common/components/dialog"; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +@Extend(Image) function customizeImage(width: number, height: number) { + .objectFit(ImageFit.Contain) + .width(width) + .height(height) +} + +let routerData = router.getParams().routerData; // Routing jump data +let backTitle = router.getParams().backTitle; // return title name +let nowGrantResult = Constants.PERMISSION_NUM; // Authorization results now +let nowRevokeResult = Constants.PERMISSION_NUM; // Now deauthorize results +let GrantResultFlag = []; // Authorization result Flag +let RevokeResultFlag = []; // Cancel authorization result Flag + +class ApplicationObj { + labelId: string + iconId: string + index: number + accessTokenId: number + permission: string + alphabeticalIndex: string + constructor( + labelId: string, + iconId: string, + index: number, + accessTokenId: number, + permission: string, + alphabeticalIndex: string) { + this.labelId = labelId + this.iconId = iconId + this.index = index + this.accessTokenId = accessTokenId + this.permission = permission + this.alphabeticalIndex = alphabeticalIndex + } +} // application information + +@Entry +@Component +struct locationInfoPage { + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(backTitle), recordable: false }) + } + Row() { + Column() { + applicationItem() + + }.width(Constants.FULL_WIDTH) + } + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } +} + +@Component +struct applicationItem { + @State permissionNum: number = Constants.PERMISSION_NUM; // permission num + @State toggleIsOn: object = {}; // toggle switch state array + @State applicationList: ApplicationObj[] = []; // application info array + @State oldApplicationItem: ApplicationObj[] = []; // Original application information array + @State searchResult: boolean = true; // search results + @State placeholder: string = '' + + authorizeDialogController: CustomDialogController = new CustomDialogController({ + builder: authorizeDialog({ }), + autoCancel: true, + alignment: DialogAlignment.Center + }); + + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(item.iconId) + .customizeImage(Constants.AUTHORITY_IMAGE_WIDTH, Constants.AUTHORITY_IMAGE_HEIGHT) + .margin({ right: Constants.AUTHORITY_IMAGE_MARGIN_RIGHT }) + Text(item.labelId) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.text_color')) + .flexGrow(Constants.FLEX_GROW) + Toggle({ type: ToggleType.Switch, isOn: this.toggleIsOn[item.index] }) + .selectedColor($r('app.color.toggle_color')) + .width(Constants.AUTHORITY_TOGGLE_WIDTH) + .height(Constants.AUTHORITY_TOGGLE_HEIGHT) + .onChange((isOn: boolean) => { + if (item.accessTokenId === '' || item.permission === '') { + return; + } + let _this = this; + if (isOn) { + let promises = routerData.map(it => new Promise((resolve, reject) => { + _this.grantUserGrantedPermission(item.accessTokenId, it.permission, item.index, resolve); + })); + Promise.all(promises).then(function(results) { + if(results.indexOf(-1) != -1) { + _this.authorizeDialogController.open(); + _this.toggleIsOn[item.index] = false; + setTimeout(()=> { + _this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + } else { + _this.toggleIsOn[item.index] = true; + } + let num = Constants.PERMISSION_NUM; + for(let key in _this.toggleIsOn){ + if(_this.toggleIsOn[key]){ + num++; + } + } + _this.permissionNum = num; + }); + } else { + let promises = routerData.map(it => new Promise((resolve, reject) => { + _this.revokeUserGrantedPermission(item.accessTokenId, it.permission, item.index, resolve); + })); + Promise.all(promises).then(function(results) { + if(results.indexOf(-1) != -1) { + _this.authorizeDialogController.open(); + _this.toggleIsOn[item.index] = true; + setTimeout(()=> { + _this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + } else { + _this.toggleIsOn[item.index] = false; + } + let num = Constants.PERMISSION_NUM; + for(let key in _this.toggleIsOn){ + if(_this.toggleIsOn[key]){ + num++; + } + } + _this.permissionNum = num; + }); + } + }) + } + .width(Constants.FULL_WIDTH) + .height(Constants.AUTHORITY_ROW_HEIGHT) + .constraintSize({ minHeight: Constants.AUTHORITY_CONSTRAINTSIZE_MINHEIGHT }) + } + if (!index) { + Row() { + Flex() { + Column().width(Constants.APPLICATION_TEXT_DECORATION_MARGIN_LEFT) + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .height(Constants.TEXT_DECORATION_HEIGHT) + .flexGrow(Constants.FLEX_GROW) + } + } + } + }.onClick(() => { + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + /** + * Grant permissions to the app + * @param {Number} accessTokenId + * @param {String} permission permission name + * @param {Number} index Array index to modify permission status + */ + grantUserGrantedPermission(accessTokenId, permission, index, resolve) { + abilityAccessCtrl.createAtManager().grantUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then(result => { + // result: 0 Authorization succeeded; result: -1 Authorization failed + resolve(result); + }).catch(error => { + resolve(-1); + console.error(TAG + 'abilityAccessCtrl.createAtManager.grantUserGrantedPermission failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Deauthorize the app + * @param {Number} accessTokenId + * @param {String} permission permission name + * @param {Number} index Array index to modify permission status + */ + revokeUserGrantedPermission(accessTokenId, permission, index, resolve) { + abilityAccessCtrl.createAtManager().revokeUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then(result => { + // result: 0 successfully cancel the authorization; result: -1 cancel the authorization failed + resolve(result); + }).catch(error => { + resolve(-1); + console.error(TAG + 'abilityAccessCtrl.createAtManager.revokeUserGrantedPermission failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Lifecycle function, executed when the page is initialized + */ + aboutToAppear() { + var bundleNames = [] + routerData.forEach(permissionmanager => { + permissionmanager.bundleNames.forEach( bundleName => { + if (bundleNames.indexOf(bundleName) == -1) { + bundleNames.push(bundleName) + } + }) + }) + + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + item.getString($r("app.string.textInput_placeholder").id, (err, val) => { + this.placeholder = val + }) + }) + + // initial then fill values when sync return which may cause sync panic + for (let i = 0; i < bundleNames.length; i++) { + this.applicationList.push( + new ApplicationObj('', '', i, 0, '', '')); + this.oldApplicationItem.push( + new ApplicationObj('', '', i, 0, '', '')); + } + + for (let i = 0; i < bundleNames.length; i++) { + // Get BundleInfo based on bundle name + bundle.getBundleInfo(bundleNames[i], Constants.PARMETER_BUNDLE_FLAG).then(res => { + Promise.all([getAppLabel(res.appInfo.labelId, res.name), + getAppIcon(res.appInfo.iconId, res.name) + ]) + .then((values) => { + this.applicationList[i] = ( + new ApplicationObj( + String(values[0]), + String(values[1]), + i, + res.appInfo.accessTokenId, + routerData[0].permission, + makePy(values[0])[0].slice(0, 1)) // Get the first letter in the returned initials array + ); + this.oldApplicationItem[i] = ( + new ApplicationObj( + String(values[0]), + String(values[1]), + i, + res.appInfo.accessTokenId, + routerData[0].permission, + makePy(values[0])[0].slice(0, 1)) // Get the first letter in the returned initials array + ); + }); + // 0: have permission; -1: no permission + var boole = true; + this.permissionNum++; + for (let j = 0; j < routerData.length; j++) { + if (res.reqPermissions.indexOf(routerData[j].permission) == -1) { + continue + } + verifyAccessToken(res.appInfo.accessTokenId, routerData[j].permission).then((access) => { + if (Number(access) === Constants.PERMISSION_INDEX) { + if(boole){ + this.toggleIsOn[i] = true; + } + } else { + if(boole){ + this.permissionNum-- + } + boole = false; + this.toggleIsOn[i] = false; + } + }); + } + }).catch(error => { + console.log(TAG + bundleNames[i] + "getBundleInfo failed, cause: " + JSON.stringify(error)); + }) + } + } + + build() { + Column() { + Row() { + textInput({ + placeholder: this.placeholder, + applicationItem: $applicationList, + oldApplicationItem: $oldApplicationItem, + searchResult: $searchResult + }) + }.padding({ + left: Constants.AUTHORITY_TEXTINPUT_PADDING_LEFT, + right: Constants.AUTHORITY_TEXTINPUT_PADDING_RIGHT + }) + Row() { + Flex({ alignItems:ItemAlign.Start, justifyContent: FlexAlign.Start }) { + Column() { + Flex({ justifyContent: FlexAlign.Start }) { + Text(this.permissionNum + '个应用获取此权限') + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.secondary_font_color')) + .margin({ top: Constants.AUTHORITY_TEXT_MARGIN_TOP, left: Constants.AUTHORITY_TEXT_MARGIN_LEFT }) + } + Scroll() { + Row() { + Column() { + if (!this.applicationList.length) { + if (this.searchResult) { + Row() { + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } else { + Row() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Image($r('app.media.searchnoresult')) + .customizeImage(Constants.SEARCHNORESULT_IMAGE_WIDTH, Constants.SEARCHNORESULT_IMAGE_HEIGHT) + } + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } + } else { + Row() { + List() { + ForEach(this.applicationList.slice(Constants.SLICE_START, this.applicationList.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.applicationList.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } + }.width(Constants.FULL_WIDTH) + .height(Constants.AUTHORITY_COLUMN_HEIGHT) + } + } + }.padding({ left: Constants.AUTHORITY_LISTITEM_PADDING_LEFT }) + Column() { + alphabetIndexerComponent({ applicationItem: $applicationList, oldApplicationItem: $oldApplicationItem }) + }.width(Constants.AUTHORITY_ALPHABETINDEX_WIDTH) + .padding({ top: Constants.AUTHORITY_ALPHABETINDEX_PADDING_TOP }) + } + } + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary.ets new file mode 100644 index 000000000..040934f2f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/authority-tertiary.ets @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import { alphabetIndexerComponent } from "../common/components/alphabeticalIndex"; +import { textInput } from "../common/components/search"; +import router from '@system.router'; +import bundle from "@ohos.bundle"; +import Resmgr from '@ohos.resourceManager'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import { getAppLabel, getAppIcon, verifyAccessToken } from "../common/utils/utils"; +import { makePy } from "../common/utils/utils"; +import { authorizeDialog } from "../common/components/dialog"; +import Constants from '../common/utils/constant'; + +var TAG = 'PermissionManager_MainAbility:' + +@Extend(Image) function customizeImage(width: number, height: number) { + .objectFit(ImageFit.Contain) + .width(width) + .height(height) +} + +let routerData = router.getParams().routerData; // Routing jump data +let backTitle = router.getParams().backTitle; // return title name +class ApplicationObj { + labelId: string + iconId: string + index: number + accessTokenId: number + permission: string + alphabeticalIndex: string + constructor( + labelId: string, + iconId: string, + index: number, + accessTokenId: number, + permission: string, + alphabeticalIndex: string) { + this.labelId = labelId + this.iconId = iconId + this.index = index + this.accessTokenId = accessTokenId + this.permission = permission + this.alphabeticalIndex = alphabeticalIndex + } +} // application information + +@Entry +@Component +struct locationInfoPage { + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(backTitle), recordable: false }) + } + Row() { + Column() { + applicationItem() + + }.width(Constants.FULL_WIDTH) + } + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } +} + +@Component +struct applicationItem { + @State permissionNum: number = Constants.PERMISSION_NUM; // permission num + @State toggleIsOn: object = {}; // toggle switch state array + @State applicationList: ApplicationObj[] = []; // application info array + @State oldApplicationItem: ApplicationObj[] = []; // Original application information array + @State searchResult: boolean = true; // search results + @State placeholder: string = '' + + authorizeDialogController: CustomDialogController = new CustomDialogController({ + builder: authorizeDialog({ }), + autoCancel: true, + alignment: DialogAlignment.Center + }); + + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Image(item.iconId) + .customizeImage(Constants.AUTHORITY_IMAGE_WIDTH, Constants.AUTHORITY_IMAGE_HEIGHT) + .margin({ right: Constants.AUTHORITY_IMAGE_MARGIN_RIGHT }) + Text(item.labelId) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .flexGrow(Constants.FLEX_GROW) + Toggle({ type: ToggleType.Switch, isOn: this.toggleIsOn[item.index] }) + .selectedColor($r('app.color.toggle_color')) + .width(Constants.AUTHORITY_TOGGLE_WIDTH) + .height(Constants.AUTHORITY_TOGGLE_HEIGHT) + .onChange((isOn: boolean) => { + if (item.accessTokenId === '' || item.permission === '') { + return; + } + if (isOn) { + this.grantUserGrantedPermission(item.accessTokenId, item.permission, item.index); + } else { + this.revokeUserGrantedPermission(item.accessTokenId, item.permission, item.index); + } + }) + } + .width(Constants.FULL_WIDTH) + .height(Constants.AUTHORITY_ROW_HEIGHT) + .constraintSize({ minHeight: Constants.AUTHORITY_CONSTRAINTSIZE_MINHEIGHT }) + } + if (!index) { + Row() { + Flex() { + Column().width(Constants.APPLICATION_TEXT_DECORATION_MARGIN_LEFT) + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .height(Constants.TEXT_DECORATION_HEIGHT) + .flexGrow(Constants.FLEX_GROW) + } + } + } + }.onClick(() => { + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + /** + * Grant permissions to the app + * @param {Number} accessTokenId + * @param {String} permission permission name + * @param {Number} index Array index to modify permission status + */ + grantUserGrantedPermission(accessTokenId, permission, index) { + abilityAccessCtrl.createAtManager().grantUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then(result => { + // result: 0 Authorization succeeded; result: -1 Authorization failed + if (result !== Constants.PERMISSION_INDEX) { + this.authorizeDialogController.open(); + this.toggleIsOn[index] = false; + setTimeout(()=> { + this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + } else { + this.toggleIsOn[index] = true; + } + let num = Constants.PERMISSION_NUM; + for(let key in this.toggleIsOn){ + if(this.toggleIsOn[key]){ + num++; + } + } + this.permissionNum = num; + }).catch(error => { + console.error(TAG + 'abilityAccessCtrl.createAtManager.grantUserGrantedPermission failed. Cause: ' + JSON.stringify(error)); + }) + } + + /** + * Deauthorize the app + * @param {Number} accessTokenId + * @param {String} permission permission name + * @param {Number} index Array index to modify permission status + */ + revokeUserGrantedPermission(accessTokenId, permission, index) { + abilityAccessCtrl.createAtManager().revokeUserGrantedPermission( + accessTokenId, permission, Constants.PERMISSION_FLAG).then(result => { + // result: 0 successfully cancel the authorization; result: -1 cancel the authorization failed + if (result !== Constants.PERMISSION_INDEX) { + this.authorizeDialogController.open(); + this.toggleIsOn[index] = true; + setTimeout(()=> { + this.authorizeDialogController.close(); + }, Constants.DELAY_TIME) + } else { + this.toggleIsOn[index] = false; + } + let num = Constants.PERMISSION_NUM; + for(let key in this.toggleIsOn){ + if(this.toggleIsOn[key]){ + num++; + } + } + this.permissionNum = num; + }) + } + + /** + * Lifecycle function, executed when the page is initialized + */ + aboutToAppear() { + let bundleNames = routerData[0].bundleNames; + + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + item.getString($r("app.string.textInput_placeholder").id, (err, val) => { + this.placeholder = val + }) + }) + + // initial then fill values when sync return which may cause sync panic + for (let i = 0; i < bundleNames.length; i++) { + this.applicationList.push( + new ApplicationObj('', '', i, 0, '', '')); + this.oldApplicationItem.push( + new ApplicationObj('', '', i, 0, '', '')); + } + + for (let i = 0; i < bundleNames.length; i++) { + // Get BundleInfo based on bundle name + bundle.getBundleInfo(bundleNames[i], Constants.PARMETER_BUNDLE_FLAG).then(res => { + Promise.all([getAppLabel(res.appInfo.labelId, res.name), + getAppIcon(res.appInfo.iconId, res.name), + verifyAccessToken(res.appInfo.accessTokenId, routerData[0].permission)]) + .then((values) => { + this.applicationList[i] = ( + new ApplicationObj( + String(values[0]), + String(values[1]), + i, + res.appInfo.accessTokenId, + routerData[0].permission, + makePy(values[0])[0].slice(0, 1)) // Get the first letter in the returned initials array + ); + this.oldApplicationItem[i] = ( + new ApplicationObj( + String(values[0]), + String(values[1]), + i, + res.appInfo.accessTokenId, + routerData[0].permission, + makePy(values[0])[0].slice(0, 1)) // Get the first letter in the returned initials array + ); + // 0: have permission; -1: no permission + if (values[2] === Constants.PERMISSION_INDEX) { + this.toggleIsOn[i] = true; + this.permissionNum++; + } else { + this.toggleIsOn[i] = false; + } + }); + }).catch(error => { + console.log(TAG + bundleNames[i] + "getBundleInfo failed, cause: " + JSON.stringify(error)); + }) + } + } + + build() { + Column() { + Row() { + textInput({ + placeholder: this.placeholder, + applicationItem: $applicationList, + oldApplicationItem: $oldApplicationItem, + searchResult: $searchResult + }) + }.padding({ + left: Constants.AUTHORITY_TEXTINPUT_PADDING_LEFT, + right: Constants.AUTHORITY_TEXTINPUT_PADDING_RIGHT + }) + Row() { + Flex({ alignItems:ItemAlign.Start, justifyContent: FlexAlign.Start }) { + Column() { + Flex({ justifyContent: FlexAlign.Start }) { + Text(this.permissionNum + '个应用获取此权限') + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.secondary_font_color')) + .margin({ top: Constants.AUTHORITY_TEXT_MARGIN_TOP, left: Constants.AUTHORITY_TEXT_MARGIN_LEFT }) + } + Scroll() { + Row() { + Column() { + if (!this.applicationList.length) { + if (this.searchResult) { + Row() { + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } else { + Row() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Image($r('app.media.searchnoresult')) + .customizeImage(Constants.SEARCHNORESULT_IMAGE_WIDTH, Constants.SEARCHNORESULT_IMAGE_HEIGHT) + } + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } + } else { + Row() { + List() { + ForEach(this.applicationList.slice(Constants.SLICE_START, this.applicationList.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.applicationList.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.AUTHORITY_ROW_MARGIN_TOP }) + } + }.width(Constants.FULL_WIDTH) + .height(Constants.AUTHORITY_COLUMN_HEIGHT) + } + } + }.padding({ left: Constants.AUTHORITY_LISTITEM_PADDING_LEFT }) + Column() { + alphabetIndexerComponent({ applicationItem: $applicationList, oldApplicationItem: $oldApplicationItem }) + }.width(Constants.AUTHORITY_ALPHABETINDEX_WIDTH) + .padding({ top: Constants.AUTHORITY_ALPHABETINDEX_PADDING_TOP }) + } + } + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets new file mode 100644 index 000000000..a56068a72 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import bundle from '@ohos.bundle'; +import Resmgr from '@ohos.resourceManager' +import rpc from '@ohos.rpc'; +import { Log, getPermissionGroup } from '../common/utils/utils' +import Constants from '../common/utils/constant' +import { BundleFlag } from '../common/model/bundle' +import { permissionGroups, showSubpermissionsGrop } from '../common/model/permissionGroup' + +@Extend(Button) function customizeButton() { + .backgroundColor($r('app.color.default_background_color')) + .fontColor($r('app.color.button_color')) + .fontWeight(FontWeight.Medium) + .height(Constants.BUTTON_HEIGHT) + .width(Constants.BUTTON_WIDTH) +} + +@Entry +@Component +struct dialogPlusPage { + @State count: number = 0 + @State result: Array = [] + @State accessTokenId: number = 0 + @State initStatus: number = Constants.INIT_NEED_TO_WAIT + @State reqPerms: Array = [] + @State grantGroups: Array = [] + @State userFixedFlag: number = 2 // means user fixed + @State appName: string = "" + @State win: any = "" + @State proxy: any = '' + + build() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Column() { + if ((this.initStatus != Constants.INIT_NEED_TO_WAIT) && this.verify()) { + Image(this.grantGroups[this.count].icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .fillColor($r("app.color.first_font_color")) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) + Text(`${this.count + 1} / ${this.grantGroups.length}`) + .fontSize(Constants.DIALOG_LABEL_FONT_SIZE) + .fontColor($r('app.color.text_secondary_color')) + .lineHeight(Constants.DIALOG_LABEL_LINE_HEIGHT) + .margin({ + top: Constants.DIALOG_LABEL_MARGIN_TOP + }) + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Start }) { + Text("是否允许" + this.appName + + this.grantGroups[this.count].label) + .fontSize(Constants.DIALOG_REQ_FONT_SIZE) + .fontColor($r('app.color.first_font_color')) + .fontWeight(FontWeight.Medium) + .fontSize(Constants.DIALOG_REQ_FONT_SIZE) + .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) + .margin({ + top: Constants.DIALOG_REQ_MARGIN_TOP, + left: Constants.DIALOG_REQ_MARGIN_LEFT + }) + } + } + + Row() { + Flex({ justifyContent: FlexAlign.Start }) { + Text(this.grantGroups[this.count].description) + .fontSize(Constants.DIALOG_DESP_FONT_SIZE) + .fontColor($r('app.color.text_secondary_color')) + .fontSize(Constants.DIALOG_DESP_FONT_SIZE) + .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) + .margin({ + top: Constants.DIALOG_DESP_MARGIN_TOP, + left: Constants.DIALOG_DESP_MARGIN_LEFT, + right: Constants.DIALOG_DESP_MARGIN_RIGHT, + bottom: Constants.DIALOG_DESP_MARGIN_BOTTOM + }) + } + } + } + } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button('禁止') + .fontSize(Constants.BUTTON_FONT_SIZE) + .onClick(() => { + this.privacyCancel(this.grantGroups[this.count], this.accessTokenId, this.reqPerms, this.userFixedFlag) + }).customizeButton().margin({ left: Constants.BUTTON_MARGIN_LEFT }) + Text('|').fontSize(Constants.BUTTON_DIVIDER_FONT_SIZE).fontColor($r('app.color.divider_color')) + Button('允许') + .fontSize(Constants.BUTTON_FONT_SIZE) + .onClick(() => { + this.privacyAccept(this.grantGroups[this.count], this.accessTokenId, this.reqPerms, this.userFixedFlag) + }).customizeButton().margin({ right: Constants.BUTTON_MARGIN_RIGHT }) + } + } + } + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) + .width(Constants.DIALOG_PRIVACY_WIDTH) + .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) + }.width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + + verify() { + if((this.initStatus == Constants.INIT_NEED_TO_TERMINATED) || (this.count >= this.grantGroups.length)) { + this.answerRequest() + this.initStatus = Constants.INIT_NEED_TO_WAIT + return false + } + return true + } + + answerRequest() { + var ret: number = Constants.RESULT_SUCCESS + if (this.initStatus == Constants.INIT_NEED_TO_TERMINATED) { + ret = Constants.RESULT_FAILURE + } + this.answer(ret, this.reqPerms) + } + + answer(ret, reqPerms) { + Log.info("code:" + ret + ", perms="+ JSON.stringify(reqPerms) +", result=" + JSON.stringify(this.result)) + var perms = [] + var results = [] + reqPerms.forEach(perm => { + perms.push(perm) + }) + this.result.forEach(result => { + results.push(result) + }) + let option = new rpc.MessageOption() + let data = new rpc.MessageParcel() + let reply = new rpc.MessageParcel() + Promise.all([data.writeInterfaceToken(Constants.ACCESS_TOKEN), + data.writeStringArray(perms), + data.writeIntArray(results) + ]).then(() => { + this.proxy.sendRequest(Constants.RESULT_CODE, data, reply, option) + this.destruction() + }).catch(() => { + Log.error('write result failed!') + this.destruction() + }) + } + + destruction() { + this.win.destroy() + globalThis.windowNum -- + Log.info("windowNum:" + globalThis.windowNum) + if(globalThis.windowNum == 0) { + globalThis.extensionContext.terminateSelf() + } + } + + async privacyAccept(group, accessTokenId, permissionList, userFixedFlag) { + var acManager = abilityAccessCtrl.createAtManager() + var num = 0 + group.permissions.forEach(async permission => { + let result + if(showSubpermissionsGrop.indexOf(group.groupName) == -1) { + result = await acManager.grantUserGrantedPermission(accessTokenId, permission, userFixedFlag) + }else { + if(permissionList.includes(permission)) { + result = await acManager.grantUserGrantedPermission(accessTokenId, permission, userFixedFlag) + } + } + num ++ + Log.info("grant permission result:" + result + "permission" + permission) + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + permissionList.forEach((req, idx) => { + if(req == permission) { + this.result[idx] = abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED; + } + }) + Log.info("grant permission success:" + permission) + } else { + Log.error("failed to grant permission:" + permission + " ret:" + result) + } + if(num == group.permissions.length) { + this.count ++ + } + }) + } + + async privacyCancel(group, accessTokenId, permissionList, userFixedFlag) { + var acManager = abilityAccessCtrl.createAtManager() + group.permissions.forEach(async permission => { + let result + if(showSubpermissionsGrop.indexOf(group.groupName) == -1) { + result = await acManager.revokeUserGrantedPermission(accessTokenId, permission, userFixedFlag) + }else { + if(permissionList.includes(permission)) { + result = await acManager.revokeUserGrantedPermission(accessTokenId, permission, userFixedFlag) + } + } + Log.info("revoke permission result:" + result + "permission" + permission); + }) + this.count ++ + } + + getgrantGroups(stateGroup) { + this.reqPerms.forEach((permission, idx) => { + //已授权 + if(stateGroup[idx] == Constants.PASS_OPER) { + Log.info("permission has been fixed:" + permission) + this.result[idx] = abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED; + //待授权 + }else if(stateGroup[idx] == Constants.DYNAMIC_OPER) { + var group = getPermissionGroup(permission) + if(!group) { + Log.info("permission not find:" + permission) + }else { + var exist = this.grantGroups.find(grantGroup => grantGroup.name == group.name) + //判断是否为需要展示子权限的权限组 + if(showSubpermissionsGrop.indexOf(group.groupName) != -1) { + var permissionDetail + permissionGroups.forEach(permissionGroup => { + if(permissionGroup.permissionName == permission) { + //获取授权的权限信息 + permissionDetail = permissionGroup + } + }) + //权限组已存在的情况 + if(!exist) { + group.description = [permissionDetail.label] + this.grantGroups.push(group) + }else { + if(exist.description.indexOf(permissionDetail.label) == -1) { + exist.description.push(permissionDetail.label) + } + } + }else { + if(!exist) { + this.grantGroups.push(group) + } + } + } + } + }) + this.initStatus = Constants.INIT_NEED_TO_VERIFY + } + + getApplicationName(uid) { + bundle.getNameForUid(uid).then((data) => { + Log.info("getApplicationName bundleName:" + data) + Log.info("getApplicationName userId:" + Math.floor(uid/200000)) + bundle.getApplicationInfo(data, BundleFlag.GET_BUNDLE_DEFAULT, Math.floor(uid/200000)).then(applicationInfo => { + Resmgr.getResourceManager(globalThis.extensionContext, data).then(item => { + item.getString(applicationInfo.labelId, (err, value) => { + if (value == undefined) { + this.appName = applicationInfo.label + } else { + this.appName = value + } + Log.info("hap label:" + applicationInfo.label + ", value:"+this.appName) + }) + }) + }).catch(err => { + Log.error("applicationInfo error :" + err) + this.initStatus = Constants.INIT_NEED_TO_TERMINATED + }) + bundle.getBundleInfo(data, Constants.PARMETER_BUNDLE_FLAG).then(bundleInfo => { + this.grantGroups.forEach((group, idx) => { + if(group.description) { + Resmgr.getResourceManager(globalThis.extensionContext, Constants.BUNDLE_NAME).then(item => { + Promise.all([item.getString($r("app.string.separator").id), + item.getString($r("app.string.reason_suffix").id)]) + .then(values => { + group.description = group.description.join(values[0]) + group.description += values[1] + this.getReason(group, bundleInfo, data) + }) + }) + }else { + this.getReason(group, bundleInfo, data) + } + }) + }) + }).catch(err => { + Log.error("getNameForUid error :" + JSON.stringify(err)) + this.initStatus = Constants.INIT_NEED_TO_TERMINATED + }) + } + + getReason(group, bundleInfo, bundleName) { + group.permissions.forEach(permission => { + if(this.reqPerms.indexOf(permission) != -1) { + bundleInfo.reqPermissionDetails.forEach(reqPermissionDetail => { + if(reqPermissionDetail.name == permission) { + Resmgr.getResourceManager(globalThis.extensionContext, bundleName).then(item => { + item.getString(reqPermissionDetail.reasonId, (err, value) => { + this.initStatus = Constants.INIT_NEED_TO_REFRESH + if (value !== undefined && !group.hasReason) { + group.description += value.slice(Constants.START_SUBSCRIPT, Constants.END_SUBSCRIPT) + group.hasReason = true + } + }) + }) + } + }) + } + }) + } + + aboutToAppear() { + this.count = 0; + this.initStatus = Constants.INIT_NEED_TO_WAIT + this.result = [] + this.reqPerms = globalThis.abilityWant.parameters['ohos.user.grant.permission'] + this.accessTokenId = globalThis.abilityWant.parameters['ohos.aafwk.param.callerToken'] + this.proxy = globalThis.abilityWant.parameters['ohos.ability.params.callback'].value + this.win = globalThis.extensionWin + if (this.reqPerms == undefined || this.accessTokenId == undefined || this.reqPerms.length == 0) { + Log.info("invalid parameters") + this.initStatus = Constants.INIT_NEED_TO_TERMINATED + return + } + Log.info("request permission=" + JSON.stringify(this.reqPerms) + ", tokenId = " + this.accessTokenId) + Log.info("permission state=" + JSON.stringify(globalThis.abilityWant.parameters['ohos.user.grant.permission.state'])); + this.result = new Array(this.reqPerms.length).fill(-1); + this.getgrantGroups(globalThis.abilityWant.parameters['ohos.user.grant.permission.state']); + this.getApplicationName(globalThis.abilityWant.parameters['ohos.aafwk.param.callerUid']) + } +} + diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/other-permissions.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/other-permissions.ets new file mode 100644 index 000000000..1de45de53 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/other-permissions.ets @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { backBar } from "../common/components/backBar"; +import router from '@system.router'; +import Constants from '../common/utils/constant'; +import { otherPermissionsLabel } from '../common/model/permissionGroup' +import abilityAccessCtrl from '@ohos.abilityAccessCtrl' + +var TAG = 'PermissionManager_MainAbility:' + +let routerData = router.getParams().routerData; // Routing jump data +let tokenId: any = router.getParams().tokenId; // tokenId for verify permission +let backTitle = router.getParams().backTitle; // return title name +let status = router.getParams().status; // Status: Allowed, Forbidden +let permissions: any = router.getParams().permission; // permissions name +let otherPermissionList = []; // otherPermission List +for (let i = 0; i < permissions.length; i++) { + otherPermissionList.push({ + permissionLabel: otherPermissionsLabel[permissions[i]], + permission: permissions[i] + }) +} + +@Entry +@Component +struct appNamePage { + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar({ title: JSON.stringify(backTitle), recordable: false }) + } + Row() { + Column() { + Scroll() { + appNameItem() + } + } + }.layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } + +/** + * Lifecycle function, triggered once when this page is displayed + */ + onPageShow() { + console.log(TAG + 'onPageShow other-permissions') + let isGranted = true; + permissions.forEach(permission => { + abilityAccessCtrl.createAtManager().verifyAccessToken(tokenId, permission).then(res => { + status = res; + }) + .catch(err => { + console.error(TAG + 'verifyAccessToken occure error: ' + JSON.stringify(err)) + }) + }) + } +} + +@Component +struct appNameItem { + @State otherPermissionListItem: string[] = otherPermissionList; // Other permission interface data array + @Builder ListItemLayout(item, index) { + ListItem() { + Row() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + Text(item.permissionLabel) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontColor($r('app.color.text_color')) + .flexGrow(Constants.FLEX_GROW) + Image($r('app.media.rightarrow')) + .objectFit(ImageFit.Contain) + .height(Constants.IMAGE_HEIGHT) + .width(Constants.IMAGE_WIDTH) + } + .width(Constants.FULL_WIDTH) + .height(Constants.LISTITEM_ROW_HEIGHT) + } + if (!index) { + Row() { + Column() + .backgroundColor($r('app.color.text_decoration_color')) + .width(Constants.FULL_WIDTH) + .height(Constants.TEXT_DECORATION_HEIGHT) + } + } + }.onClick(() => { + router.push({ + uri: 'pages/application-tertiary', + params: { + routerData: routerData, + backTitle: item.permissionLabel, + permission: [item.permission], + status: status + } + }); + }) + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END }) + } + + build() { + Row() { + Column() { + Row() { + List() { + ForEach(this.otherPermissionListItem.slice(Constants.SLICE_START, this.otherPermissionListItem.length - 1), + (item) => { + this.ListItemLayout(item, Constants.SLICE_START_INDEX) + }, item => item.toString()) + ForEach(this.otherPermissionListItem.slice(Constants.SLICE_END), (item, index) => { + this.ListItemLayout(item, Constants.SLICE_END_INDEX) + }, item => item.toString()) + }.backgroundColor($r('app.color.default_background_color')).borderRadius(Constants.BORDER_RADIUS) + .padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.margin({ top: Constants.ROW_MARGIN_TOP }) + .padding({ left: Constants.LIST_PADDING_LEFT, right: Constants.LISTITEM_PADDING_RIGHT }) + } + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/permission-access-record.ets b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/permission-access-record.ets new file mode 100644 index 000000000..529f738d3 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/permission-access-record.ets @@ -0,0 +1,533 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import bundle from '@ohos.bundle'; +import router from '@system.router'; +import Resmgr from '@ohos.resourceManager' +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +import privacyManager from '@ohos.privacyManager' +import { backBar } from "../common/components/backBar"; +import Constants from '../common/utils/constant'; +import { noNeedDisplayApp, userGrantPermissions, permissionGroupIds } from "../common/model/permissionGroup"; +import { getPermissionGroup } from '../common/utils/utils' + +var TAG = 'PermissionManager_MainAbility:' + +@Extend(Image) function customizeImage(width: number, height: number) { + .objectFit(ImageFit.Contain) + .width(width) + .height(height) +}; + +@Entry +@Component +struct permissionRecordPage { + @State groups: any[] = [] + @State applicationInfos: any[] = [] + @State permissionApplications: any[] = [] + @State permissionIndex: number = -1 + @State applicationIndex: number = -1 + @State strings: any = {} + @State currentIndex: number = 0 + @Builder TabBuilder(index: number) { + Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(index ? $r('app.string.application') : $r('app.string.authority')) + .fontColor(this.currentIndex == index ? $r('app.color.button_color') : $r('app.color.label_color')) + .fontWeight(this.currentIndex == index ? FontWeight.Bold : FontWeight.Regular) + .lineHeight(Constants.TEXT_LINE_HEIGHT) + if(this.currentIndex == index) { + Row().width(Constants.FULL_WIDTH).height(Constants.TAB_DECORATION_HEIGHT) + .backgroundColor($r('app.color.button_color')) + .position({ y: Constants.TAB_DECORATION_POSITION_Y }) + } + }.height(Constants.TAB_HEIGHT) + } + + @Builder ListItemLayout(item, index, dimension) { + ListItem() { + Column() { + Column() { + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Row() { + if(dimension) { + Image(item.icon) + .customizeImage(Constants.MANAGEMENT_IMAGE_WIDTH, Constants.MANAGEMENT_IMAGE_HEIGHT) + .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT_RECORD, left: Constants.MANAGEMENT_IMAGE_MARGIN_LEFT }) + }else { + Image(item.icon) + .customizeImage(Constants.APPLICATION_IMAGE_WIDTH, Constants.APPLICATION_IMAGE_HEIGHT) + .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT }) + } + Column() { + Text(item.groupName) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .lineHeight(Constants.TEXT_LINE_HEIGHT) + .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM }) + if(dimension) { + Text(this.strings.visits + item.sum) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT) + }else { + Row() { + if (item.permissions) { + ForEach(item.permissions, permission => { + Image(permission.icon) + .customizeImage(Constants.IMAGE_WIDTH_RECORD_APPLICATION, Constants.IMAGE_HEIGHT_RECORD_APPLICATION) + .margin({ right: Constants.APPLICATION_TEXT_MARGIN_RIGHT }) + }) + } + } + } + }.flexGrow(Constants.FLEX_GROW) + .alignItems(HorizontalAlign.Start) + if(dimension) { + if(index == this.permissionIndex) { + Image($r('app.media.xiangshangjiantou')) + .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD) + }else { + Image($r('app.media.xiangxiajiantou')) + .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD) + } + }else { + if(index == this.applicationIndex) { + Image($r('app.media.xiangshangjiantou')) + .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD) + }else { + Image($r('app.media.xiangxiajiantou')) + .customizeImage(Constants.IMAGE_WIDTH_RECORD, Constants.IMAGE_HEIGHT_RECORD) + } + } + } + .width(Constants.FULL_WIDTH) + .height(dimension ? Constants.LISTITEM_HEIGHT_PERMISSION : Constants.LISTITEM_HEIGHT_APPLICATION) + } + }.onClick(() => { + dimension ? + (this.permissionIndex = this.permissionIndex == index ? -1 : index) : + (this.applicationIndex = this.applicationIndex == index ? -1 : index) + if(dimension) { + this.permissionApplications = this.applicationInfos.filter(appInfo => { + return appInfo.groupNames.includes(item.groupName) + }) + } + }) + if(dimension && (index == this.permissionIndex)) { + List() { + ForEach(this.permissionApplications, (permissionApplication) => { + ListItem() { + Row() { + Image(permissionApplication.icon) + .customizeImage(Constants.APPLICATION_IMAGE_WIDTH, Constants.APPLICATION_IMAGE_HEIGHT) + .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT }) + Column() { + Row().width(Constants.FULL_WIDTH).height(Constants.TEXT_DECORATION_HEIGHT) + .backgroundColor($r("app.color.label_color_lightest")) + .margin({ bottom: Constants.LISTITEM_MARGIN_BOTTOM_PERMISSION }) + Text(permissionApplication.groupName) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .lineHeight(Constants.TEXT_LINE_HEIGHT) + .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM }) + Text(this.strings.visits + this.getAppRecords(permissionApplication, item.groupName, true) + + this.strings.recent_visit + this.getTime(this.getAppRecords(permissionApplication, item.groupName, false))) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT) + }.alignItems(HorizontalAlign.Start) + .height(Constants.FULL_HEIGHT) + } + }.height(Constants.LISTITEM_HEIGHT_APPLICATION) + .onClick(() => { + router.push({ + uri: 'pages/application-secondary', + params: { routerData: { + 'bundleName': permissionApplication.name, + 'tokenId': permissionApplication.accessTokenId, + 'iconId': permissionApplication.icon, + 'labelId': permissionApplication.groupName, + 'permissions': permissionApplication.reqUserPermissions, + 'groupId': permissionApplication.groupIds + } } + }); + }) + }) + } + } + if(!dimension && (index == this.applicationIndex)) { + List() { + ForEach(item.permissions, (permission) => { + ListItem() { + Row() { + Image(permission.icon) + .customizeImage(Constants.MANAGEMENT_IMAGE_WIDTH, Constants.MANAGEMENT_IMAGE_HEIGHT) + .margin({ right: Constants.MANAGEMENT_IMAGE_MARGIN_RIGHT_RECORD, left: Constants.MANAGEMENT_IMAGE_MARGIN_LEFT }) + Column() { + Row().width(Constants.FULL_WIDTH).height(Constants.TEXT_DECORATION_HEIGHT) + .backgroundColor($r("app.color.label_color_lightest")) + .margin({ bottom: Constants.LISTITEM_MARGIN_BOTTOM_APPLICATION }) + Text(permission.groupName) + .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontWeight(FontWeight.Medium) + .fontColor($r('app.color.label_color')) + .lineHeight(Constants.TEXT_LINE_HEIGHT) + .margin({ bottom: Constants.TERTIARY_LABEL_MARGIN_BOTTOM }) + Text(this.strings.visits + permission['count' + item.accessTokenId] + + this.strings.recent_visit + this.getTime(permission['lastTime' + item.accessTokenId])) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .lineHeight(Constants.TEXT_SMALL_LINE_HEIGHT) + }.alignItems(HorizontalAlign.Start) + .height(Constants.FULL_HEIGHT) + } + }.height(Constants.LISTITEM_HEIGHT_PERMISSION) + .onClick(() => { + router.push({ + uri: 'pages/application-secondary', + params: { routerData: { + 'bundleName': item.name, + 'tokenId': item.accessTokenId, + 'iconId': item.icon, + 'labelId': item.groupName, + 'permissions': item.reqUserPermissions, + 'groupId': item.groupIds + } } + }); + }) + }) + } + } + } + }.padding({ left: Constants.DEFAULT_PADDING_START, right: Constants.DEFAULT_PADDING_END, + top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + .margin({ bottom: Constants.LISTITEM_MARGIN_BOTTOM }) + .backgroundColor($r('app.color.default_background_color')) + .borderRadius(Constants.BORDER_RADIUS) + } + + build() { + GridContainer({ gutter: Constants.GUTTER, margin: Constants.GRID_MARGIN }) { + Row() { + Row() + .useSizeType({ + xs: { span: Constants.LEFT_XS_SPAN, offset: Constants.LEFT_XS_OFFSET }, + sm: { span: Constants.LEFT_SM_SPAN, offset: Constants.LEFT_SM_OFFSET }, + md: { span: Constants.LEFT_MD_SPAN, offset: Constants.LEFT_MD_OFFSET }, + lg: { span: Constants.LEFT_LG_SPAN, offset: Constants.LEFT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() { + Column() { + Row() { + backBar( { title: JSON.stringify($r('app.string.permission_access_record')), recordable: false }) + } + Row() { + Column() { + Column() { + Flex({ justifyContent: FlexAlign.Start }) { + Text($r('app.string.record_time_limit')) + .margin({ left: Constants.BACKBAR_IMAGE_MARGIN_LEFT }) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + .lineHeight(Constants.SUBTITLE_LINE_HEIGHT) + }.constraintSize({ minHeight: Constants.SUBTITLE_MIN_HEIGHT }) + .padding({ top: Constants.SUBTITLE_PADDING_TOP, bottom: Constants.SUBTITLE_PADDING_BOTTOM }) + if(this.groups.length) { + Stack() { + Tabs() { + TabContent() { + Row() { + Column() { + Scroll() { + Row() { + List() { + ForEach(this.groups, (item, index) => { + this.ListItemLayout(item, index, Constants.PERMISSION) + }, item => item.toString()) + }.padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.padding({ + left: Constants.MANAGEMENT_ROW_PADDING_LEFT, + right: Constants.MANAGEMENT_ROW_PADDING_RIGHT, + top: Constants.MANAGEMENT_ROW_PADDING_TOP + }) + }.scrollBar(BarState.Off) + }.width(Constants.FULL_WIDTH) + } + }.tabBar(this.TabBuilder(0)) + TabContent() { + Row() { + Column() { + Scroll() { + Row() { + List() { + ForEach(this.applicationInfos, (item, index) => { + this.ListItemLayout(item, index, Constants.APPLICATION) + }, item => item.toString()) + }.padding({ top: Constants.LIST_PADDING_TOP, bottom: Constants.LIST_PADDING_BOTTOM }) + }.padding({ + left: Constants.MANAGEMENT_ROW_PADDING_LEFT, + right: Constants.MANAGEMENT_ROW_PADDING_RIGHT, + top: Constants.MANAGEMENT_ROW_PADDING_TOP + }) + }.scrollBar(BarState.Off) + }.width(Constants.FULL_WIDTH) + } + }.tabBar(this.TabBuilder(1)) + } + .barWidth(Constants.BAR_WIDTH) + .barMode(BarMode.Fixed) + .onChange((index) => { + this.currentIndex = index + }) + }.height(Constants.FULL_HEIGHT) + }else { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center, direction: FlexDirection.Column }) { + Image($r('app.media.noRecord')) + .customizeImage(Constants.NORECORD_IMAGE_WIDTH, Constants.NORECORD_IMAGE_HEIGHT) + .margin({ left: Constants.NORECORD_IMAGE_MARGIN_LEFT }) + Text($r('app.string.no_record')).margin({ top: Constants.DIALOG_REQ_MARGIN_TOP }) + .fontSize(Constants.TEXT_SMAL_FONT_SIZE) + .fontColor($r('app.color.label_color_light')) + }.width(Constants.FULL_WIDTH).height(Constants.FULL_HEIGHT) + .padding({ bottom: Constants.RECORD_PADDING_BOTTOM }) + } + } + } + } + .layoutWeight(Constants.LAYOUT_WEIGHT) + } + } + .useSizeType({ + xs: { span: Constants.MIDDLE_XS_SPAN, offset: Constants.MIDDLE_XS_OFFSET }, + sm: { span: Constants.MIDDLE_SM_SPAN, offset: Constants.MIDDLE_SM_OFFSET }, + md: { span: Constants.MIDDLE_MD_SPAN, offset: Constants.MIDDLE_MD_OFFSET }, + lg: { span: Constants.MIDDLE_LG_SPAN, offset: Constants.MIDDLE_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + Row() + .useSizeType({ + xs: { span: Constants.RIGHT_XS_SPAN, offset: Constants.RIGHT_XS_OFFSET }, + sm: { span: Constants.RIGHT_SM_SPAN, offset: Constants.RIGHT_SM_OFFSET }, + md: { span: Constants.RIGHT_MD_SPAN, offset: Constants.RIGHT_MD_OFFSET }, + lg: { span: Constants.RIGHT_LG_SPAN, offset: Constants.RIGHT_LG_OFFSET } + }) + .height(Constants.FULL_HEIGHT) + } + .height(Constants.FULL_HEIGHT) + .width(Constants.FULL_WIDTH) + .backgroundColor($r("sys.color.ohos_id_color_sub_background")) + .opacity(Constants.MANAGEMENT_TRANSPARENCY) + } + } + + /** + * Get time + * @param {Number} The time stamp + */ + getTime(time, format='MM月DD日 NNHH:mm') { + if(this.strings.morning == 'am') { format = 'MM/DD HH:mm NN' } + let date = new Date(time * 1000) + let config = { + MM: date.getMonth() + 1, + DD: date.getDate(), + NN: date.getHours() >= 12 ? this.strings.afternoon : this.strings.morning, + HH: date.getHours() >= 12 ? date.getHours() - 12 : date.getHours(), + mm: date.getMinutes() > 10 ? date.getMinutes() : '0' + date.getMinutes(), + } + + for(const key in config){ + format = format.replace(key,config[key]) + } + return format + } + + /** + * Get application record info + * @param {Object} application info + * @param {String} groupName + * @param {Boolean} true: count, false: lastTime + */ + getAppRecords(appInfo, groupName, option) { + var record = appInfo.permissions.filter(permission => { + return permission.groupName == groupName + }) + return option ? record[0]['count' + appInfo.accessTokenId] : record[0]['lastTime' + appInfo.accessTokenId] + } + + getStrings() { + Resmgr.getResourceManager(globalThis.context, Constants.BUNDLE_NAME).then(item => { + item.getString($r("app.string.visits").id, (err, val) => { + this.strings.visits = val + }) + item.getString($r("app.string.recent_visit").id, (err, val) => { + this.strings.recent_visit = val + }) + item.getString($r("app.string.morning").id, (err, val) => { + this.strings.morning = val + }) + item.getString($r("app.string.afternoon").id, (err, val) => { + this.strings.afternoon = val + }) + }).catch(error => { + console.error(TAG + 'Resmgr.getResourceManager failed. Cause: ' + JSON.stringify(error)); + }) + } + + getInfo(record, sortFlag) { + bundle.getBundleInfo(record.bundleName, Constants.PARMETER_BUNDLE_FLAG).then(async info => { + var reqUserPermissions: string[] = []; + var reqUserRecords: any[] = []; + var permissionGroups: any[] = []; + var acManager = abilityAccessCtrl.createAtManager() + var appInfo: any = {} + for (let j = 0; j < record.permissionRecords.length; j++) { + var permission = record.permissionRecords[j].permissionName; + var flag = await acManager.getPermissionFlags(info.appInfo.accessTokenId, permission) + if(flag == Constants.PRE_AUTHORIZATION_NOT_MODIFIED) { + continue + } + if (userGrantPermissions.indexOf(permission) != -1) { + reqUserRecords.push(record.permissionRecords[j]) + } + } + for (let k = 0; k < info.reqPermissions.length; k++) { + var reqPermission = info.reqPermissions[k]; + var reqFlag = await acManager.getPermissionFlags(info.appInfo.accessTokenId, reqPermission) + if(reqFlag == Constants.PRE_AUTHORIZATION_NOT_MODIFIED) { + continue + } + if (userGrantPermissions.indexOf(reqPermission) != -1) { + reqUserPermissions.push(reqPermission); + } + } + + let groupNames = []; + let appLastTime = 0; + reqUserRecords.forEach(reqUserRecord => { + var group = getPermissionGroup(reqUserRecord.permissionName) + if(!group) { + console.info(TAG + "permission not find:" + reqUserRecord.permissionName) + }else { + var existing = permissionGroups.find(permissionGroup => permissionGroup.name == group.name) + var lastTime = reqUserRecord.lastAccessTime + lastTime > appLastTime ? appLastTime = lastTime : '' + if(!existing) { + group['count' + record.tokenId] = reqUserRecord.accessCount + group['lastTime' + record.tokenId] = lastTime + permissionGroups.push(group) + groupNames.push(group.groupName) + }else { + existing['count' + record.tokenId] += reqUserRecord.accessCount + lastTime > existing['lastTime' + record.tokenId] ? existing['lastTime' + record.tokenId] = lastTime : '' + } + } + }) + + let groupIds = []; + for (let i = 0; i < reqUserPermissions.length; i++) { + if(groupIds.indexOf(permissionGroupIds[reqUserPermissions[i]]) == -1){ + groupIds.push(permissionGroupIds[reqUserPermissions[i]]); + } + } + + await Resmgr.getResourceManager(globalThis.context, info.name).then(item => { + item.getString(info.appInfo['labelId'], (error, value) => { + if (value == undefined) { + appInfo['groupName'] = info.appInfo.label; + } else { + appInfo['groupName'] = value; + } + }) + + item.getMediaBase64(info.appInfo['iconId'], (error, value) => { + appInfo['icon'] = value; + }) + }) + + appInfo.name = info.appInfo.name + appInfo.accessTokenId = info.appInfo.accessTokenId + appInfo.reqUserPermissions = reqUserPermissions + appInfo.permissions = permissionGroups + appInfo.groupNames = groupNames + appInfo.groupIds = groupIds + appInfo.appLastTime = appLastTime + this.applicationInfos.push(appInfo) + if(sortFlag) { + var appInfos: any[] = [] + this.applicationInfos.forEach(item => { appInfos.push(item) }) + appInfos.sort((a, b) => { return b.appLastTime - a.appLastTime }) + this.applicationInfos = appInfos + } + }) + } + + getAllRecords() { + let request = { + "tokenId": 0, + "isRemote": false, + "permissionNames": [], + "beginTime": 0, + "endTime": 0, + "flag": 1 + } + privacyManager.getPermissionUsedRecords(request).then(async records => { + console.info(TAG + "records: " + JSON.stringify(records.bundleRecords)) + var groupArray: any[] = [] + for (let i = 0; i < records.bundleRecords.length; i++) { + var record = records.bundleRecords[i] + try { + const ret = await bundle.queryAbilityByWant({ + bundleName: record.bundleName, + action: "action.system.home", + entities: ["entity.system.home"] + }, bundle.BundleFlag.GET_ABILITY_INFO_WITH_APPLICATION, Constants.USERID); + } catch(e) { + continue; + } + if (noNeedDisplayApp.indexOf(record.bundleName) != -1) { + continue; + } + console.info(TAG + "record: " + JSON.stringify(record)) + this.getInfo(record, (i + 1) == records.bundleRecords.length) + + record.permissionRecords.forEach(permissionRecord => { + var group = getPermissionGroup(permissionRecord.permissionName) + if(group) { + var exist = groupArray.find(permissionGroup => permissionGroup.name == group.name) + var lastTime = permissionRecord.lastAccessTime + if(!exist) { + group.sum = permissionRecord.accessCount + group.recentVisit = lastTime + groupArray.push(group) + }else { + exist.sum += permissionRecord.accessCount + lastTime > exist.recentVisit ? exist.recentVisit = lastTime : '' + } + } + }) + } + groupArray.sort((a, b) => { return b.recentVisit - a.recentVisit }) + this.groups = groupArray + }) + } + + aboutToAppear() { + this.getStrings() + this.getAllRecords() + } +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/module.json5 b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/module.json5 new file mode 100644 index 000000000..321012a87 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/module.json5 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +{ + "module": { + "name": "permissionmanager", + "type": "feature", + "srcEntrance": "./ets/Application/AbilityStage.ts", + "description": "$string:permissionmanager_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [ + { + "name": "com.ohos.permissionmanager.MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "visible": true, + "launchType": "standard" + } + ], + "extensionAbilities": [ + { + "icon": "$media:icon", + "name": "com.ohos.permissionmanager.GrantAbility", + "srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts", + "type": "service", + "visible": true + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.GET_SENSITIVE_PERMISSIONS", + }, + { + "name": "ohos.permission.GRANT_SENSITIVE_PERMISSIONS" + }, + { + "name": "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS" + }, + { + "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED" + }, + { + "name": "ohos.permission.GET_BUNDLE_INFO" + }, + { + "name": "ohos.permission.PERMISSION_USED_STATS" + } + ] + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/ar/profile/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/ar/profile/string.json new file mode 100644 index 000000000..c3a6df19c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/ar/profile/string.json @@ -0,0 +1,14 @@ +{ + "strings": { + "app_name": "CategoryPage", + "describe": "describe", + "category": "Category", + "itemChild": "ItemChild", + "item": "Item", + "search": "search...", + "you_search": "You search ", + "you_clicked": "You clicked ", + "tab": "Tab", + "more": "< more" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/color.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/color.json new file mode 100644 index 000000000..d9c648ab6 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/color.json @@ -0,0 +1,112 @@ +{ + "color": [ + { + "name": "text_color", + "value": "#E5000000" + }, + { + "name": "label_color", + "value": "#182431" + }, + { + "name": "label_color_light", + "value": "#99182431" + }, + { + "name": "label_color_lighter", + "value": "#66182431" + }, + { + "name": "label_color_20", + "value": "#33182431" + }, + { + "name": "label_color_lightest", + "value": "#0D182431" + }, + { + "name": "background_color", + "value": "#F4F5F7" + }, + { + "name": "list_background_color", + "value": "#FDFDFD" + }, + { + "name": "text_secondary_color", + "value": "#99000000" + }, + { + "name": "active_background_color", + "value": "#e5f3ff" + }, + { + "name": "divider_color", + "value": "#f3f4f6" + }, + { + "name": "text_decoration_color", + "value": "#f3f4f6" + }, + { + "name": "default_background_color", + "value": "#ffffff" + }, + { + "name": "button_color", + "value": "#007DFF" + }, + { + "name": "shape_allow_color", + "value": "#1856D4" + }, + { + "name": "shape_ban_color", + "value": "#000000" + }, + { + "name": "first_font_color", + "value": "#E6000000" + }, + { + "name": "secondary_font_color", + "value": "#66000000" + }, + { + "name": "toggle_color", + "value": "#409eff" + }, + { + "name": "color_Primary", + "value": "#E5000000" + }, + { + "name": "color_Secondary", + "value": "#99000000" + }, + { + "name": "color_Tertiary", + "value": "#66000000" + }, + { + "name": "color_Fourth", + "value": "#33000000" + }, + { + "name": "selected_Color", + "value": "#ffffff" + }, + { + "name": "popup_Color", + "value": "#FFFAF0" + }, + { + "name": "selected_Background_Color", + "value": "#CCCCCC" + }, + { + "name": "popup_Background_Color", + "value": "#D2B48C" + } + ] +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/string.json new file mode 100644 index 000000000..a1b07a981 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/element/string.json @@ -0,0 +1,92 @@ +{ + "string": [ + { + "name": "permissionmanager_desc", + "value": "permissionmanager" + }, + { + "name": "MainAbility_desc", + "value": "manage the permissions of all applications from the permission and application dimensions" + }, + { + "name": "MainAbility_label", + "value": "permission manage" + }, + { + "name": "no_permission", + "value": "no permission" + }, + { + "name": "access_permission", + "value": "access permission" + }, + { + "name": "permission_access_record", + "value": "permission access record" + }, + { + "name": "authority_management", + "value": "authority management" + }, + { + "name": "other_permissions", + "value": "other permissions" + }, + { + "name": "application", + "value": "application" + }, + { + "name": "authority", + "value": "authority" + }, + { + "name": "textInput_placeholder", + "value": "search application" + }, + { + "name": "allowed", + "value": "allowed" + }, + { + "name": "banned", + "value": "banned" + }, + { + "name": "Authorization_failed", + "value": "Authorization failure!" + }, + { + "name": "reason_suffix", + "value": " and other permissions." + }, + { + "name": "separator", + "value": "," + }, + { + "name": "visits", + "value": "Number of visits:" + }, + { + "name": "recent_visit", + "value": ";Recent visits:" + }, + { + "name": "morning", + "value": "am" + }, + { + "name": "afternoon", + "value": "pm" + }, + { + "name": "no_record", + "value": "No permission access record" + }, + { + "name": "record_time_limit", + "value": "Access records in the last 7 days" + } + ] +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/gongneng_dian.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/gongneng_dian.svg new file mode 100644 index 000000000..50265c1b1 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/gongneng_dian.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_call_logs.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_call_logs.svg new file mode 100644 index 000000000..8826af67d --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_call_logs.svg @@ -0,0 +1,15 @@ + + + + + + + diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_dropzone.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_dropzone.svg new file mode 100644 index 000000000..960483f7f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_dropzone.svg @@ -0,0 +1,19 @@ + + + IC/ic_floatingwindow + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_exercise.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_exercise.svg new file mode 100644 index 000000000..e31feee74 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_exercise.svg @@ -0,0 +1,15 @@ + + + + diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_forward.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_forward.svg new file mode 100644 index 000000000..ddf503e7c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_forward.svg @@ -0,0 +1,13 @@ + + + + + + + diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_more.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_more.svg new file mode 100644 index 000000000..73ab24938 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_more.svg @@ -0,0 +1,7 @@ + + + HM/ic/24x24/more1.5 + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_multi_device_vector.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_multi_device_vector.svg new file mode 100644 index 000000000..b85bdf10a --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_multi_device_vector.svg @@ -0,0 +1,7 @@ + + + HM/ic/24x24/Multi-device vector + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_nearby.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_nearby.svg new file mode 100644 index 000000000..4b201c865 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_nearby.svg @@ -0,0 +1,7 @@ + + + HM/ic/24x24/ic_nearby + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_calendar.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_calendar.svg new file mode 100644 index 000000000..bfb163637 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_calendar.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_calendar + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_camera.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_camera.svg new file mode 100644 index 000000000..535b7a305 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_camera.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_camera + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_contacts_group.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_contacts_group.svg new file mode 100644 index 000000000..e01910786 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_contacts_group.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_contacts_group + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_folder.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_folder.svg new file mode 100644 index 000000000..01a9fae00 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_folder.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_folder + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_gps.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_gps.svg new file mode 100644 index 000000000..738516f85 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_gps.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_gps + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_message.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_message.svg new file mode 100644 index 000000000..79f77f671 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_message.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_message + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_phone.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_phone.svg new file mode 100644 index 000000000..df52fe39c --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_phone.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_phone + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_voice.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_voice.svg new file mode 100644 index 000000000..257ae0605 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_public_voice.svg @@ -0,0 +1,13 @@ + + + Public/ic_public_voice + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_sport.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_sport.svg new file mode 100644 index 000000000..e9ed5719d --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_sport.svg @@ -0,0 +1,7 @@ + + + HM/ic/24x24/s0324ok + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_ssensor.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_ssensor.svg new file mode 100644 index 000000000..51b9c504f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/ic_ssensor.svg @@ -0,0 +1,9 @@ + + + HM/ic/24x24/ssensor + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/icon.png b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c GIT binary patch literal 6790 zcmX|G1ymHk)?T_}Vd;>R?p|tHQo6fg38|$UVM!6BLrPFWk?s;$LOP{GmJpBl$qoSA!PUg~PA65-S00{{S`XKG6NkG0RgjEntPrmV+?0|00mu7;+5 zrdpa{2QLqPJ4Y{j7=Mrl{BaxrkdY69+c~(w{Fv-v&aR%aEI&JYSeRTLWm!zbv;?)_ ziZB;fwGbbeL5Q}YLx`J$lp~A09KK8t_z}PZ=4ZzgdeKtgoc+o5EvN9A1K1_<>M?MBqb#!ASf&# zEX?<)!RH(7>1P+j=jqG(58}TVN-$psA6K}atCuI!KTJD&FMmH-78ZejBm)0qc{ESp z|LuG1{QnBUJRg_E=h1#XMWt2%fcoN@l7eAS!Es?Q+;XsRNPhiiE=@AqlLkJzF`O18 zbsbSmKN=aaq8k3NFYZfDWpKmM!coBU0(XnL8R{4=i|wi{!uWYM2je{U{B*K2PVdu&=E zTq*-XsEsJ$u5H4g6DIm2Y!DN`>^v|AqlwuCD;w45K0@eqauiqWf7l&o)+YLHm~|L~ z7$0v5mkobriU!H<@mVJHLlmQqzQ3d6Rh_-|%Yy2li*tHO>_vcnuZ7OR_xkAIuIU&x z-|8Y0wj|6|a6_I(v91y%k_kNw6pnkNdxjqG8!%Vz_d%c_!X+6-;1`GC9_FpjoHev5fEV7RhJ>r=mh-jp$fqbqRJ=obwdgLDVP5+s zy1=_DWG0Y-Jb3t^WXmkr(d9~08k-|#Ly zaNOmT(^9tIb&eb4%CzIT zAm3CUtWSr1t4?h1kk#NBi{U|pJslvME{q|_eS^3En>SOqSxyuN1x;Is@8~m?*>}** znrRFArP!K_52RpX*&JHMR<^lVdm8ypJ}0R(SD(51j;6@ni$6bQ+2XL+R^|NnSp5}(kzvMZ^(@4fD_{QVu$(&K6H|C37TG1Am9Re{<<3gd zh@`>;BqkXMW&p0T6rt|iB$)~CvFe(XC)F9WgAZn*0@t$oZo;!*}r@_`h?KKH&6A@3= zISXoQB+~`op>NP-buiA*^0n{@i{_?MRG)&k)c)k_F+-2Lud!S9pc+i`s74NpBCaGF zXN+pHkubw*msGBTY27BKHv)RRh3;nMg4&$fD_6X9Vt~;_4D+5XPH~#Kn-yjcy!$}1 zigv#FNY>TqMhtIBb@UoF!cE~Q8~;!Pek>SQQwHnHuWKoVBosAiOr}q>!>aE*Krc)V zBUMEcJ5NU0g8}-h6i1zpMY9>m4ne?=U2~`w7K7Q0gB_=p@$5K7p6}thw z-~3dMj?YNX2X$lZ+7ngQ$=s}3mizNN@kE%OtB)?c&i~2L55z8^=yz;xMHLmlY>&Q# zJj?!)M#q_SyfkQh)k?j8IfLtB)ZCp|*vf4_B zos?73yd^h-Ac+;?E4*bpf=o*^3x3-`TVjbY4n6!EN10K6o@fxdyps05Vo3PU)otB} z`3kR+2w7_C#8Z!q`J)p{Vh!+m9-UP!$STp+Hb}}#@#_u^SsUQg<}59< zTvH3%XS4G+6FF^(m6bVF&nSUIXcl;nw{=H$%fgeJ>CgDYiLdpDXr{;-AnG z8dvcrHYVMI&`R6;GWekI@Ir3!uo)oz4^{6q0m^}@f2tM9&=YHNi6-?rh0-{+k@cQm zdp`g#YdQn%MDVg2GR>wZ`n2<0l4)9nx1Wfr&!Dvz=bPwU!h2S?ez6MVc5APE4-xLB zi&W9Q8k2@0w!C53g?iAIQ}~p*3O(@zja6KQ=M3zfW*_6o5SwR-)6VBh~m7{^-=MC-owYH5-u40a}a0liho3QZZ5L{bS_xM1)4}19)zTU$$MY zq3eZML1WC{K%YFd`Be0M-rkO^l?h{kM{$2oK1*A@HVJ57*yhDkUF!2WZ&oA4Y-sK( zCY69%#`mBCi6>6uw(x4gbFaP0+FD*JKJ-q!F1E?vLJ+d35!I5d7@^eU?(CS|C^tmI5?lv@s{{*|1F zFg|OzNpZ0hxljdjaW%45O0MOttRrd(Z?h{HYbB-KFUx&9GfFL3b8NwZ$zNu)WbBD` zYkj$^UB5%3Pj1MDr>S2Ejr9pUcgA!;ZG!@{uAy12)vG=*^9-|dNQBc8&`oxBlU~#y zs!anJX&T?57Jdr^sb>e+V`MVfY>Y0ESg7MG<7W0g&bR-ZYzzZ%2H&Etcp zcd6QeXO1D!5A#zM0lx*GH}`M)2~ZFLE;sP^RSB5wVMNfiZXPd(cmO>j=OSA3`o5r& zna(|^jGXbdN7PK)U8b7^zYtYkkeb%<%F~=OqB~kXMQkq}ii|skh@WSRt>5za;cjP0 zZ~nD%6)wzedqE}BMLt~qKwlvTr33))#uP~xyw#*Eaa|DbMQ_%mG0U8numf8)0DX`r zRoG2bM;#g|p-8gWnwRV5SCW0tLjLO&9Z?K>FImeIxlGUgo0Zk`9Qzhj1eco~7XZy+hXc@YF&ZQ=? zn*^1O56yK^x{y}q`j7}blGCx%dydV!c7)g~tJzmHhV=W~jbWRRR{1<^oDK+1clprm zz$eCy7y9+?{E|YgkW~}}iB#I4XoJ*xr8R?i_Hv$=Cof5bo-Nj~f`-DLebH}&0% zfQj9@WGd4;N~Y?mzQsHJTJq6!Qzl^-vwol(+fMt#Pl=Wh#lI5Vmu@QM0=_r+1wHt` z+8WZ~c2}KQQ+q)~2Ki77QvV&`xb|xVcTms99&cD$Zz4+-^R4kvUBxG8gDk7Y`K*)JZ^2rL(+ZWV~%W(@6 z)0bPArG#BROa_PHs~&WplQ_UIrpd)1N1QGPfv!J(Z9jNT#i%H?CE6|pPZb9hJ1JW4 z^q;ft#!HRNV0YgPojzIYT`8LuET2rUe-J|c!9l4`^*;4WtY@Ew@pL>wkjmMgGfN7 ze}}GtmU0@<_#08~I-Suk=^*9GLW=H4xhsml;vAV{%hy5Eegl@!6qKqbG024%n2HHw zCc@ivW_$@5ZoHP70(7D+(`PvgjW1Pd`wsiuv-aCukMrafwDm)B!xXVy*j2opohhoU zcJz%ADmj>i3`-3-$7nQKBQQuGY;2Qt&+(L~C>vSGFj5{Mlv?T_^dql;{zkpe4R1}R z%XfZyQ}wr*sr>jrKgm*PWLjuVc%6&&`Kbf1SuFpHPN&>W)$GmqC;pIoBC`=4-hPY8 zT*>%I2fP}vGW;R=^!1be?ta2UQd2>alOFFbVl;(SQJ4Jk#)4Z0^wpWEVvY4=vyDk@ zqlModi@iVPMC+{?rm=4(n+<;|lmUO@UKYA>EPTS~AndtK^Wy^%#3<;(dQdk3WaUkRtzSMC9}7x2||CNpF#(3T4C)@ z$~RWs`BNABKX|{cmBt>Q=&gkXl&x!!NK_%5hW0LS)Z4PB>%sV?F-{Wyj#s7W%$F{D zXdK^Fp3wvy+48+GP6F_|^PCRx=ddcTO3sG;B23A49~Qaw31SZ0Rc~`r4qqt%#OGW{ zCA_(LG5^N>yzUn&kAgVmxb=EA8s&tBXC}S1CZ(KoW)(%^JjLTPo^fs`Va;`=YlVPgmB$!yB}<(4ym6OeZ3xAJJ#;)2+B%p3P1Wt+d$eo`vz`T zXfUP2))kBDPoscH;Jc7I3NU<({|@wM$&GaDt`n7WLgIY3IA7A6-_R?z8N3mz|}*i z(zl5ot--Oq@f2-nv{X(ujT2T(k1vY_qh93pK@>H-qc%2Xta)IP0Q%zt%bqYgI`o!wv!0QerB`nCN^1n|@$sVOQ!V0teVG!I z_fD%JvfDeT1cK#-{o6Gv7}& zY0#NWin~kVaf$aufV&;63Hbs|`QVZWpDX6IMk1Hj2G}fiH9e-^6u2zf^FIr^BwD<6zjw63+{yUe8PUFvk8v{sJ=R{d#`O!sz`Q13~< zPT$JS(w=yQfU2`zPCNfSw=&zup@DXc(98afjhv@1w_f!m2Z>rMJ19AB&dB%P#Ls3b z=lK7OILM+SQ&VEd=1GN6o&>YVVtIzoZ%=Z_SdqJN2}E43{bE`>w+A;=y->@^k{oCC z$F*WTY&?34;kfyFV?b*Xb1Pq`Z=%OgwEg)Rz)tx=`f%5#w_INP=x&z5!jI;#;N$ma zhO)+MDm;SxOEVL15; zGq(v2pL3&P1Sl)8P*;G-fd{l1QJsv@e@d8)1PK4w2m*M%V3j-V~L^$i|&C@b?D?9tfwE{B^}Z$k8e5FmQ>v7Xz)sG32g9t}YBt zyR$+*_00RmPx+0mW+vVG4mxd(n$(eQf3-w>JPl2UJpafrPaL5@2j}%{VE-) zBI%6Qpj*dsdH<;g!S!avA~bv^0E+ zfyJbSjPb+j;J52U)<|cIcntQBI2T#>2;tOxu{%D?kML476AErF(qN9hPva5Nkc@BF zC-tLF@3ZFb%Kpj)M<{)x*l|*Ia@ECeXo2E4h2f!aV=cHAhi_E_mfUth(sM4^hJq7B zQsGWqdZUm9S%F`$nQ*_#NcuD`&)Ek%_s{&^78{9Hm ztri&rYLOxgFdG>O@+XHy z9#;|&vBCPXH5Mon^I`jSuR$&~ZWtyB67ujzFSj!51>#C}C17~TffQ{c-!QFQkTQ%! zIR^b1`zHx|*1GU?tbBx23weFLz5H?y_Q%N&t$}k?w+``2A=aotj0;2v$~AL z{scF-cL{wsdrmPvf#a9OHyYLcwQD4Kcm)`LLwMh4WT~p29f7M!iafJSU`IV}QY5Wa z(n44-9oA}?J{a+ah*@31WTs#&J#o1`H98#6IQf;Wv0N_!);f&9g7o-k(lW5rWnDUR zQBFIRG+X=6NnsI@mxnwm;tf5;_Uxg?jZ8m-m0}&6+DA!qam(p$mN5R})yA_7m$q@| zFEd|dpS595rxQr-n#GjI5i-AhnUE>Cr;jpCqSrD~EwK_DqI^7%3#p5)%T_od!t3SOmH9MyXeeGO2(UQL;ax|x?Ncixmeo1=$ z{-);Au{*tfzOG?KQ~K|ak8-HQ?`Pekhe2WM(8s{xv-p>Zmu_6{G!-oE$7$mY`MOJorI=+mMx?H;`pr!;fVYz?5~yXBACruWB`Ph zZM}90_<^OBxIhyZ9BW$`>6JvO;%VFpqVr8|7t3~AmxYak6?`Pp#c;**_SYmi`&z23 z`p6_~ePvH)C6x-G9$hgL=eVALq`-AiamN>!3~Lxw&{H(b{B(7xSRm6<3<{%{yXiH# zos5Rv1L+8fUKJLo%P>4I&$}y + + HM/ic/24x24/in-app installations + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/left.png b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/left.png new file mode 100644 index 0000000000000000000000000000000000000000..3d2329c71504881e33df1d7a687002934cd01daa GIT binary patch literal 1070 zcmbu9{ZCs}7{{O6TS_UzT^KSXSUN(LE%M@qVt~?HDAKwNCeFPuU^OEQ!gyIq9Bz|) zTiC)@UK}`Jo36-UHBpNgHnyP!q(jtLYnwPsV1?EwL`J!epI0jt2WpERPY+Z) zs|YX$YK9jR?L{nD!s2BPsU!)BJF zLOt@<$&~pWH+fwK`4>-gy{v-0_Q&C1>_aORvru>~&Og0039MC3(hzVbx5#DjB5 zjPe5}^+7Ap-18n*K>BRVS)Qbh=Dq@|IUb$zA;Y}PM)jh9%2%U+V>d{uGozow1boX^lp;- zu5B?_u-35775O(*CL zQJ8c4X2443GAq}0-t3fg71<~Ib*lqDwtO~^|8?IUx!w?9K9j3i*av!yC}4Y3#1>+x zxZ!w}$WQUTpq(mNdV4^k64x$qT6lxX`u*u+?e%BYSSgT1Qc?5qD?Cs%SNQvqI{*}; z^wHMAP!Qg!Oq*i+G0%TWEcL89*EYc&$k$7wxPm>xc65c0l7cF$N6VI zy4G}8+FIcUeCaDG=Wa=Xs1c^IlfMF)c&L|gu>kss%dIl=cH~yr(RrR^J_z_92P;vh zMc9J`FY+$~-Hq!@fwYG!l+Y(!Qm;+b9vhd%@1jHaRWY*X%qou#&0gm6UPtr9dc@MH zU$Dr`W{1IHt@N6}hUdxX|LC|ZiP)QVZ!9&H_3bfMI&rl`GQ1hF>}Bq6b5#GVmi z6r~7i2DPcto_f<>@B5yf>pIW<>3P20zw5sqeFHt!YqkM^00062I5|0?P$&cfAuTP9 z_6GRh13FuHbu&QAB+kUIjseV5-QGt)kID>^;N9 z2Uw)j3&Of%(^%G7Ls+^JwMxIi!DA+&HdA|Gd=tXqZQ}7#$p3C2PjIM0xPPRpcZ^i5 zS3KNJ@Eu1)YFavfCR+qF=WPNaj4!(=Dq6mnrvR7x7y~PbtH#^#=AXqjl;%lRWD(js z?3=rhJtP!btN&cpP@@l93sc+p`_9Qxma&=M8qPXm3Iwx4{;(4I#v&a*>&agkKswFGq^IKv?$mBUj zdk`s68e8s^wt1;FmHGL50o&c@##x6C_C{Wuv)AX=J~*qiDuz~nWE`ma`jm2y8Af(y zyyG~QWQ1endRW5sg>$Gt-3?>ii^opZxXzQZjB0Qc0%Z4=^29#>V_ScT3ujrNWwZ8S zoV$OaYuzl8U}6WM(jQHpRi_ZHJ?DQ|x;&7p9VKK^U$rufx?9|(1$Q63`|NV3pNFd1 z`bBZu86ic^&kF*7ygoS1G5Y4!Y^ybEj=6x_PO#eLo3{@iczdpPPhKtcu-@298okuy zHDu}QwMAGv)mJ-x$2+Zg^yO3b`1ZF)yZR&Yxt;fan|2#B}mqae^;xB?`q6zvwK;i#_Zqf{HP+hw&vuGn}n5~j6dEdfe&1+4jc}->J zh4Uv3)PY!_S=@0R0Ic~^Rfku<=VD|}->B&j6*?hsUHhR!oXp-MUEA`Asr@W1hyC>5 zk6+D^&Sy|zt@Cm|ATM5se2}yYUs!kqUkC@}ZOl`sUsQmSk1uZ=8(bB}lg%2P=b055 zpQeGhh+!|pqPUSP6_r)&c&1!UCY-`0p4#gf)n#X!np^7GQp!u%=tt-S``bF+vyP4$ zjq6XIr7UJ@1hJ&KEOdm48(12lL3Do`U-+M#jKFlojjC%`m%rPf zUT4{7i>~B3{fUOl3@{iE9Xc%g)*c`NU0aT`fW)7ibboLfX@!}ip%cp2wH`YE;FM>( z0G&GZ?ux^9YNlH7yb*q&2`aPe`O4Q7BIl$d?85D*6doZK92Fho%^%5?keI}q!s_R* z9G)DX8hQ|X;b2ORj*~*wIG-1`!@Y*h1+eMzvW`=l_?;U>#2^Q~+x{GmE7x^=+2d(B+@;PCzXZ-3E`YtL#1 zsj_rw6Secy!p;c7g2CEzI+04Uj_nVI&Wm3J@3?MN7;n zc7wjc4XH>&ml4>$W3M}2EAIfPCvGx`eQPCEnq;X0zaBsEiQn}w2KFae8*;(RSH#ae zAn@H&M<|mglQ%3j=ygm&96TWr6z!i8c{w;mj;@eSJw&poNDWzBQle5ST8_sVOW_G< zDk zy|cTw|K;HD==d1$*Y^_uJy2P^EVtD^_nfqHtwUaWV1ke#!=NjoJ>&u_N1r6Unbt2@ zOaV+Zm))mf`3$aa*v;=TkO>`Jedo3`yY$XhDh7#0pe-xn2^AI0V@omNt_>dbIg*l9 zY*B*e-BDH+FjGDGbOCdT;g|H@ix>u*z<4}!cn&%Jt#v1A>@$9Vp)^*wqCN{VqyE(o z9N_93{Mbh#GdMb+h2L^}U508v00>%LaAEyvgGZR^}Gc=DSF3nR{ zW-ULjZ){SwcgFYj*Y-c%KmPjd@Mt{Ah&wX3#v^~p9Q;erm;!|V3t;6(bG{AkY%jw4|ynO=n4)E~`_H+w#v8P!F78@52Phg@; zrhA@}{vJo99Eer|R6)7sMJqlJxr>bCXD=l$caHb>vr zsqA9I146Y@XMVZ820-J#t~mN}d$SmW;>N41g5@V%67DufG1MoxhpUE8-#k+Ihqg3it3xYOUb^ocf=^d=TcJ{r{b>@5fKT|j)_tCjE9G7Iwhw-(_XU!@&E#vsajTi2n4d= zHU`6AP-t9QT#hxV&MT=ks?TposjC;OsOk{yY9jVDf}3d*VxW(lX*f7U(*HOyHc~A= zsY{t|n;Kn$Q$Nkk-&&N~)Y{&e(b->xEv(2be_Qu5wmUG44fge7Bbigf^7z78nfZJH zFYSUE{>}(tfayOF)XTUDjTbJ6YR%gUqYHr;-=4lJsBN3 z7uXYJ<$gC=#h{>m34F~w6-&23IVwLyXWOzmyKsKRBIZtEH(%wT4)IGTR+<$37c$4dG;jM#|Kb zsm<6p&ubKRH_k59aPV<=^t+`+%f^}zIVUpjK#KydiU>e{OMB{7y#B8FhG3*|SJps^ zWmMzq=0=B0QIDD_LvE&WzR$RU;XodLhy_E4RaiuLWRyj092XqU9Tjav;}ntTf1Ab$ zO5+srlat<0PPcw?(xPz^s#E>RN$D3(!8qX_;a;DQ6Ez}~C%&M`spjd$rB8D!;@u)N zP9np^^^LJFYvQ}dE+6)u+$ZZ?_j5M;Mo%@c0fip103CIld30r%<(Ya=+iFpF;@0LPo=X;3Ys)!ZqqRBLpG1_ z|6;D|r*MH7mfq3y+Sw8n&eO5-i(6@MxzaPv2Wq$*!{jgOU$8UFUws1t->3t_fO_6E zA?bSFjE>fE)`|~@K{S(7QtxYL#E8)6)8EOBKp^wYicq{5%Z#tZl3BY?W;%lX~$6AI6Ho6O$c!)97aXxq0HJCE<~k4E4{t?^U*R zc9iz^<24VD@@{@}5eKk0dP| zU!Glxp|uR^XUkxFTgyv^kniSG<#t$S&M~rkMd;2mpi2N57X*}Rkly){v~AXfyuzXL-uiAHZ5cy7NIOK1$VKC(y|nEWpW8Vr=rpd zuSnlQf1yFHwUrBdwX5rV(T(12a=99X(3QNcc+X;5#+Z4-4y%NITf*6doAwI^0D$^`07`+R{{R30 literal 0 HcmV?d00001 diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noRecord.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noRecord.svg new file mode 100644 index 000000000..bc844b758 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noRecord.svg @@ -0,0 +1,20 @@ + + + EmptyPage/04 NoRecord + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noinstallationpackage.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noinstallationpackage.svg new file mode 100644 index 000000000..5b10a66c6 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/noinstallationpackage.svg @@ -0,0 +1,17 @@ + + + EmptyPage/08 NoInstallationPackage + + + + + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/nopermission.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/nopermission.svg new file mode 100644 index 000000000..fe47a1df8 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/nopermission.svg @@ -0,0 +1,16 @@ + + + EmptyPage/18 NoPermission + + + + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radioactive.jpg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radioactive.jpg new file mode 100644 index 0000000000000000000000000000000000000000..55e2adeb54f5b48587302a9f8ed15d8d5e9b1834 GIT binary patch literal 2217 zcmbW1eN@s}8pnTtfN!OUW~TXumD;3ZGftuK7acjBKeRQzNWSnU#)W zBWt>B006a0KE@A`SErNCPASp>L#b zV7L;xnX!?f@ycT5lCMXha2O13h(sX2l>ASkeFC8L0XM)625|(SCA@X55N10fkjcl;j@W#C^PSYn`&>sFcg3TG>gp3IHC#YYWZHaq<8rC3%(`sF4!tH@eG$| zUc{cA(pz8Zf6Ah{n2mVzg1xV^tiV;JHh-%eVrvR5BdgNe}%ji<%z}=*575ctriZid| zfA4FtWOsVpDzG>?3i~pBW@3hQCCU7H^EqN_E2jk{Z;^tju3m?C>}zP#T;o_~EpFoD z8cAj&Oq`7BYgZr)wMl6If_XQv42}4 ziu13qUf5$-+y88PX>1|ZFL7P-e1g!k)|(j?HbJ3O3renM@$cPG9B>?n8JWT>W>j`< zoJO21N*=6a$;~OK#|ETvQS5z(=o$2h@FNaZ3)3Zoao>I}Mm=-NN~9+BP~PL0Qq<9! zqGi7sj+q)$^I*p8AkXA1>uFF%UT`=T=9Ok$>Q&?D=j$BXhED3`@Wj@nTqz-+MJZY~ z9ddls=Ph#+@9+B{@e7f?DM>BqIst9)Wp?`Sl`AI4oN|>cf^NR^~9~s_kD=MdGFhJQs3rgWM@KH=~N#Lm9SI-W$*Yhs2{7 zc=Yu@$1BZ2OVTs`|kc|^hpXsN(-Sla4? z=cVqD*L%`zZ58n4Kgzdukp(&55K0qqahe%jM>c}ONCiWUCQ24&h0r5jsqKA-E-t-_ zAKyzQLj&ppXdI|_USRa2cApbfcXDfwqMLdqYo60WZ03JFK|8u!!kM_tff70C^TR}m zpd*hEUM`4Yy;?IL({$;WlTYqG6}D3g$S~be&9C2WGnrx9F?N<3PiK4B&2L_qW^rtz z7APi|$X~|Ys@)}V;_bxT4>3!E10Y>4;%WiQN3i-|y%oyS2*$09XtR;oXiNL|*R9O! zE4g~9=x6r7-zb1EpUjJvmJPy|z9&Cj_Pr7nZ!K6uT0QMq1@c1fVa-Rc@^TH)%G~{) zE$JKghn5A?a5p}uDrrJ$Q~Q8{Nyxw7C&CJ)4vHr|DG{he*tcj`UE;3p?`F^v6ZiqjZr*yj*OLUT|3F zHCiPtEz0zdkZOSuBG05I!A6jkoT&`Q|My~dY<{Y`SmBdcI2N~Knzj< literal 0 HcmV?d00001 diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radiodefault.jpg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/radiodefault.jpg new file mode 100644 index 0000000000000000000000000000000000000000..189d3ae2322a419ac0dc886fa6f4797daa651f10 GIT binary patch literal 1313 zcmex=iF;N$`UAd82aiwDF383NJD#LCRf%Eivc4pu@E@&5pWAP0jUgB~-Z5(ASU zBeNjm|04|YKzFi&odL?6mQqXwbzED#l4gO`Kd};u4Zls%q*Qnp!5NX66=_R?aT2 zZtfnQUcn)uVc`*xQOPN(Y3Ui6S;Zx#W#tu>Rn0A}ZS5VMU6UqHnL2IyjG40*Enc#8 z+42=DS8dw7W$U)>J9h3mboj{8W5-XNJay^vm8;jT-?(|};iJb-o<4j2;^nK4pFV&2 z`tAFVpT9u3cne5k^_L*fUreAlU=!0ld(M2vX6_bamA3_(y$p_- zkL7!!R%DjkZ~iuI<(`gXJ0GRC-mDhd;AnUG?W`Gp96wI$|6FnSVeA{jdeM8m71J-O zUv=>8_|H&gRJ(eWLLV=~#0wW#q~vxl`7zn6Ip)Gwj=VST77Ink+&;NeCHRii_PE-| zr=|C|g}?o1en{+SZd}4WjmwXmTs}Nzdl*t6XZTqrVN;XUqusl?Z|Az5vwm&aGSRE? zajA`gEiXgiJ#({P^N;CsyeM~^shd-3>u2(6UzU#9t0U!#c_~V}eUD3=E&R_Q#8Rc+ zTciEha>3st<&$1+-`xCfrCtb&`rpY~Zk%r?#?~@;x{3s_gqwZz7j`tsdhyCxo2Q9C zAba``3H9wi{1?6a9yC2$J8g5At(U`FuJkK!T~EHNTzg*Z$E3@LFvZDOqvx!Tx-mI+@?J|Ao^Wfa$ni(h9rDuF)YB1g7z94g- z=B4Ey{;kj19CgPnsA5iv(Y!@FdAX0>I)C`*{6qg4L=rM`7R+#7@}vI@zwD9d@cj9G z2?a;iMQh!5yu+Ql?mq+bIxWpbeWiwHrFK1kx8cMB*0zeLooP+36?al)`5fgIT&wS@ z$$se1azkzTqx*u9ncLngxX$|ZG%3h`x75k`50)R+%#(X||1fu2YVM_FGfQssf7-4^d-64$3X>)dbY^X5Nrfh{WY*Yso7d(9(0vUOK3 z&8W(K9drBT^iyKFP9>?I)F)OQmlAll;^w_b$)>jl-yJy4wD{Ql>9$tIK>_UlZvp_{ Cav1vn literal 0 HcmV?d00001 diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/rightarrow.png b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/rightarrow.png new file mode 100644 index 0000000000000000000000000000000000000000..51aad9fae9c47616835ecc4841028e1c887565e8 GIT binary patch literal 1058 zcmV+-1l{|IP)Px&+(|@1RA@uhnN5fsMHq(PZ+bm=@ZiA(4=#A{ASig)g9i^DJmesB*U$C@H)x2W z5`zQ@K|)YNkRU-82^vPxprYbHRqdaOL4pJk2@)it1Q7`me^60TamAkLPd;eD%Q~|& z)jhL)YUrx&=c#(Ty7-!~%@2yf@0{xp(amL9?y=ThjB(Fl?-5Jj2_kwNz=b49Oq!-& z4ht}DyC?zz5kff1%!dJ-CnBSix->4_F#V$m$iuw%#{fJE;2bj>W6b4YAjWAERiKhM z4&VSYe+a-DW4;>)a8Tdq0#%%rn0Y^dv%Ox==6U|(Adpe7*CJ3!oM7gC0M2Y|Y}m!c z#a~8+{J(y+2~=@93E)8hr;{YHX`22XTcTEhO5z0o_Yu+CMNvqcHeyQDE>Okk6f^Gz zusSz4XXoeVi&zqk2vjriDu7+G+A5_i5pfKO#sn&fHvsGe(A8SEx19hpQwX6e-v=Uk zT`9FVu0*3VAh4ZI=Ze|c*)B6@0AA5r-!qOx;{pQP?RKx6nVFH9xD&ujTI+j9m6(Wt zz^<&UT-ERQMPdgLJ+G8{U=)do2?*@^`uf#HQAnKbVCIv?n7vz-n5aM%r)#P>-OkJ> zj4=;yMPlLt0_&W+mWU)yw*gqvT0b(Z#8e0f?DF#Rb!AzK#H|31Ypo9sBQZ4s0=v4p zdcC~Z%sfv-$COfs21!hnfWWS;t=-V;^+e(pB08#+dTe6b=|Q8n*>&&zjq zWQ=)kv$j(=1J#~MM*WDKmu0!bTKn#{5eOk1W@f2yl&w}PS4z2U6Cvl^AtHJbK#!So zV@wzn!>Ngo_g=~|QkMA}K(4i383Zrar$QivaFCgwV&=b+B+0WZTN?&`Dg?au2js&A z;Lj>HZw(7SaRKkWY#E*g@COme3;WJi;3p~&LfFsDO8|b8)h5fbO_$24TZO#$vg3RP zz_0y&zrC=qaC)mF|8M)oU*ZtLKG`+{__-|0wzc-XQQ;epkaKP?5j_jwCjf1&^_g+t z8x`>0ONmiRjXzYed4F8^#soqL_cL<`!1v7DHpZNd0pEy#b581_QXl=cip>YH;Aol%tukltDDs#;Jv>az{>zG5m8$y zb*>KhS|Sue*u~6JiT)}{l6IP=AJ+vRUBEea7ZJV2%<`XDVspMu_^1Njdnubs`TUD2 zHlNfDA59>HkTdg}04`RsxzGfBOo4A?V^$Q!&OFaQZ3;e`fcJi(EX&WWwVyQ!A5EZX c=>I4T>t<807*qoM6N<$f~)T41cdvEP)Px(HAzH4R9Hv7mtSZcRTRd*GrQV08Y)vx0o4p%FL_|f+LnSDpd9c3K+L?7Tvnv5DXyUGOM0o&=ySr!?7@Q^W8P^#4YNa4u0aRf<2+$z_cZCf~;N!~L=<|gg$-l#U zIw)0PPXHJX8^ot$zThblqm&u=DU5$f1=O5<5{&(RGhGIA7QhT4I#XE_wIhp*BSbvn zfrbg3X-`&GNS{w@`Q;#d05Or@Md0_^Ow$TQo|(%ef9MuW%~@k$UK$h_@h*vRB?ijDu1C!Q6q|iqV zLqv((Sx6^;>=i&2`O^UJsrzSLL%$>V6r6Exz`C-W+c(vY0p4*l`s2L-ByxpekG-z} z?yvdjuxn_?0s*Q`le6CjjCLnrrF@+T(=k^7scAZ^d=d zQTA{<$@c<6KNA(?y8#2!MPu-br4_t%2vB_IpNQUaGTOdYZ76`y8_*_Us)#U2!*`I+foGk5Bo(r?al1ja~B!G?K=JwTD5c zTOfpM=;o>c$i%Tpdz=)=x2|gPRojBr(#Lao)5&OZ##EnGtw5(9`5#LUf-p}l^$Y+2 N002ovPDHLkV1oB;9~1xp literal 0 HcmV?d00001 diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/searchnoresult.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/searchnoresult.svg new file mode 100644 index 000000000..e948acc0b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/searchnoresult.svg @@ -0,0 +1,22 @@ + + + EmptyPage/05 SearchNoResult + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangshangjiantou.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangshangjiantou.svg new file mode 100644 index 000000000..24d372dc5 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangshangjiantou.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangxiajiantou.svg b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangxiajiantou.svg new file mode 100644 index 000000000..42116e213 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/media/xiangxiajiantou.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/profile/main_pages.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/profile/main_pages.json new file mode 100644 index 000000000..c2e856f09 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,13 @@ +{ + "src": [ + "pages/authority-management", + "pages/application-secondary", + "pages/authority-secondary", + "pages/authority-tertiary", + "pages/application-tertiary", + "pages/other-permissions", + "pages/authority-tertiary-groups", + "pages/permission-access-record", + "pages/dialogPlus" + ] +} diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/dark/profile/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/dark/profile/string.json new file mode 100644 index 000000000..ddc52a17f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/dark/profile/string.json @@ -0,0 +1,7 @@ +{ + "colors": { + "colorSubBackground": "#000000", + "appbar_subtitle_color": "#99ffffff", + "text_color": "#ffffff" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/en/profile/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/en/profile/string.json new file mode 100644 index 000000000..319b5d66e --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/en/profile/string.json @@ -0,0 +1,14 @@ +{ + "strings": { + "app_name": "CategoryPage", + "describe": "describe", + "category": "Category", + "itemChild": "ItemChild", + "item": "Item", + "search": "search...", + "you_search": "You search ", + "you_clicked": "You clicked ", + "tab": "Tab", + "more": "more >" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/light/profile/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/light/profile/string.json new file mode 100644 index 000000000..4b9482c8f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/light/profile/string.json @@ -0,0 +1,7 @@ +{ + "colors": { + "colorSubBackground": "#f1f3f5", + "appbar_subtitle_color": "#99000000", + "text_color": "#000000" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh/profile/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh/profile/string.json new file mode 100644 index 000000000..4ca364c62 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh/profile/string.json @@ -0,0 +1,14 @@ +{ + "strings": { + "app_name": "分类页", + "describe": "描述", + "category": "分类", + "itemChild": "子类", + "item": "类型", + "search": "搜索...", + "you_search": "你搜索了", + "you_clicked": "你点击了", + "tab": "分页", + "more": "更多 >" + } +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh_CN/element/string.json b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh_CN/element/string.json new file mode 100644 index 000000000..e92d068a4 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,92 @@ +{ + "string": [ + { + "name": "permissionmanager_desc", + "value": "权限管理" + }, + { + "name": "MainAbility_desc", + "value": "从权限和应用两个维度来管理所有应用申请的权限。" + }, + { + "name": "MainAbility_label", + "value": "权限管理" + }, + { + "name": "no_permission", + "value": "暂无权限" + }, + { + "name": "access_permission", + "value": "访问权限" + }, + { + "name": "permission_access_record", + "value": "权限访问记录" + }, + { + "name": "authority_management", + "value": "权限管理" + }, + { + "name": "other_permissions", + "value": "其它权限" + }, + { + "name": "application", + "value": "应用" + }, + { + "name": "authority", + "value": "权限" + }, + { + "name": "textInput_placeholder", + "value": "搜索应用" + }, + { + "name": "allowed", + "value": "已允许" + }, + { + "name": "banned", + "value": "已禁止" + }, + { + "name": "Authorization_failed", + "value": "授权失败!" + }, + { + "name": "reason_suffix", + "value": "等权限。" + }, + { + "name": "separator", + "value": "、" + }, + { + "name": "visits", + "value": "访问次数:" + }, + { + "name": "recent_visit", + "value": ";最近访问:" + }, + { + "name": "morning", + "value": "上午" + }, + { + "name": "afternoon", + "value": "下午" + }, + { + "name": "no_record", + "value": "没有权限访问记录" + }, + { + "name": "record_time_limit", + "value": "近7天访问记录" + } + ] +} \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/common/BUILD.gn b/security_access_token-yl_0822/frameworks/common/BUILD.gn new file mode 100644 index 000000000..3970b261d --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("accesstoken_common_cxx_public_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +ohos_shared_library("accesstoken_common_cxx") { + subsystem_name = "security" + part_name = "access_token" + + public_configs = [ ":accesstoken_common_cxx_public_config" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//third_party/mbedtls/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + + sources = [ + "src/constant_common.cpp", + "src/data_validator.cpp", + "src/random_mbedtls.cpp", + ] + + deps = [ "//third_party/mbedtls:mbedtls_shared" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "init:libbegetutil", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/security_access_token-yl_0822/frameworks/common/include/accesstoken_log.h b/security_access_token-yl_0822/frameworks/common/include/accesstoken_log.h new file mode 100644 index 000000000..8f0c43b2d --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/accesstoken_log.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_LOG_H +#define ACCESSTOKEN_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#ifndef __cplusplus + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#else + +#define ACCESSTOKEN_LOG_DEBUG(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Debug(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Info(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Warn(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Error(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Fatal(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#endif // __cplusplus + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG +#undef LOG_DOMAIN + +static constexpr unsigned int SECURITY_DOMAIN_ACCESSTOKEN = 0xD002F01; +static constexpr unsigned int SECURITY_DOMAIN_PRIVACY = 0xD002F03; + +#else + +#include +#include + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG + +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // ACCESSTOKEN_LOG_H diff --git a/security_access_token-yl_0822/frameworks/common/include/constant_common.h b/security_access_token-yl_0822/frameworks/common/include/constant_common.h new file mode 100644 index 000000000..8651f5d4e --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/constant_common.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FRAMEWORK_CONSTANT_COMMON_H +#define FRAMEWORK_CONSTANT_COMMON_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class ConstantCommon { +public: + /** + * Device id length. + */ + const static int32_t DEVICE_UUID_LENGTH = 65; + static constexpr int32_t MINDEVICEIDLEN = 8; + static constexpr int32_t ENCRYPTLEN = 4; + static constexpr int32_t ENCRYPTBEGIN = 0; + static constexpr int32_t ENCRYPTEND = 3; + static std::string EncryptDevId(std::string deviceId); + + /** + * GetLocalDeviceId + */ + static std::string GetLocalDeviceId(); +}; +} +} +} +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/common/include/data_validator.h b/security_access_token-yl_0822/frameworks/common/include/data_validator.h new file mode 100644 index 000000000..bea3c582a --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/data_validator.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_VALIDATOR_H +#define DATA_VALIDATOR_H + +#include +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataValidator final { +public: + static bool IsBundleNameValid(const std::string& bundleName); + + static bool IsPermissionNameValid(const std::string& permissionName); + + static bool IsUserIdValid(const int userId); + + static bool IsAppIDDescValid(const std::string& appIDDesc); + + static bool IsDomainValid(const std::string& domain); + + static bool IsAplNumValid(const int apl); + + static bool IsProcessNameValid(const std::string& processName); + + static bool IsDeviceIdValid(const std::string& deviceId); + + static bool IsLabelValid(const std::string& label); + + static bool IsDescValid(const std::string& desc); + static bool IsPermissionFlagValid(int flag); + static bool IsDcapValid(const std::string& dcap); + static bool IsTokenIDValid(AccessTokenID id); + static bool IsDlpTypeValid(int dlpType); + +private: + const static int MAX_LENGTH = 256; + const static int MAX_APPIDDESC_LENGTH = 10240; + const static int MAX_DCAP_LENGTH = 1024; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DATA_VALIDATOR_H diff --git a/security_access_token-yl_0822/frameworks/common/include/parcel_utils.h b/security_access_token-yl_0822/frameworks/common/include/parcel_utils.h new file mode 100644 index 000000000..d6b7e8b6b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/parcel_utils.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PARCEL_UTILS_H +#define PARCEL_UTILS_H +#define MAX_PERMLIST_SIZE 256 +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + if ((obj) != nullptr) { \ + delete (obj); \ + (obj) = nullptr; \ + } \ + return (obj); \ + } +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PARCEL_UTILS_H diff --git a/security_access_token-yl_0822/frameworks/common/include/random.h b/security_access_token-yl_0822/frameworks/common/include/random.h new file mode 100644 index 000000000..29d2e637f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/random.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_RANDOM_H +#define ACCESSTOKEN_RANDOM_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +unsigned int GetRandomUint32(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#endif /* ACCESSTOKEN_RANDOM_H */ diff --git a/security_access_token-yl_0822/frameworks/common/include/random_mbedtls.h b/security_access_token-yl_0822/frameworks/common/include/random_mbedtls.h new file mode 100644 index 000000000..d9461c734 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/include/random_mbedtls.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESS_TOKEN_RANDOM_MBEDTLS +#define ACCESS_TOKEN_RANDOM_MBEDTLS + +#include "rwlock.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RandomMbedtls { +public: + static RandomMbedtls& GetInstance(); + int GenerateRandomArray(unsigned char *randStr, unsigned int len); + ~RandomMbedtls() {} + static unsigned int GetRandomUint32(); + +private: + RandomMbedtls() : initFlag_(false) {} + mbedtls_entropy_context entropy_; + mbedtls_ctr_drbg_context ctrDrbg_; + OHOS::Utils::RWLock randomLock_; + bool initFlag_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKEN_RANDOM_MBEDTLS diff --git a/security_access_token-yl_0822/frameworks/common/src/constant_common.cpp b/security_access_token-yl_0822/frameworks/common/src/constant_common.cpp new file mode 100644 index 000000000..736a66ce0 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/src/constant_common.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "constant_common.h" +#include +#include "parameter.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static const std::string REPLACE_TARGET = "****"; +static const std::string REPLACE_TARGET_LESS_THAN_MINLEN = "*******"; +} // namespace +std::string ConstantCommon::EncryptDevId(std::string deviceId) +{ + std::string result = deviceId; + if (deviceId.empty()) { + return result; + } + if (deviceId.size() > MINDEVICEIDLEN) { + result.replace(ENCRYPTBEGIN + ENCRYPTLEN, deviceId.size() - MINDEVICEIDLEN, REPLACE_TARGET); + } else { + result.replace(ENCRYPTBEGIN + 1, deviceId.size()-1, REPLACE_TARGET_LESS_THAN_MINLEN); + } + return result; +} + +std::string ConstantCommon::GetLocalDeviceId() +{ + static std::string localDeviceId; + if (!localDeviceId.empty()) { + return localDeviceId; + } + const int32_t DEVICE_UUID_LENGTH = 65; + char udid[DEVICE_UUID_LENGTH] = {0}; + if (GetDevUdid(udid, DEVICE_UUID_LENGTH) == 0) { + localDeviceId = udid; + } + return localDeviceId; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/common/src/data_validator.cpp b/security_access_token-yl_0822/frameworks/common/src/data_validator.cpp new file mode 100644 index 000000000..80fde5efa --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/src/data_validator.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_validator.h" +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool DataValidator::IsBundleNameValid(const std::string& bundleName) +{ + return !bundleName.empty() && (bundleName.length() <= MAX_LENGTH); +} + +bool DataValidator::IsLabelValid(const std::string& label) +{ + return label.length() <= MAX_LENGTH; +} + +bool DataValidator::IsDescValid(const std::string& desc) +{ + return desc.length() <= MAX_LENGTH; +} + +bool DataValidator::IsPermissionNameValid(const std::string& permissionName) +{ + return !permissionName.empty() && (permissionName.length() <= MAX_LENGTH); +} + +bool DataValidator::IsUserIdValid(const int userId) +{ + return userId >= 0; +} + +bool DataValidator::IsAppIDDescValid(const std::string& appIDDesc) +{ + return !appIDDesc.empty() && (appIDDesc.length() <= MAX_APPIDDESC_LENGTH); +} + +bool DataValidator::IsDomainValid(const std::string& domain) +{ + return !domain.empty() && (domain.length() <= MAX_LENGTH); +} + +bool DataValidator::IsAplNumValid(const int apl) +{ + return (apl == APL_NORMAL || apl == APL_SYSTEM_BASIC || apl == APL_SYSTEM_CORE); +} + +bool DataValidator::IsProcessNameValid(const std::string& processName) +{ + return !processName.empty() && (processName.length() <= MAX_LENGTH); +} + +bool DataValidator::IsDeviceIdValid(const std::string& deviceId) +{ + return !deviceId.empty() && (deviceId.length() <= MAX_LENGTH); +} + +bool DataValidator::IsDcapValid(const std::string& dcap) +{ + return !dcap.empty() && (dcap.length() <= MAX_DCAP_LENGTH); +} + +bool DataValidator::IsPermissionFlagValid(int flag) +{ + uint32_t unmaskedFlag = + static_cast(flag) & (~PermissionFlag::PERMISSION_GRANTED_BY_POLICY); + + return unmaskedFlag == PermissionFlag::PERMISSION_DEFAULT_FLAG || + unmaskedFlag == PermissionFlag::PERMISSION_USER_SET || + unmaskedFlag == PermissionFlag::PERMISSION_USER_FIXED || + unmaskedFlag == PermissionFlag::PERMISSION_SYSTEM_FIXED; +} + +bool DataValidator::IsTokenIDValid(AccessTokenID id) +{ + return id != 0; +} + +bool DataValidator::IsDlpTypeValid(int dlpType) +{ + return ((dlpType == DLP_COMMON) || (dlpType == DLP_READ) || (dlpType == DLP_FULL_CONTROL)); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/common/src/random_mbedtls.cpp b/security_access_token-yl_0822/frameworks/common/src/random_mbedtls.cpp new file mode 100644 index 000000000..1a6ad4013 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/common/src/random_mbedtls.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "random_mbedtls.h" +#include "access_token.h" + +using OHOS::Security::AccessToken::RandomMbedtls; +using OHOS::Security::AccessToken::RET_SUCCESS; + +namespace OHOS { +namespace Security { +namespace AccessToken { +extern "C" unsigned int GetRandomUint32() +{ + unsigned int rand; + int ret = RandomMbedtls::GetInstance().GenerateRandomArray((unsigned char *)&rand, sizeof(rand)); + if (ret != RET_SUCCESS) { + return 0; + } + return rand; +} + +int RandomMbedtls::GenerateRandomArray(unsigned char *randStr, unsigned int len) +{ + if (randStr == nullptr || len == 0) { + return RET_FAILED; + } + int ret; + + Utils::UniqueWriteGuard infoGuard(this->randomLock_); + if (!initFlag_) { + mbedtls_ctr_drbg_init(&ctrDrbg_); + mbedtls_entropy_init(&entropy_); + ret = mbedtls_ctr_drbg_seed(&ctrDrbg_, mbedtls_entropy_func, &entropy_, NULL, 0); + if (ret != 0) { + return RET_FAILED; + } + initFlag_ = true; + } + + ret = mbedtls_ctr_drbg_random(&ctrDrbg_, randStr, len); + if (ret != 0) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +RandomMbedtls& RandomMbedtls::GetInstance() +{ + static RandomMbedtls instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/BUILD.gn b/security_access_token-yl_0822/frameworks/privacy/BUILD.gn new file mode 100644 index 000000000..e72102551 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("privacy_communication_adapter_cxx") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/frameworks/common/include", + "//commonlibrary/c_utils/base/include", + ] + + sources = [ + "src/bundle_used_record_parcel.cpp", + "src/perm_active_response_parcel.cpp", + "src/permission_used_record_parcel.cpp", + "src/permission_used_request_parcel.cpp", + "src/permission_used_result_parcel.cpp", + "src/used_record_detail_parcel.cpp", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] +} diff --git a/security_access_token-yl_0822/frameworks/privacy/include/bundle_used_record_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/bundle_used_record_parcel.h new file mode 100644 index 000000000..d94e185e8 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/bundle_used_record_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BUNDLE_USED_RECORD_PARCEL_H +#define BUNDLE_USED_RECORD_PARCEL_H + +#include "parcel.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct BundleUsedRecordParcel final : public Parcelable { + BundleUsedRecordParcel() = default; + + ~BundleUsedRecordParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static BundleUsedRecordParcel* Unmarshalling(Parcel& in); + + BundleUsedRecord bundleRecord; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // BUNDLE_USED_RECORD_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/i_perm_active_status_callback.h b/security_access_token-yl_0822/frameworks/privacy/include/i_perm_active_status_callback.h new file mode 100644 index 000000000..e473c656f --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/i_perm_active_status_callback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_PERMI_ACTIVE_STATUS_CALLBACK_H +#define I_PERMI_ACTIVE_STATUS_CALLBACK_H + +#include + +#include "access_token.h" +#include "active_change_response_info.h" +#include "iremote_broker.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class IPermActiveStatusCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.IPermActiveStatusCallback"); + + virtual void ActiveStatusChangeCallback(ActiveChangeResponse& result) = 0; + + enum { + PERM_ACTIVE_STATUS_CHANGE = 0, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMI_ACTIVE_STATUS_CALLBACK_H \ No newline at end of file diff --git a/security_access_token-yl_0822/frameworks/privacy/include/i_privacy_manager.h b/security_access_token-yl_0822/frameworks/privacy/include/i_privacy_manager.h new file mode 100644 index 000000000..c5dcc2eef --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/i_privacy_manager.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_PRIVACY_MANAGER_H +#define I_PRIVACY_MANAGER_H + +#include + +#include "access_token.h" +#include "errors.h" +#include "iremote_broker.h" + +#include "on_permission_used_record_callback.h" +#include "permission_used_request_parcel.h" +#include "permission_used_result_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class IPrivacyManager : public IRemoteBroker { +public: + static const int32_t SA_ID_PRIVACY_MANAGER_SERVICE = 3505; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.IPrivacyManager"); + + virtual int32_t AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) = 0; + virtual int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int32_t RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) = 0; + virtual int32_t GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) = 0; + virtual int32_t GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, const sptr& callback) = 0; + virtual std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) = 0; + virtual int32_t RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) = 0; + virtual int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) = 0; + virtual bool IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName) = 0; + + enum class InterfaceCode { + ADD_PERMISSION_USED_RECORD = 0xf001, + START_USING_PERMISSION = 0xf002, + STOP_USING_PERMISSION = 0xf003, + DELETE_PERMISSION_USED_RECORDS = 0xf004, + GET_PERMISSION_USED_RECORDS = 0xf005, + GET_PERMISSION_USED_RECORDS_ASYNC = 0xf006, + DUMP_RECORD_INFO = 0xf007, + REGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK = 0xf008, + UNREGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK = 0xf009, + IS_ALLOW_USING_PERMISSION = 0xf010, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // I_PRIVACY_MANAGER_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/perm_active_response_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/perm_active_response_parcel.h new file mode 100644 index 000000000..706d9fa4b --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/perm_active_response_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_RESPONES_PARCEL_H +#define PERM_ACTIVE_RESPONES_PARCEL_H + +#include "active_change_response_info.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct ActiveChangeResponseParcel final : public Parcelable { + ActiveChangeResponseParcel() = default; + + ~ActiveChangeResponseParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static ActiveChangeResponseParcel* Unmarshalling(Parcel& in); + + ActiveChangeResponse changeResponse; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERM_ACTIVE_RESPONES_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/permission_used_record_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_record_parcel.h new file mode 100644 index 000000000..c2a24dcce --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_record_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RECORD_PARCEL_H +#define PERMISSION_USED_RECORD_PARCEL_H + +#include "parcel.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionUsedRecordParcel final : public Parcelable { + PermissionUsedRecordParcel() = default; + + ~PermissionUsedRecordParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static PermissionUsedRecordParcel* Unmarshalling(Parcel& in); + + PermissionUsedRecord permissionRecord; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_USED_RECORD_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/permission_used_request_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_request_parcel.h new file mode 100644 index 000000000..e0146d521 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_request_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_REQUEST_PARCEL_H +#define PERMISSION_USED_REQUEST_PARCEL_H + +#include "parcel.h" +#include "permission_used_request.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionUsedRequestParcel final : public Parcelable { + PermissionUsedRequestParcel() = default; + + ~PermissionUsedRequestParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static PermissionUsedRequestParcel* Unmarshalling(Parcel& in); + + PermissionUsedRequest request; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_USED_REQUEST_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/permission_used_result_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_result_parcel.h new file mode 100644 index 000000000..40e3d01fd --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/permission_used_result_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RESPONSE_PARCEL_H +#define PERMISSION_USED_RESPONSE_PARCEL_H + +#include "parcel.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionUsedResultParcel final : public Parcelable { + PermissionUsedResultParcel() = default; + + ~PermissionUsedResultParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static PermissionUsedResultParcel* Unmarshalling(Parcel& in); + + PermissionUsedResult result; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_USED_RESPONSE_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/include/used_record_detail_parcel.h b/security_access_token-yl_0822/frameworks/privacy/include/used_record_detail_parcel.h new file mode 100644 index 000000000..8922fc222 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/include/used_record_detail_parcel.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USED_RECORD_DETAIL_PARCEL_H +#define USED_RECORD_DETAIL_PARCEL_H + +#include "parcel.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct UsedRecordDetailParcel final : public Parcelable { + UsedRecordDetailParcel() = default; + + ~UsedRecordDetailParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static UsedRecordDetailParcel* Unmarshalling(Parcel& in); + + UsedRecordDetail detail; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // USED_RECORD_DETAIL_PARCEL_H diff --git a/security_access_token-yl_0822/frameworks/privacy/src/bundle_used_record_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/bundle_used_record_parcel.cpp new file mode 100644 index 000000000..529c386e1 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/bundle_used_record_parcel.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bundle_used_record_parcel.h" +#include "refbase.h" +#include "parcel_utils.h" +#include "permission_used_record_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool BundleUsedRecordParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteUint32(this->bundleRecord.tokenId)); + RETURN_IF_FALSE(out.WriteBool(this->bundleRecord.isRemote)); + RETURN_IF_FALSE(out.WriteString(this->bundleRecord.deviceId)); + RETURN_IF_FALSE(out.WriteString(this->bundleRecord.bundleName)); + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->bundleRecord.permissionRecords.size()))); + for (const auto& permRecord : this->bundleRecord.permissionRecords) { + PermissionUsedRecordParcel permRecordParcel; + permRecordParcel.permissionRecord = permRecord; + out.WriteParcelable(&permRecordParcel); + } + return true; +} + +BundleUsedRecordParcel* BundleUsedRecordParcel::Unmarshalling(Parcel& in) +{ + auto* bundleRecordParcel = new (std::nothrow) BundleUsedRecordParcel(); + RELEASE_IF_FALSE(bundleRecordParcel != nullptr, bundleRecordParcel); + + RELEASE_IF_FALSE(in.ReadUint32(bundleRecordParcel->bundleRecord.tokenId), bundleRecordParcel); + RELEASE_IF_FALSE(in.ReadBool(bundleRecordParcel->bundleRecord.isRemote), bundleRecordParcel); + RELEASE_IF_FALSE(in.ReadString(bundleRecordParcel->bundleRecord.deviceId), bundleRecordParcel); + RELEASE_IF_FALSE(in.ReadString(bundleRecordParcel->bundleRecord.bundleName), bundleRecordParcel); + + int32_t permRecordSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(permRecordSize), bundleRecordParcel); + for (int32_t i = 0; i < permRecordSize; i++) { + sptr permRecord = in.ReadParcelable(); + RELEASE_IF_FALSE(permRecord != nullptr, bundleRecordParcel); + bundleRecordParcel->bundleRecord.permissionRecords.emplace_back(permRecord->permissionRecord); + } + return bundleRecordParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/src/perm_active_response_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/perm_active_response_parcel.cpp new file mode 100644 index 000000000..49617f9d7 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/perm_active_response_parcel.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "parcel_utils.h" +#include "perm_active_response_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool ActiveChangeResponseParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteUint32(this->changeResponse.tokenID)); + RETURN_IF_FALSE(out.WriteString(this->changeResponse.permissionName)); + RETURN_IF_FALSE(out.WriteString(this->changeResponse.deviceId)); + RETURN_IF_FALSE(out.WriteInt32(this->changeResponse.type)); + return true; +} + +ActiveChangeResponseParcel* ActiveChangeResponseParcel::Unmarshalling(Parcel& in) +{ + auto* activeChangeResponseParcel = new (std::nothrow) ActiveChangeResponseParcel(); + if (activeChangeResponseParcel == nullptr) { + return nullptr; + } + + RELEASE_IF_FALSE(in.ReadUint32(activeChangeResponseParcel->changeResponse.tokenID), activeChangeResponseParcel); + RELEASE_IF_FALSE(in.ReadString(activeChangeResponseParcel->changeResponse.permissionName), + activeChangeResponseParcel); + RELEASE_IF_FALSE(in.ReadString(activeChangeResponseParcel->changeResponse.deviceId), activeChangeResponseParcel); + + int32_t type; + RELEASE_IF_FALSE(in.ReadInt32(type), activeChangeResponseParcel); + activeChangeResponseParcel->changeResponse.type = static_cast(type); + return activeChangeResponseParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/src/permission_used_record_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_record_parcel.cpp new file mode 100644 index 000000000..135e4a918 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_record_parcel.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_record_parcel.h" +#include "refbase.h" +#include "parcel_utils.h" +#include "used_record_detail_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionUsedRecordParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteString(this->permissionRecord.permissionName)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionRecord.accessCount)); + RETURN_IF_FALSE(out.WriteInt32(this->permissionRecord.rejectCount)); + RETURN_IF_FALSE(out.WriteInt64(this->permissionRecord.lastAccessTime)); + RETURN_IF_FALSE(out.WriteInt64(this->permissionRecord.lastRejectTime)); + RETURN_IF_FALSE(out.WriteInt64(this->permissionRecord.lastAccessDuration)); + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->permissionRecord.accessRecords.size()))); + for (const auto& accRecord : this->permissionRecord.accessRecords) { + UsedRecordDetailParcel detailParcel; + detailParcel.detail = accRecord; + out.WriteParcelable(&detailParcel); + } + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->permissionRecord.rejectRecords.size()))); + for (const auto& rejRecord : this->permissionRecord.rejectRecords) { + UsedRecordDetailParcel detailParcel; + detailParcel.detail = rejRecord; + out.WriteParcelable(&detailParcel); + } + return true; +} + +PermissionUsedRecordParcel* PermissionUsedRecordParcel::Unmarshalling(Parcel& in) +{ + auto* permissionRecordParcel = new (std::nothrow) PermissionUsedRecordParcel(); + RELEASE_IF_FALSE(permissionRecordParcel != nullptr, permissionRecordParcel); + + RELEASE_IF_FALSE(in.ReadString(permissionRecordParcel->permissionRecord.permissionName), permissionRecordParcel); + RELEASE_IF_FALSE(in.ReadInt32(permissionRecordParcel->permissionRecord.accessCount), permissionRecordParcel); + RELEASE_IF_FALSE(in.ReadInt32(permissionRecordParcel->permissionRecord.rejectCount), permissionRecordParcel); + RELEASE_IF_FALSE(in.ReadInt64(permissionRecordParcel->permissionRecord.lastAccessTime), permissionRecordParcel); + RELEASE_IF_FALSE(in.ReadInt64(permissionRecordParcel->permissionRecord.lastRejectTime), permissionRecordParcel); + RELEASE_IF_FALSE(in.ReadInt64(permissionRecordParcel->permissionRecord.lastAccessDuration), permissionRecordParcel); + + int32_t accRecordSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(accRecordSize), permissionRecordParcel); + for (int32_t i = 0; i < accRecordSize; i++) { + sptr detailParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(detailParcel != nullptr, permissionRecordParcel); + permissionRecordParcel->permissionRecord.accessRecords.emplace_back(detailParcel->detail); + } + + int32_t rejRecordSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(rejRecordSize), permissionRecordParcel); + for (int32_t i = 0; i < rejRecordSize; i++) { + sptr detailParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(detailParcel != nullptr, permissionRecordParcel); + permissionRecordParcel->permissionRecord.rejectRecords.emplace_back(detailParcel->detail); + } + return permissionRecordParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/src/permission_used_request_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_request_parcel.cpp new file mode 100644 index 000000000..e4eac2bce --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_request_parcel.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_request_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionUsedRequestParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteUint32(this->request.tokenId)); + RETURN_IF_FALSE(out.WriteBool(this->request.isRemote)); + RETURN_IF_FALSE(out.WriteString(this->request.deviceId)); + RETURN_IF_FALSE(out.WriteString(this->request.bundleName)); + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->request.permissionList.size()))); + for (const auto& perm : this->request.permissionList) { + RETURN_IF_FALSE(out.WriteString(perm)); + } + RETURN_IF_FALSE(out.WriteInt64(this->request.beginTimeMillis)); + RETURN_IF_FALSE(out.WriteInt64(this->request.endTimeMillis)); + RETURN_IF_FALSE(out.WriteInt32(this->request.flag)); + return true; +} + +PermissionUsedRequestParcel* PermissionUsedRequestParcel::Unmarshalling(Parcel& in) +{ + auto* requestParcel = new (std::nothrow) PermissionUsedRequestParcel(); + RELEASE_IF_FALSE(requestParcel != nullptr, requestParcel); + + RELEASE_IF_FALSE(in.ReadUint32(requestParcel->request.tokenId), requestParcel); + RELEASE_IF_FALSE(in.ReadBool (requestParcel->request.isRemote), requestParcel); + RELEASE_IF_FALSE(in.ReadString(requestParcel->request.deviceId), requestParcel); + RELEASE_IF_FALSE(in.ReadString(requestParcel->request.bundleName), requestParcel); + + int32_t permSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(permSize), requestParcel); + for (int32_t i = 0; i < permSize; i++) { + std::string perm; + RELEASE_IF_FALSE(in.ReadString(perm), requestParcel); + requestParcel->request.permissionList.emplace_back(perm); + } + RELEASE_IF_FALSE(in.ReadInt64(requestParcel->request.beginTimeMillis), requestParcel); + RELEASE_IF_FALSE(in.ReadInt64(requestParcel->request.endTimeMillis), requestParcel); + int32_t flag; + RELEASE_IF_FALSE(in.ReadInt32(flag), requestParcel); + requestParcel->request.flag = static_cast(flag); + return requestParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/src/permission_used_result_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_result_parcel.cpp new file mode 100644 index 000000000..8dec895ab --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/permission_used_result_parcel.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_result_parcel.h" +#include "refbase.h" +#include "bundle_used_record_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionUsedResultParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt64(this->result.beginTimeMillis)); + RETURN_IF_FALSE(out.WriteInt64(this->result.endTimeMillis)); + + RETURN_IF_FALSE(out.WriteInt32((int32_t)(this->result.bundleRecords.size()))); + for (const auto& bundRecord : this->result.bundleRecords) { + BundleUsedRecordParcel bundleParcel; + bundleParcel.bundleRecord = bundRecord; + out.WriteParcelable(&bundleParcel); + } + return true; +} + +PermissionUsedResultParcel* PermissionUsedResultParcel::Unmarshalling(Parcel& in) +{ + auto* resultParcel = new (std::nothrow) PermissionUsedResultParcel(); + RELEASE_IF_FALSE(resultParcel != nullptr, resultParcel); + + RELEASE_IF_FALSE(in.ReadInt64(resultParcel->result.beginTimeMillis), resultParcel); + RELEASE_IF_FALSE(in.ReadInt64(resultParcel->result.endTimeMillis), resultParcel); + + int32_t bundResponseSize = 0; + RELEASE_IF_FALSE(in.ReadInt32(bundResponseSize), resultParcel); + for (int32_t i = 0; i < bundResponseSize; i++) { + sptr bunRecordParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(bunRecordParcel != nullptr, resultParcel); + resultParcel->result.bundleRecords.emplace_back(bunRecordParcel->bundleRecord); + } + return resultParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/privacy/src/used_record_detail_parcel.cpp b/security_access_token-yl_0822/frameworks/privacy/src/used_record_detail_parcel.cpp new file mode 100644 index 000000000..d59512b67 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/privacy/src/used_record_detail_parcel.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "used_record_detail_parcel.h" +#include "parcel_utils.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool UsedRecordDetailParcel::Marshalling(Parcel& out) const +{ + RETURN_IF_FALSE(out.WriteInt32(this->detail.status)); + RETURN_IF_FALSE(out.WriteInt64(this->detail.timestamp)); + RETURN_IF_FALSE(out.WriteInt64(this->detail.accessDuration)); + return true; +} + +UsedRecordDetailParcel* UsedRecordDetailParcel::Unmarshalling(Parcel& in) +{ + auto* detailRecordParcel = new (std::nothrow) UsedRecordDetailParcel(); + RELEASE_IF_FALSE(detailRecordParcel != nullptr, detailRecordParcel); + + RELEASE_IF_FALSE(in.ReadInt32(detailRecordParcel->detail.status), detailRecordParcel); + RELEASE_IF_FALSE(in.ReadInt64(detailRecordParcel->detail.timestamp), detailRecordParcel); + RELEASE_IF_FALSE(in.ReadInt64(detailRecordParcel->detail.accessDuration), detailRecordParcel); + return detailRecordParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/frameworks/tokensync/include/i_token_sync_manager.h b/security_access_token-yl_0822/frameworks/tokensync/include/i_token_sync_manager.h new file mode 100644 index 000000000..9736a6fe2 --- /dev/null +++ b/security_access_token-yl_0822/frameworks/tokensync/include/i_token_sync_manager.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_TOKENSYNC_MANAGER_H +#define I_TOKENSYNC_MANAGER_H + +#include + +#include "iremote_broker.h" +#include "errors.h" + +#include "access_token.h" +#include "hap_token_info_for_sync_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class ITokenSyncManager : public IRemoteBroker { +public: + static const int SA_ID_TOKENSYNC_MANAGER_SERVICE = 3504; + + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.ITokenSyncManager"); + + virtual int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) = 0; + virtual int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) = 0; + + enum class InterfaceCode { + GET_REMOTE_HAP_TOKEN_INFO = 0xff01, + DELETE_REMOTE_HAP_TOKEN_INFO = 0xff02, + UPDATE_REMOTE_HAP_TOKEN_INFO = 0xff03 + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // I_TOKENSYNC_MANAGER_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/BUILD.gn new file mode 100644 index 000000000..30d5d6129 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") + +config("accesstoken") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_shared_library("libaccesstoken_sdk") { + subsystem_name = "security" + part_name = "access_token" + + output_name = "libaccesstoken_sdk" + + public_configs = [ ":accesstoken" ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "include", + "src", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + + sources = [ + "src/accesstoken_death_recipient.cpp", + "src/accesstoken_kit.cpp", + "src/accesstoken_manager_client.cpp", + "src/accesstoken_manager_proxy.cpp", + "src/perm_state_change_callback_customize.cpp", + "src/permission_state_change_callback.cpp", + "src/permission_state_change_callback_stub.cpp", + ] + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + + cflags_cc = [ + "-DHILOG_ENABLE", + "-DDEBUG_API_PERFORMANCE", + ] + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + } + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/access_token.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/access_token.h new file mode 100644 index 000000000..383cd6c73 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/access_token.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESS_TOKEN_DEF_H +#define ACCESS_TOKEN_DEF_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef unsigned int AccessTokenID; +typedef unsigned int AccessTokenAttr; +static const int DEFAULT_TOKEN_VERSION = 1; +static const int FIRSTCALLER_TOKENID_DEFAULT = 0; +static const int MAX_PERMISSION_SIZE = 1000; +static const int MAX_NATIVE_TOKEN_INFO_SIZE = 20480; +static const int INVALID_TOKENID = 0; +static const int INVALID_DLP_TOKEN_FLAG = -1; + +enum AccessTokenKitRet { + RET_FAILED = -1, + RET_SUCCESS = 0, +}; + +typedef struct { + unsigned int tokenUniqueID : 20; + unsigned int res : 6; + unsigned int dlpFlag : 1; + unsigned int type : 2; + unsigned int version : 3; +} AccessTokenIDInner; + +typedef enum TypeATokenTypeEnum { + TOKEN_INVALID = -1, + TOKEN_HAP = 0, + TOKEN_NATIVE, + TOKEN_SHELL, +} ATokenTypeEnum; + +typedef enum TypeATokenAplEnum { + APL_INVALID = 0, + APL_NORMAL = 1, + APL_SYSTEM_BASIC = 2, + APL_SYSTEM_CORE = 3, +} ATokenAplEnum; + +typedef union { + unsigned long long tokenIDEx; + struct { + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; + } tokenIdExStruct; +} AccessTokenIDEx; + +typedef enum TypePermissionState { + PERMISSION_DENIED = -1, + PERMISSION_GRANTED = 0, +} PermissionState; + +typedef enum TypeGrantMode { + USER_GRANT = 0, + SYSTEM_GRANT = 1, +} GrantMode; + +typedef enum TypePermissionFlag { + PERMISSION_DEFAULT_FLAG = 0, + PERMISSION_USER_SET = 1 << 0, + PERMISSION_USER_FIXED = 1 << 1, + PERMISSION_SYSTEM_FIXED = 1 << 2, + PERMISSION_GRANTED_BY_POLICY = 1 << 3, +} PermissionFlag; + +typedef enum TypePermissionOper { + SETTING_OPER = -1, + PASS_OPER = 0, + DYNAMIC_OPER = 1, + INVALID_OPER = 2, +} PermissionOper; + +typedef enum DlpType { + DLP_COMMON = 0, + DLP_READ = 1, + DLP_FULL_CONTROL = 2, +} HapDlpType; + +typedef enum TypeDlpPerm { + DLP_PERM_ALL = 0, + DLP_PERM_FULL_CONTROL = 1, + DLP_PERM_NONE = 2, +} DlpPermMode; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKEN_DEF_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken.h new file mode 100644 index 000000000..6257cc046 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef unsigned int AccessTokenID; +enum AccessTokenKitRet { + RET_FAILED = -1, + RET_SUCCESS = 0, +}; + +typedef enum TypePermissionState { + PERMISSION_DENIED = -1, + PERMISSION_GRANTED = 0, +} PermissionState; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h new file mode 100644 index 000000000..6de93b0df --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef ACCESS_TOKNE_DEATH_RECIPIENT_H +#define ACCESS_TOKNE_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenDeathRecipient : public IRemoteObject::DeathRecipient { +public: + AccessTokenDeathRecipient() {} + virtual ~AccessTokenDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKNE_DEATH_RECIPIENT_H + diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_kit.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_kit.h new file mode 100644 index 000000000..a71d1d551 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/accesstoken_kit.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H + +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "native_token_info.h" +#include "permission_def.h" +#include "permission_list_state.h" +#include "permission_state_change_info.h" +#include "permission_state_full.h" +#include "perm_state_change_callback_customize.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenKit { +public: + static AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); + static AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); + static int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); + static int DeleteToken(AccessTokenID tokenID); + /* Get token type by ATM service */ + static ATokenTypeEnum GetTokenType(AccessTokenID tokenID); + /* Get token type from flag in tokenId, which doesn't depend on ATM service */ + static ATokenTypeEnum GetTokenTypeFlag(AccessTokenID tokenID); + static int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); + static AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); + static int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); + static int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); + static int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); + static int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName); + static int VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName); + static int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); + static int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); + static int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); + static int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); + static PermissionOper GetSelfPermissionsState(std::vector& permList); + static int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + static int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + static int ClearUserGrantedPermissionState(AccessTokenID tokenID); + static int32_t RegisterPermStateChangeCallback( + const std::shared_ptr& callback); + static int32_t UnRegisterPermStateChangeCallback(const std::shared_ptr& callback); + static int32_t GetHapDlpFlag(AccessTokenID tokenID); + +#ifdef TOKEN_SYNC_ENABLE + static int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + static int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + static int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); + static int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + static int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + static AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); + static int DeleteRemoteDeviceTokens(const std::string& deviceID); +#endif + static void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/hap_token_info.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/hap_token_info.h new file mode 100644 index 000000000..917b8733b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/hap_token_info.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_HAP_TOKEN_INFO_H +#define ACCESSTOKEN_HAP_TOKEN_INFO_H + +#include "access_token.h" +#include "permission_def.h" +#include "permission_state_full.h" +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class HapInfoParams final { +public: + int userID; + std::string bundleName; + int instIndex; + int dlpType; + std::string appIDDesc; + int32_t apiVersion; +}; + +class HapPolicyParams final { +public: + ATokenAplEnum apl; + std::string domain; + std::vector permList; + std::vector permStateList; +}; + +class HapTokenInfo final { +public: + ATokenAplEnum apl; + char ver; + int userID; + std::string bundleName; + int32_t apiVersion; + int instIndex; + int dlpType; + std::string appID; + std::string deviceID; + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; +}; + +class HapTokenInfoForSync final { +public: + HapTokenInfo baseInfo; + std::vector permStateList; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_HAP_TOKEN_INFO_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/native_token_info.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/native_token_info.h new file mode 100644 index 000000000..62811db99 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/native_token_info.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_NATIVE_TOKEN_INFO_H +#define ACCESSTOKEN_NATIVE_TOKEN_INFO_H + +#include "access_token.h" +#include +#include +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class NativeTokenInfo final { +public: + ATokenAplEnum apl; + unsigned char ver; + std::string processName; + std::vector dcap; + AccessTokenID tokenID; + AccessTokenAttr tokenAttr; + std::vector nativeAcls; +}; + +class NativeTokenInfoForSync final { +public: + NativeTokenInfo baseInfo; + std::vector permStateList; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_NATIVE_TOKEN_INFO_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/perm_state_change_callback_customize.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/perm_state_change_callback_customize.h new file mode 100644 index 000000000..8ef8962c3 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/perm_state_change_callback_customize.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERM_STATE_CALLBACK_CUSTOMIZE_H +#define INTERFACES_INNER_KITS_PERM_STATE_CALLBACK_CUSTOMIZE_H + +#include "permission_state_change_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermStateChangeCallbackCustomize { +public: + PermStateChangeCallbackCustomize(); + explicit PermStateChangeCallbackCustomize(const PermStateChangeScope &scopeInfo); + virtual ~PermStateChangeCallbackCustomize(); + + virtual void PermStateChangeCallback(PermStateChangeInfo& result) = 0; + + void GetScope(PermStateChangeScope &scopeInfo) const; + +private: + PermStateChangeScope scopeInfo_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // INTERFACES_INNER_KITS_PERM_STATE_CALLBACK_CUSTOMIZE_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_def.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_def.h new file mode 100644 index 000000000..33539a31d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_def.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H + +#include + +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionDef final { +public: + std::string permissionName; + std::string bundleName; + int grantMode; + TypeATokenAplEnum availableLevel; + bool provisionEnable; + bool distributedSceneEnable; + std::string label; + int labelId; + std::string description; + int descriptionId; +}; + +class PermissionDefData final { +public: + AccessTokenID tokenId; + PermissionDef permDef; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DEF_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_dlp_mode.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_dlp_mode.h new file mode 100644 index 000000000..c635bc9a7 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_dlp_mode.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DLP_MODE_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DLP_MODE_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionDlpMode final { +public: + std::string permissionName; + int32_t dlpMode; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_DLP_MODE_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_list_state.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_list_state.h new file mode 100644 index 000000000..0e8787e88 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_list_state.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_LIST_STATE_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_LIST_STATE_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionListState final { +public: + std::string permissionName; + int state; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_LIST_STATE_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_change_info.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_change_info.h new file mode 100644 index 000000000..40c4e6a54 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_change_info.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PERMISSION_STATE_CHANGE_INFO_H +#define INTERFACES_INNER_KITS_PERMISSION_STATE_CHANGE_INFO_H + +#include +#include + +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define TOKENIDS_LIST_SIZE_MAX 1024 +#define PERMS_LIST_SIZE_MAX 1024 + +struct PermStateChangeInfo { + int32_t PermStateChangeType; + AccessTokenID tokenID; + std::string permissionName; +}; + +struct PermStateChangeScope { + std::vector tokenIDs; + std::vector permList; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // INTERFACES_INNER_KITS_PERMISSION_STATE_CHANGE_INFO_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_full.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_full.h new file mode 100644 index 000000000..be30cb569 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/include/permission_state_full.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_STATE_FULL_H +#define INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_STATE_FULL_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionStateFull final { +public: + std::string permissionName; + bool isGeneral; + std::vector resDeviceID; + std::vector grantStatus; + std::vector grantFlags; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_KITS_ACCESSTOKEN_PERMISSION_STATE_FULL_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp new file mode 100644 index 000000000..095981870 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "accesstoken_death_recipient.h" +#include "accesstoken_log.h" +#include "accesstoken_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenDeathRecipient"}; +} // namespace + +void AccessTokenDeathRecipient::OnRemoteDied(const wptr& object) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + AccessTokenManagerClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp new file mode 100644 index 000000000..108f7bd0e --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -0,0 +1,396 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_kit.h" +#include +#include +#include "accesstoken_log.h" +#include "accesstoken_manager_client.h" +#include "constant_common.h" +#include "data_validator.h" +#include "hap_token_info.h" +#include "permission_def.h" +#include "perm_state_change_callback_customize.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKit"}; +} // namespace + +AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) +{ + AccessTokenIDEx res = {0}; + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if ((!DataValidator::IsUserIdValid(info.userID)) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || + !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAplNumValid(policy.apl) || + !DataValidator::IsDomainValid(policy.domain) || !DataValidator::IsDlpTypeValid(info.dlpType)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); + return res; + } + + return AccessTokenManagerClient::GetInstance().AllocHapToken(info, policy); +} + +AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start call"); + AccessTokenID resID = AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:end call"); + return resID; +#else + return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); +#endif +} + +int AccessTokenKit::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if ((tokenID == 0) || (!DataValidator::IsAppIDDescValid(appIDDesc)) || + (!DataValidator::IsAplNumValid(policy.apl))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); + return RET_FAILED; + } + return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, apiVersion, policy); +} + +int AccessTokenKit::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().DeleteToken(tokenID); +} + +ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return TOKEN_INVALID; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().GetTokenType(tokenID); +} + +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ + if (tokenID == 0) { + return TOKEN_INVALID; + } + AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); + return (ATokenTypeEnum)(idInner->type); +} + +int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsDcapValid(dcap)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "dcap is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); + return AccessTokenManagerClient::GetInstance().CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (!DataValidator::IsUserIdValid(userID) || !DataValidator::IsBundleNameValid(bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); + return 0; + } + ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", + userID, bundleName.c_str(), instIndex); + return AccessTokenManagerClient::GetInstance().GetHapTokenID(userID, bundleName, instIndex); +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfoRes); +} + +int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfoRes); +} + +PermissionOper AccessTokenKit::GetSelfPermissionsState(std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called."); + return AccessTokenManagerClient::GetInstance().GetSelfPermissionsState(permList); +} + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return PERMISSION_DENIED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DENIED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenKit::VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) +{ + int ret = AccessTokenKit::VerifyAccessToken(callerTokenID, permissionName); + if (ret != PERMISSION_GRANTED) { + return ret; + } + if (firstTokenID == FIRSTCALLER_TOKENID_DEFAULT) { + return ret; + } + return AccessTokenKit::VerifyAccessToken(firstTokenID, permissionName); +} + +int AccessTokenKit::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID=%{public}d is invalid", tokenID); + return PERMISSION_DENIED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DENIED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().VerifyNativeToken(tokenID, permissionName); +} + +int AccessTokenKit::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); + + int ret = AccessTokenManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult); + ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); + + return ret; +} + +int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& permDefList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetDefPermissions(tokenID, permDefList); +} + +int AccessTokenKit::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); + + return AccessTokenManagerClient::GetInstance().GetReqPermissions(tokenID, reqPermList, isSystemGrant); +} + +int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return PERMISSION_DEFAULT_FLAG; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return PERMISSION_DEFAULT_FLAG; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); + return AccessTokenManagerClient::GetInstance().GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().GrantPermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); + return RET_FAILED; + } + if (!DataValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); + return AccessTokenManagerClient::GetInstance().RevokePermission(tokenID, permissionName, flag); +} + +int AccessTokenKit::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + return AccessTokenManagerClient::GetInstance().ClearUserGrantedPermissionState(tokenID); +} + +int32_t AccessTokenKit::RegisterPermStateChangeCallback( + const std::shared_ptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + return AccessTokenManagerClient::GetInstance().RegisterPermStateChangeCallback(callback); +} + +int32_t AccessTokenKit::UnRegisterPermStateChangeCallback( + const std::shared_ptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + return AccessTokenManagerClient::GetInstance().UnRegisterPermStateChangeCallback(callback); +} + +int32_t AccessTokenKit::GetHapDlpFlag(AccessTokenID tokenID) +{ + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return INVALID_DLP_TOKEN_FLAG; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); + return (int32_t)(idInner->dlpFlag); +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenKit::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + + return AccessTokenManagerClient::GetInstance().GetHapTokenInfoFromRemote(tokenID, hapSync); +} + +int AccessTokenKit::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + + return AccessTokenManagerClient::GetInstance().GetAllNativeTokenInfo(nativeTokenInfosRes); +} + +int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, + const HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), hapSync.baseInfo.tokenID); + return AccessTokenManagerClient::GetInstance().SetRemoteHapTokenInfo(deviceID, hapSync); +} + +int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, + ConstantCommon::EncryptDevId(deviceID).c_str()); + return AccessTokenManagerClient::GetInstance() + .SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); +} + +int AccessTokenKit::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().DeleteRemoteToken(deviceID, tokenID); +} + +int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, + ConstantCommon::EncryptDevId(deviceID).c_str()); + return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); +} + +AccessTokenID AccessTokenKit::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); +} +#endif + +void AccessTokenKit::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called,tokenID: %{public}d", __func__, tokenID); + AccessTokenManagerClient::GetInstance().DumpTokenInfo(tokenID, dumpInfo); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp new file mode 100644 index 000000000..c7c1e5ac1 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp @@ -0,0 +1,561 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_client.h" + +#include "accesstoken_log.h" +#include "accesstoken_manager_proxy.h" +#include "hap_token_info.h" +#include "hap_token_info_for_sync_parcel.h" +#include "iservice_registry.h" +#include "native_token_info_for_sync_parcel.h" +#include "native_token_info.h" +#include "permission_state_change_callback.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerClient" +}; +} // namespace +static const uint32_t MAX_CALLBACK_MAP_SIZE = 200; + +AccessTokenManagerClient& AccessTokenManagerClient::GetInstance() +{ + static AccessTokenManagerClient instance; + return instance; +} + +AccessTokenManagerClient::AccessTokenManagerClient() +{} + +AccessTokenManagerClient::~AccessTokenManagerClient() +{} + +int AccessTokenManagerClient::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return PERMISSION_DENIED; + } + return proxy->VerifyAccessToken(tokenID, permissionName); +} + +int AccessTokenManagerClient::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return PERMISSION_DENIED; + } + return proxy->VerifyNativeToken(tokenID, permissionName); +} + +int AccessTokenManagerClient::GetDefPermission( + const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + PermissionDefParcel permissionDefParcel; + int result = proxy->GetDefPermission(permissionName, permissionDefParcel); + permissionDefResult = permissionDefParcel.permissionDef; + return result; +} + +int AccessTokenManagerClient::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + std::vector parcelList; + int result = proxy->GetDefPermissions(tokenID, parcelList); + for (const auto& permParcel : parcelList) { + PermissionDef perm = permParcel.permissionDef; + permList.emplace_back(perm); + } + return result; +} + +int AccessTokenManagerClient::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + std::vector parcelList; + int result = proxy->GetReqPermissions(tokenID, parcelList, isSystemGrant); + for (const auto& permParcel : parcelList) { + PermissionStateFull perm = permParcel.permStatFull; + reqPermList.emplace_back(perm); + } + return result; +} + +int AccessTokenManagerClient::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return PERMISSION_DEFAULT_FLAG; + } + return proxy->GetPermissionFlag(tokenID, permissionName); +} + +PermissionOper AccessTokenManagerClient::GetSelfPermissionsState( + std::vector& permList) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "permList.size() : %{public}d.", (int)permList.size()); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null."); + return INVALID_OPER; + } + + size_t len = permList.size(); + if (len == 0) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "len is zero."); + return PASS_OPER; + } + + std::vector parcelList; + + for (const auto& perm : permList) { + PermissionListStateParcel permParcel; + permParcel.permsState = perm; + parcelList.emplace_back(permParcel); + } + PermissionOper result = proxy->GetSelfPermissionsState(parcelList); + + if (len != parcelList.size()) { + return INVALID_OPER; + } + for (uint32_t i = 0; i < len; i++) { + PermissionListState perm = parcelList[i].permsState; + permList[i].state = perm.state; + } + return result; +} + +int AccessTokenManagerClient::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + return proxy->GrantPermission(tokenID, permissionName, flag); +} + +int AccessTokenManagerClient::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + return proxy->RevokePermission(tokenID, permissionName, flag); +} + +int AccessTokenManagerClient::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + return proxy->ClearUserGrantedPermissionState(tokenID); +} + +int32_t AccessTokenManagerClient::CreatePermStateChangeCallback( + const std::shared_ptr& customizedCb, sptr& callbackObject) +{ + std::lock_guard lock(callbackMutex_); + if (callbackMap_.size() == MAX_CALLBACK_MAP_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "the maximum number of callback has been reached"); + return RET_FAILED; + } + + auto goalCallback = callbackMap_.find(customizedCb); + if (goalCallback != callbackMap_.end()) { + callbackObject = goalCallback->second->AsObject(); + ACCESSTOKEN_LOG_ERROR(LABEL, "already has the same callback"); + return RET_FAILED; + } else { + sptr callback = new (std::nothrow) PermissionStateChangeCallback(customizedCb); + if (!callback) { + ACCESSTOKEN_LOG_ERROR(LABEL, "memory allocation for callback failed!"); + return RET_FAILED; + } + callbackObject = callback->AsObject(); + callbackMap_[customizedCb] = callback; + } + return RET_SUCCESS; +} + +int32_t AccessTokenManagerClient::RegisterPermStateChangeCallback( + const std::shared_ptr& customizedCb) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called!"); + + if (customizedCb == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "customizedCb is nullptr"); + return RET_FAILED; + } + + sptr callbackObject = nullptr; + int32_t result = CreatePermStateChangeCallback(customizedCb, callbackObject); + if (result != RET_SUCCESS) { + return result; + } + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + PermStateChangeScopeParcel scopeParcel; + customizedCb->GetScope(scopeParcel.scope); + + return proxy->RegisterPermStateChangeCallback(scopeParcel, callbackObject); +} + +int32_t AccessTokenManagerClient::UnRegisterPermStateChangeCallback( + const std::shared_ptr& customizedCb) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: called!", __func__); + + std::lock_guard lock(callbackMutex_); + auto goalCallback = callbackMap_.find(customizedCb); + if (goalCallback == callbackMap_.end()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "goalCallback already is not exist"); + return RET_FAILED; + } + + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + int32_t result = proxy->UnRegisterPermStateChangeCallback(goalCallback->second->AsObject()); + if (result == RET_SUCCESS) { + callbackMap_.erase(goalCallback); + } + return result; +} + +AccessTokenIDEx AccessTokenManagerClient::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) +{ + AccessTokenIDEx res = { 0 }; + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return res; + } + HapInfoParcel hapInfoParcel; + HapPolicyParcel hapPolicyParcel; + hapInfoParcel.hapInfoParameter = info; + hapPolicyParcel.hapPolicyParameter = policy; + + return proxy->AllocHapToken(hapInfoParcel, hapPolicyParcel); +} + +int AccessTokenManagerClient::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + return proxy->DeleteToken(tokenID); +} + +ATokenTypeEnum AccessTokenManagerClient::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return TOKEN_INVALID; + } + return static_cast(proxy->GetTokenType(tokenID)); +} + +int AccessTokenManagerClient::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + return proxy->CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenManagerClient::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return INVALID_TOKENID; + } + return proxy->GetHapTokenID(userID, bundleName, instIndex); +} + +AccessTokenID AccessTokenManagerClient::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return INVALID_TOKENID; + } + return proxy->AllocLocalTokenID(remoteDeviceID, remoteTokenID); +} + +int AccessTokenManagerClient::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + HapPolicyParcel hapPolicyParcel; + hapPolicyParcel.hapPolicyParameter = policy; + return proxy->UpdateHapToken(tokenID, appIDDesc, apiVersion, hapPolicyParcel); +} + +int AccessTokenManagerClient::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + HapTokenInfoParcel hapTokenInfoParcel; + int res = proxy->GetHapTokenInfo(tokenID, hapTokenInfoParcel); + + hapTokenInfoRes = hapTokenInfoParcel.hapTokenInfoParams; + return res; +} + +int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + NativeTokenInfoParcel nativeTokenInfoParcel; + int res = proxy->GetNativeTokenInfo(tokenID, nativeTokenInfoParcel); + nativeTokenInfoRes = nativeTokenInfoParcel.nativeTokenInfoParams; + return res; +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenManagerClient::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + HapTokenInfoForSyncParcel hapSyncParcel; + int res = proxy->GetHapTokenInfoFromRemote(tokenID, hapSyncParcel); + hapSync = hapSyncParcel.hapTokenInfoForSyncParams; + return res; +} + +int AccessTokenManagerClient::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + std::vector parcelList; + int result = proxy->GetAllNativeTokenInfo(parcelList); + for (const auto& nativeTokenParcel : parcelList) { + NativeTokenInfoForSync native = nativeTokenParcel.nativeTokenInfoForSyncParams; + nativeTokenInfosRes.emplace_back(native); + } + + return result; +} + +int AccessTokenManagerClient::SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + HapTokenInfoForSyncParcel hapSyncParcel; + hapSyncParcel.hapTokenInfoForSyncParams = hapSync; + + int res = proxy->SetRemoteHapTokenInfo(deviceID, hapSyncParcel); + return res; +} + +int AccessTokenManagerClient::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + std::vector nativeTokenInfoParcels; + for (const auto& native : nativeTokenInfoList) { + NativeTokenInfoForSyncParcel nativeTokenInfoForSyncParcel; + nativeTokenInfoForSyncParcel.nativeTokenInfoForSyncParams = native; + nativeTokenInfoParcels.emplace_back(nativeTokenInfoForSyncParcel); + } + PermissionStateFullParcel permStateParcel; + int res = proxy->SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoParcels); + return res; +} + +int AccessTokenManagerClient::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + int res = proxy->DeleteRemoteToken(deviceID, tokenID); + return res; +} + +AccessTokenID AccessTokenManagerClient::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return INVALID_TOKENID; + } + + AccessTokenID res = proxy->GetRemoteNativeTokenID(deviceID, tokenID); + return res; +} + +int AccessTokenManagerClient::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + int res = proxy->DeleteRemoteDeviceTokens(deviceID); + return res; +} +#endif + +void AccessTokenManagerClient::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + return; + } + proxy->DumpTokenInfo(tokenID, dumpInfo); +} + +void AccessTokenManagerClient::InitProxy() +{ + std::lock_guard lock(proxyMutex_); + if (proxy_ == nullptr) { + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); + return; + } + auto accesstokenSa = sam->GetSystemAbility(IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); + if (accesstokenSa == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", + IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); + return; + } + + serviceDeathObserver_ = new (std::nothrow) AccessTokenDeathRecipient(); + if (serviceDeathObserver_ != nullptr) { + accesstokenSa->AddDeathRecipient(serviceDeathObserver_); + } + proxy_ = iface_cast(accesstokenSa); + if (proxy_ == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); + } + } +} + +void AccessTokenManagerClient::OnRemoteDiedHandle() +{ + { + std::lock_guard lock(proxyMutex_); + proxy_ = nullptr; + } + InitProxy(); +} + +sptr AccessTokenManagerClient::GetProxy() +{ + if (proxy_ == nullptr) { + InitProxy(); + } + return proxy_; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h new file mode 100644 index 000000000..8a0e14df3 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_CLIENT_H +#define ACCESSTOKEN_MANAGER_CLIENT_H + +#include +#include +#include +#include + +#include "access_token.h" +#include "accesstoken_death_recipient.h" +#include "hap_info_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info.h" +#include "i_accesstoken_manager.h" +#include "native_token_info.h" +#include "nocopyable.h" +#include "permission_def.h" +#include "permission_state_change_callback.h" +#include "permission_state_full.h" +#include "perm_state_change_callback_customize.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenManagerClient final { +public: + static AccessTokenManagerClient& GetInstance(); + + virtual ~AccessTokenManagerClient(); + + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); + int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName); + int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); + PermissionOper GetSelfPermissionsState(std::vector& permList); + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + int ClearUserGrantedPermissionState(AccessTokenID tokenID); + AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); + int DeleteToken(AccessTokenID tokenID); + ATokenTypeEnum GetTokenType(AccessTokenID tokenID); + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); + int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); + int32_t RegisterPermStateChangeCallback( + const std::shared_ptr& customizedCallback); + int32_t UnRegisterPermStateChangeCallback( + const std::shared_ptr& customizedCb); + +#ifdef TOKEN_SYNC_ENABLE + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); + int DeleteRemoteDeviceTokens(const std::string& deviceID); +#endif + + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); + void OnRemoteDiedHandle(); + +private: + AccessTokenManagerClient(); + int32_t CreatePermStateChangeCallback( + const std::shared_ptr& customizedCallback, sptr& callback); + + DISALLOW_COPY_AND_MOVE(AccessTokenManagerClient); + std::mutex proxyMutex_; + sptr proxy_ = nullptr; + sptr serviceDeathObserver_ = nullptr; + void InitProxy(); + sptr GetProxy(); + std::mutex callbackMutex_; + std::map, sptr> callbackMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_CLIENT_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp new file mode 100644 index 000000000..19785428e --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp @@ -0,0 +1,1036 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_proxy.h" + +#include "accesstoken_log.h" + +#include "parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerProxy"}; +} + +AccessTokenManagerProxy::AccessTokenManagerProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +AccessTokenManagerProxy::~AccessTokenManagerProxy() +{} + +int AccessTokenManagerProxy::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return PERMISSION_DENIED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return PERMISSION_DENIED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return PERMISSION_DENIED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::VERIFY_ACCESSTOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return PERMISSION_DENIED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return PERMISSION_DENIED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return PERMISSION_DENIED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return PERMISSION_DENIED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::VERIFY_NATIVETOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return PERMISSION_DENIED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetDefPermission( + const std::string& permissionName, PermissionDefParcel& permissionDefResult) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read permission def parcel fail"); + return RET_FAILED; + } + permissionDefResult = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, + std::vector& permList) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSIONS), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + if (size > MAX_PERMISSION_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "size = %{public}d get from request is invalid", size); + return RET_FAILED; + } + for (int i = 0; i < size; i++) { + sptr permissionDef = reply.ReadParcelable(); + if (permissionDef != nullptr) { + permList.emplace_back(*permissionDef); + } + } + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + if (!data.WriteInt32(isSystemGrant)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write isSystemGrant"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_REQ_PERMISSIONS), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + if (size > MAX_PERMISSION_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "size = %{public}d get from request is invalid", size); + return RET_FAILED; + } + for (int i = 0; i < size; i++) { + sptr permissionReq = reply.ReadParcelable(); + if (permissionReq != nullptr) { + reqPermList.emplace_back(*permissionReq); + } + } + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return PERMISSION_DEFAULT_FLAG; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return PERMISSION_DEFAULT_FLAG; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return PERMISSION_DEFAULT_FLAG; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_FLAG), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return PERMISSION_DEFAULT_FLAG; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +PermissionOper AccessTokenManagerProxy::GetSelfPermissionsState( + std::vector& permListParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(permListParcel.size())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permListParcel size."); + return INVALID_OPER; + } + for (const auto& permission : permListParcel) { + if (!data.WriteParcelable(&permission)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permListParcel."); + return INVALID_OPER; + } + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return INVALID_OPER; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_OPER_STATE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d.", requestResult); + return INVALID_OPER; + } + + PermissionOper result = static_cast(reply.ReadInt32()); + if (result == INVALID_OPER) { + ACCESSTOKEN_LOG_ERROR(LABEL, "result from server is invalid!"); + return result; + } + size_t size = reply.ReadUint32(); + if (size != permListParcel.size()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permListParcel size from server is invalid!"); + return INVALID_OPER; + } + for (uint32_t i = 0; i < size; i++) { + sptr permissionReq = reply.ReadParcelable(); + if (permissionReq != nullptr) { + permListParcel[i].permsState.state = permissionReq->permsState.state; + } + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return RET_FAILED; + } + if (!data.WriteInt32(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write flag"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GRANT_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return RET_FAILED; + } + if (!data.WriteInt32(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write flag"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::REVOKE_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::CLEAR_USER_GRANT_PERMISSION), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int32_t AccessTokenManagerProxy::RegisterPermStateChangeCallback( + const PermStateChangeScopeParcel& scope, const sptr& callback) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write WriteInterfaceToken."); + return RET_FAILED; + } + if (!data.WriteParcelable(&scope)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write PermStateChangeScopeParcel."); + return RET_FAILED; + } + if (!data.WriteRemoteObject(callback)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write remote object."); + return RET_FAILED; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::REGISTER_PERM_STATE_CHANGE_CALLBACK), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d.", requestResult); + return RET_FAILED; + } + + int32_t result; + if (!reply.ReadInt32(result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadInt32 fail"); + return RET_FAILED; + } + return result; +} + +int32_t AccessTokenManagerProxy::UnRegisterPermStateChangeCallback(const sptr& callback) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write WriteInterfaceToken."); + return RET_FAILED; + } + if (!data.WriteRemoteObject(callback)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write remote object."); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::UNREGISTER_PERM_STATE_CHANGE_CALLBACK), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d.", requestResult); + return RET_FAILED; + } + + int32_t result; + if (!reply.ReadInt32(result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadInt32 fail"); + return RET_FAILED; + } + return result; +} + +AccessTokenIDEx AccessTokenManagerProxy::AllocHapToken( + const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) +{ + MessageParcel data; + AccessTokenIDEx res; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteParcelable(&hapInfo)) { + res.tokenIDEx = 0; + return res; + } + if (!data.WriteParcelable(&policyParcel)) { + res.tokenIDEx = 0; + return res; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + res.tokenIDEx = 0; + return res; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::ALLOC_TOKEN_HAP), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + res.tokenIDEx = 0; + return res; + } + + unsigned long long result = reply.ReadUint64(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}llu", result); + res.tokenIDEx = result; + return res; +} + +int AccessTokenManagerProxy::DeleteToken(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::TOKEN_DELETE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetTokenType(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_TOKEN_TYPE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return RET_FAILED; + } + if (!data.WriteString(dcap)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); + return RET_FAILED; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::CHECK_NATIVE_DCAP), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +AccessTokenID AccessTokenManagerProxy::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteInt32(userID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return 0; + } + if (!data.WriteString(bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); + return 0; + } + if (!data.WriteInt32(instIndex)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); + return 0; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_ID), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return 0; + } + + int result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + return result; +} + +AccessTokenID AccessTokenManagerProxy::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteString(remoteDeviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); + return 0; + } + if (!data.WriteUint32(remoteTokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); + return 0; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::ALLOC_LOCAL_TOKEN_ID), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); + return 0; + } + + AccessTokenID result = reply.ReadUint32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_TOKENINFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + nativeTokenInfoRes = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKENINFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + hapTokenInfoRes = *resultSptr; + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + if (!data.WriteString(appIDDesc)) { + return RET_FAILED; + } + if (!data.WriteInt32(apiVersion)) { + return RET_FAILED; + } + if (!data.WriteParcelable(&policyParcel)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenManagerProxy::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_FROM_REMOTE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + sptr hapResult = reply.ReadParcelable(); + if (hapResult == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + hapSyncParcel = *hapResult; + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_ALL_NATIVE_TOKEN_FROM_REMOTE), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + if (size > MAX_NATIVE_TOKEN_INFO_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "size = %{public}d get from request is invalid", size); + return RET_FAILED; + } + for (int i = 0; i < size; i++) { + sptr nativeResult = reply.ReadParcelable(); + if (nativeResult != nullptr) { + nativeTokenInfoRes.emplace_back(*nativeResult); + } + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + if (!data.WriteParcelable(&hapSyncParcel)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoForSyncParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + if (!data.WriteUint32(nativeTokenInfoForSyncParcel.size())) { + return RET_FAILED; + } + for (const NativeTokenInfoForSyncParcel& parcel : nativeTokenInfoForSyncParcel) { + if (!data.WriteParcelable(&parcel)) { + return RET_FAILED; + } + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_NATIVE_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +AccessTokenID AccessTokenManagerProxy::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return 0; + } + + if (!data.WriteUint32(tokenID)) { + return 0; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_REMOTE_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return 0; + } + + AccessTokenID result = reply.ReadUint32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_DEVICE_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} +#endif + +void AccessTokenManagerProxy::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + if (!data.WriteUint32(tokenID)) { + return; + } + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + return; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DUMP_TOKENINFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + return; + } + + dumpInfo = reply.ReadString(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server dumpInfo = %{public}s", __func__, dumpInfo.c_str()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h new file mode 100644 index 000000000..809061d35 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_PROXY_H +#define ACCESSTOKEN_MANAGER_PROXY_H + +#include +#include + +#include "access_token.h" +#include "hap_info_parcel.h" +#include "hap_policy_parcel.h" +#include "hap_token_info_parcel.h" +#include "hap_token_info_for_sync_parcel.h" +#include "i_accesstoken_manager.h" +#include "iremote_proxy.h" +#include "native_token_info_for_sync_parcel.h" +#include "native_token_info_parcel.h" +#include "permission_def_parcel.h" +#include "permission_list_state_parcel.h" +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenManagerProxy : public IRemoteProxy { +public: + explicit AccessTokenManagerProxy(const sptr& impl); + ~AccessTokenManagerProxy() override; + + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) override; + int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) override; + int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override; + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) override; + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) override; + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) override; + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + PermissionOper GetSelfPermissionsState(std::vector& permList) override; + int ClearUserGrantedPermissionState(AccessTokenID tokenID) override; + int GetTokenType(AccessTokenID tokenID) override; + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) override; + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) override; + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) override; + AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) override; + int DeleteToken(AccessTokenID tokenID) override; + int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, + const HapPolicyParcel& policyPar) override; + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) override; + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) override; + int32_t RegisterPermStateChangeCallback( + const PermStateChangeScopeParcel& scope, const sptr& callback) override; + int32_t UnRegisterPermStateChangeCallback(const sptr& callback) override; + +#ifdef TOKEN_SYNC_ENABLE + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) override; + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoForSyncParcel) override; + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteDeviceTokens(const std::string& deviceID) override; +#endif + + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_PROXY_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/perm_state_change_callback_customize.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/perm_state_change_callback_customize.cpp new file mode 100644 index 000000000..b0962ab6e --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/perm_state_change_callback_customize.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_state_change_callback_customize.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +PermStateChangeCallbackCustomize::PermStateChangeCallbackCustomize() +{} + +PermStateChangeCallbackCustomize::PermStateChangeCallbackCustomize( + const PermStateChangeScope &scopeInfo) : scopeInfo_(scopeInfo) +{} + +PermStateChangeCallbackCustomize::~PermStateChangeCallbackCustomize() +{} + +void PermStateChangeCallbackCustomize::GetScope(PermStateChangeScope &scopeInfo) const +{ + scopeInfo = scopeInfo_; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.cpp new file mode 100644 index 000000000..e29a46ebe --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_change_callback.h" + +#include "access_token.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionStateChangeCallback" +}; + +PermissionStateChangeCallback::PermissionStateChangeCallback( + const std::shared_ptr& customizedCallback) + : customizedCallback_(customizedCallback) +{} + +PermissionStateChangeCallback::~PermissionStateChangeCallback() +{} + +void PermissionStateChangeCallback::PermStateChangeCallback(PermStateChangeInfo& result) +{ + if (customizedCallback_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "customizedCallback_ is nullptr"); + return; + } + + customizedCallback_->PermStateChangeCallback(result); +} + +void PermissionStateChangeCallback::Stop() +{} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h new file mode 100644 index 000000000..8ee416fad --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_CALLBACK_H +#define PERMISSION_STATE_CHANGE_CALLBACK_H + + +#include "permission_state_change_callback_stub.h" +#include "perm_state_change_callback_customize.h" + + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionStateChangeCallback : public PermissionStateChangeCallbackStub { +public: + explicit PermissionStateChangeCallback(const std::shared_ptr& scope); + ~PermissionStateChangeCallback() override; + + void PermStateChangeCallback(PermStateChangeInfo& result) override; + + void Stop(); + +private: + std::shared_ptr customizedCallback_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_STATE_CHANGE_CALLBACK_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.cpp new file mode 100644 index 000000000..b7e1dfae3 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_change_callback_stub.h" + +#include "access_token.h" +#include "accesstoken_log.h" +#include "permission_state_change_info_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionStateChangeCallbackStub" +}; +} + +int32_t PermissionStateChangeCallbackStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, code: 0x%{public}x", code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != IPermissionStateCallback::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return RET_FAILED; + } + + int32_t msgCode = static_cast(code); + if (msgCode == IPermissionStateCallback::PERMISSION_STATE_CHANGE) { + PermStateChangeInfo result; + sptr resultSptr = data.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + + PermStateChangeCallback(resultSptr->changeInfo); + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.h new file mode 100644 index 000000000..f29bca911 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/src/permission_state_change_callback_stub.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_CALLBACK_STUB_H +#define PERMISSION_STATE_CHANGE_CALLBACK_STUB_H + + +#include "i_permission_state_callback.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionStateChangeCallbackStub : public IRemoteStub { +public: + PermissionStateChangeCallbackStub() = default; + virtual ~PermissionStateChangeCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_STATE_CHANGE_CALLBACK_STUB_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/BUILD.gn new file mode 100644 index 000000000..458557d8c --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +ohos_unittest("libaccesstoken_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + "//base/security/access_token/interfaces/innerkits/token_setproc/include", + "//base/security/access_token/frameworks/common/include", + ] + + sources = [ "unittest/src/accesstoken_kit_test.cpp" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":libaccesstoken_sdk_test" ] +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp new file mode 100644 index 000000000..c908ebd0b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp @@ -0,0 +1,2869 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_kit_test.h" +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "accesstoken_log.h" +#include "token_setproc.h" +#include "softbus_bus_center.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr int32_t DEFAULT_API_VERSION = 8; +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKitTest"}; + +PermissionStateFull g_grantPermissionReq = { + .permissionName = "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; +PermissionStateFull g_revokePermissionReq = { + .permissionName = "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; + +PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "ohos.permission.test1", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "ohos.permission.test2", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"} +}; + +PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "ohos.permission.test2", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {PermissionState::PERMISSION_GRANTED, PermissionState::PERMISSION_GRANTED}, + .resDeviceID = {"device 1", "device 2"} +}; + +HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION +}; + +HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; + +HapInfoParams g_infoManagerTestInfoParmsBak = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION +}; + +HapPolicyParams g_infoManagerTestPolicyPramsBak = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; +} + +void AccessTokenKitTest::SetUpTestCase() +{ + // make test case clean + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + AccessTokenKit::DeleteToken(tokenID); +} + +void AccessTokenKitTest::TearDownTestCase() +{ +} + +void AccessTokenKitTest::SetUp() +{ + selfTokenId_ = GetSelfTokenID(); + g_infoManagerTestInfoParms = g_infoManagerTestInfoParmsBak; + g_infoManagerTestPolicyPrams = g_infoManagerTestPolicyPramsBak; + HapInfoParams info = { + .userID = TEST_USER_ID, + .bundleName = TEST_BUNDLE_NAME, + .instIndex = 0, + .appIDDesc = "appIDDesc", + .apiVersion = DEFAULT_API_VERSION + }; + + HapPolicyParams policy = { + .apl = APL_NORMAL, + .domain = "domain" + }; + + PermissionDef permissionDefAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + + PermissionDef permissionDefBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::SYSTEM_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + PermissionDef testPermDef1 = { + .permissionName = "ohos.permission.testPermDef1", + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + + PermissionDef testPermDef2 = { + .permissionName = "ohos.permission.testPermDef2", + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + + PermissionDef testPermDef3 = { + .permissionName = "ohos.permission.testPermDef3", + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + PermissionDef testPermDef4 = { + .permissionName = "ohos.permission.testPermDef4", + .bundleName = TEST_BUNDLE_NAME, + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false + }; + policy.permList.emplace_back(permissionDefAlpha); + policy.permList.emplace_back(permissionDefBeta); + policy.permList.emplace_back(testPermDef1); + policy.permList.emplace_back(testPermDef2); + policy.permList.emplace_back(testPermDef3); + policy.permList.emplace_back(testPermDef4); + + PermissionStateFull permStatAlpha = { + .permissionName = TEST_PERMISSION_NAME_ALPHA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_SET} + }; + PermissionStateFull permStatBeta = { + .permissionName = TEST_PERMISSION_NAME_BETA, + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} + }; + PermissionStateFull permTestState1 = { + .grantFlags = {0}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .isGeneral = true, + .permissionName = "ohos.permission.testPermDef1", + .resDeviceID = {"local"} + }; + + PermissionStateFull permTestState2 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .isGeneral = true, + .permissionName = "ohos.permission.testPermDef2", + .resDeviceID = {"local"} + }; + + PermissionStateFull permTestState3 = { + .grantFlags = {2}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .isGeneral = true, + .permissionName = "ohos.permission.testPermDef3", + .resDeviceID = {"local"} + }; + + PermissionStateFull permTestState4 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.testPermDef4", + .resDeviceID = {"local"} + }; + + policy.permStateList.emplace_back(permStatAlpha); + policy.permStateList.emplace_back(permStatBeta); + policy.permStateList.emplace_back(g_grantPermissionReq); + policy.permStateList.emplace_back(g_revokePermissionReq); + policy.permStateList.emplace_back(permTestState1); + policy.permStateList.emplace_back(permTestState1); + policy.permStateList.emplace_back(permTestState2); + policy.permStateList.emplace_back(permTestState3); + policy.permStateList.emplace_back(permTestState4); + AccessTokenKit::AllocHapToken(info, policy); + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + (void)remove("/data/token.json"); + + ACCESSTOKEN_LOG_INFO(LABEL, "SetUp ok."); +} + +void AccessTokenKitTest::TearDown() +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +unsigned int AccessTokenKitTest::GetAccessTokenID(int userID, std::string bundleName, int instIndex) +{ + return AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); +} + +void AccessTokenKitTest::DeleteTestToken() const +{ + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + int ret = AccessTokenKit::DeleteToken(tokenID); + if (tokenID != 0) { + ASSERT_EQ(RET_SUCCESS, ret); + } +} + +void AccessTokenKitTest::AllocTestToken() const +{ + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); +} + +/** + * @tc.name: GetDefPermission001 + * @tc.desc: Get permission definition info after AllocHapToken function has been invoked. + * @tc.type: FUNC + * @tc.require:AR000GM5FC AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, GetDefPermission001, TestSize.Level1) +{ + PermissionDef permDefResultAlpha; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha.permissionName); + + PermissionDef permDefResultBeta; + ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_BETA, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(TEST_PERMISSION_NAME_BETA, permDefResultBeta.permissionName); +} + +/** + * @tc.name: GetDefPermission002 + * @tc.desc: Get permission definition info that permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetDefPermission002, TestSize.Level1) +{ + PermissionDef permDefResult; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_GAMMA, permDefResult); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenKit::GetDefPermission("", permDefResult); + ASSERT_EQ(RET_FAILED, ret); + + std::string invalidPerm(INVALID_PERMNAME_LEN, 'a'); + ret = AccessTokenKit::GetDefPermission(invalidPerm, permDefResult); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: GetDefPermission003 + * @tc.desc: GetDefPermission is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetDefPermission003, TestSize.Level0) +{ + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + PermissionDef permDefResultAlpha; + ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha.permissionName); + } +} + +/** + * @tc.name: GetDefPermissions001 + * @tc.desc: Get permission definition info list after AllocHapToken function has been invoked. + * @tc.type: FUNC + * @tc.require:AR000GM5FC AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, GetDefPermissions001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + std::vector permDefList; + int ret = AccessTokenKit::GetDefPermissions(tokenID, permDefList); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(6, permDefList.size()); +} + +/** + * @tc.name: GetDefPermissions002 + * @tc.desc: Get permission definition info list after clear permission definition list + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetDefPermissions002, TestSize.Level1) +{ + HapPolicyParams testPolicyPrams = g_infoManagerTestPolicyPrams; + testPolicyPrams.permList.clear(); + AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, testPolicyPrams); + + AccessTokenID tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + ASSERT_NE(0, tokenID); + + std::vector permDefList; + int ret = AccessTokenKit::GetDefPermissions(tokenID, permDefList); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(0, permDefList.size()); + + AccessTokenKit::DeleteToken(tokenID); +} + +/** + * @tc.name: GetDefPermissions003 + * @tc.desc: Get permission definition info list that tokenID is invalid. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetDefPermissions003, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + AccessTokenKit::DeleteToken(tokenID); + + std::vector permDefList; + int ret = AccessTokenKit::GetDefPermissions(TEST_TOKENID_INVALID, permDefList); + ASSERT_EQ(RET_FAILED, ret); + + std::vector permDefListRes; + ret = AccessTokenKit::GetDefPermissions(tokenID, permDefListRes); + ASSERT_EQ(RET_FAILED, ret); + ASSERT_EQ(0, permDefListRes.size()); +} + +/** + * @tc.name: GetDefPermissions004 + * @tc.desc: GetDefPermissions is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetDefPermissions004, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + std::vector permDefList; + ret = AccessTokenKit::GetDefPermissions(tokenID, permDefList); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(6, permDefList.size()); + } +} + +/** + * @tc.name: GetReqPermissions001 + * @tc.desc: Get user granted permission state info. + * @tc.type: FUNC + * @tc.require:AR000GM5FC AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + std::vector permStatList; + int ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, false); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(5, permStatList.size()); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permStatList[0].permissionName); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(ret, permStatList[0].grantStatus[0]); +} + +/** + * @tc.name: GetReqPermissions002 + * @tc.desc: Get system granted permission state info. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions002, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + std::vector permStatList; + int ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, true); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(3, permStatList.size()); + ASSERT_EQ(TEST_PERMISSION_NAME_BETA, permStatList[0].permissionName); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(ret, permStatList[0].grantStatus[0]); +} + +/** + * @tc.name: GetReqPermissions003 + * @tc.desc: Get user granted permission state info after clear request permission list. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions003, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + HapTokenInfo hapInfo; + int ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapInfo); + ASSERT_EQ(RET_SUCCESS, ret); + + HapPolicyParams policy = { + .apl = hapInfo.apl, + .domain = "domain" + }; + policy.permStateList.clear(); + + ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, DEFAULT_API_VERSION, policy); + ASSERT_EQ(RET_SUCCESS, ret); + + std::vector permStatUserList; + ret = AccessTokenKit::GetReqPermissions(tokenID, permStatUserList, false); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(0, permStatUserList.size()); + + std::vector permStatSystemList; + ret = AccessTokenKit::GetReqPermissions(tokenID, permStatSystemList, true); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(0, permStatSystemList.size()); +} + +/** + * @tc.name: GetReqPermissions004 + * @tc.desc: Get permission state info list that tokenID is invalid. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions004, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + std::vector permStatList; + int ret = AccessTokenKit::GetReqPermissions(TEST_TOKENID_INVALID, permStatList, false); + ASSERT_EQ(RET_FAILED, ret); + + AccessTokenKit::DeleteToken(tokenID); + + ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, false); + ASSERT_EQ(RET_FAILED, ret); + ASSERT_EQ(0, permStatList.size()); +} + +/** + * @tc.name: GetReqPermissions005 + * @tc.desc: GetReqPermissions is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetReqPermissions005, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + std::vector permStatList; + ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, false); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(5, permStatList.size()); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permStatList[0].permissionName); + } +} + +/** + * @tc.name: GetPermissionFlag001 + * @tc.desc: Get permission flag after grant permission. + * @tc.type: FUNC + * @tc.require:AR000GM5FC AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, GetPermissionFlag001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_USER_FIXED, ret); +} + +/** + * @tc.name: GetPermissionFlag002 + * @tc.desc: Get permission flag that tokenID or permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetPermissionFlag002, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + int ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_GAMMA); + ASSERT_EQ(PERMISSION_DEFAULT_FLAG, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, ""); + ASSERT_EQ(PERMISSION_DEFAULT_FLAG, ret); + + std::string invalidPerm(INVALID_PERMNAME_LEN, 'a'); + ret = AccessTokenKit::GetPermissionFlag(tokenID, invalidPerm); + ASSERT_EQ(PERMISSION_DEFAULT_FLAG, ret); + + ret = AccessTokenKit::GetPermissionFlag(TEST_TOKENID_INVALID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DEFAULT_FLAG, ret); + + AccessTokenKit::DeleteToken(tokenID); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DEFAULT_FLAG, ret); +} + +/** + * @tc.name: GetPermissionFlag003 + * @tc.desc: GetPermissionFlag is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GM5FC + */ +HWTEST_F(AccessTokenKitTest, GetPermissionFlag003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_USER_FIXED, ret); + } +} + +/** + * @tc.name: VerifyAccessToken001 + * @tc.desc: Verify user granted permission. + * @tc.type: FUNC + * @tc.require:AR000GK6T8 AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: VerifyAccessToken002 + * @tc.desc: Verify system granted permission. + * @tc.type: FUNC + * @tc.require:AR000GK6T8 + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken002, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: VerifyAccessToken003 + * @tc.desc: Verify permission that tokenID or permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GK6T8 + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_GAMMA); + ASSERT_EQ(PERMISSION_DENIED, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, ""); + ASSERT_EQ(PERMISSION_DENIED, ret); + + std::string invalidPerm(INVALID_PERMNAME_LEN, 'a'); + ret = AccessTokenKit::VerifyAccessToken(tokenID, invalidPerm); + ASSERT_EQ(PERMISSION_DENIED, ret); + + AccessTokenKit::VerifyAccessToken(TEST_TOKENID_INVALID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_DENIED, ret); + + AccessTokenKit::DeleteToken(tokenID); + + AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: VerifyAccessToken004 + * @tc.desc: Verify permission after update. + * @tc.type: FUNC + * @tc.require:AR000GK6T8 + */ +HWTEST_F(AccessTokenKitTest, VerifyAccessToken004, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + HapTokenInfo hapInfo; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapInfo); + ASSERT_EQ(RET_SUCCESS, ret); + + std::vector permDefList; + ret = AccessTokenKit::GetDefPermissions(tokenID, permDefList); + ASSERT_EQ(RET_SUCCESS, ret); + + std::vector permStatList; + ret = AccessTokenKit::GetReqPermissions(tokenID, permStatList, false); + ASSERT_EQ(RET_SUCCESS, ret); + + HapPolicyParams policy = { + .apl = hapInfo.apl, + .domain = "domain", + .permList = permDefList, + .permStateList = permStatList + }; + + ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, DEFAULT_API_VERSION, policy); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); +} + +/** + * @tc.name: GrantPermission001 + * @tc.desc: Grant permission that has ohos.permission.GRANT_SENSITIVE_PERMISSIONS + * @tc.type: FUNC + * @tc.require:AR000GK6TF AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, GrantPermission001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); +} + +/** + * @tc.name: GrantPermission002 + * @tc.desc: Grant permission that tokenID or permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, GrantPermission002, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + int ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_GAMMA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::GrantPermission(tokenID, "", PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + std::string invalidPerm(INVALID_PERMNAME_LEN, 'a'); + ret = AccessTokenKit::GrantPermission(tokenID, invalidPerm, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenKit::GrantPermission(TEST_TOKENID_INVALID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + AccessTokenKit::DeleteToken(tokenID); + + ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: GrantPermission003 + * @tc.desc: GrantPermission is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, GrantPermission003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + ret = AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_USER_FIXED, ret); + } +} + +/** + * @tc.name: RevokePermission001 + * @tc.desc: Revoke permission that has ohos.permission.GRANT_SENSITIVE_PERMISSIONS + * @tc.type: FUNC + * @tc.require:AR000GK6TF AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, RevokePermission001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); + + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); +} + +/** + * @tc.name: RevokePermission002 + * @tc.desc: Revoke permission that tokenID or permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, RevokePermission002, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + int ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_GAMMA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::RevokePermission(tokenID, "", PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + std::string invalidPerm(INVALID_PERMNAME_LEN, 'a'); + ret = AccessTokenKit::RevokePermission(tokenID, invalidPerm, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + ret = AccessTokenKit::RevokePermission(TEST_TOKENID_INVALID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_FAILED, ret); + + AccessTokenKit::DeleteToken(tokenID); + + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_BETA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: RevokePermission003 + * @tc.desc: RevokePermission is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, RevokePermission003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + ret = AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); + + ret = AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_USER_FIXED, ret); + } +} + +/** + * @tc.name: ClearUserGrantedPermissionState001 + * @tc.desc: Clear user/system granted permission after ClearUserGrantedPermissionState has been invoked. + * @tc.type: FUNC + * @tc.require:AR000GK6TF AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, ClearUserGrantedPermissionState001, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::ClearUserGrantedPermissionState(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_BETA); + ASSERT_EQ(PERMISSION_GRANTED, ret); +} + +/** + * @tc.name: ClearUserGrantedPermissionState002 + * @tc.desc: Clear user/system granted permission that tokenID or permission is invalid. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, ClearUserGrantedPermissionState002, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + + int ret = AccessTokenKit::ClearUserGrantedPermissionState(TEST_TOKENID_INVALID); + ASSERT_EQ(RET_FAILED, ret); + + AccessTokenKit::DeleteToken(tokenID); + + ret = AccessTokenKit::ClearUserGrantedPermissionState(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: ClearUserGrantedPermissionState003 + * @tc.desc: ClearUserGrantedPermissionState is invoked multiple times. + * @tc.type: FUNC + * @tc.require:AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, ClearUserGrantedPermissionState003, TestSize.Level0) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + int ret = RET_FAILED; + for (int i = 0; i < CYCLE_TIMES; i++) { + ret = AccessTokenKit::ClearUserGrantedPermissionState(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + ASSERT_EQ(PERMISSION_DENIED, ret); + } +} + +/** + * @tc.name: ClearUserGrantedPermissionState004 + * @tc.desc: Clear user/system granted permission after ClearUserGrantedPermissionState has been invoked. + * @tc.type: FUNC + * @tc.require:AR000GK6TF AR000GK6TG + */ +HWTEST_F(AccessTokenKitTest, ClearUserGrantedPermissionState004, TestSize.Level0) +{ + AccessTokenIDEx tokenIdEx = {0}; + OHOS::Security::AccessToken::PermissionStateFull infoManagerTestState1 = { + .permissionName = "ohos.permission.CAMERA", + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {OHOS::Security::AccessToken::PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PERMISSION_GRANTED_BY_POLICY | PERMISSION_DEFAULT_FLAG} + }; + OHOS::Security::AccessToken::PermissionStateFull infoManagerTestState2 = { + .permissionName = "ohos.permission.SEND_MESSAGES", + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {OHOS::Security::AccessToken::PermissionState::PERMISSION_DENIED}, + .grantFlags = {PERMISSION_GRANTED_BY_POLICY | PERMISSION_USER_FIXED} + }; + OHOS::Security::AccessToken::PermissionStateFull infoManagerTestState3 = { + .permissionName = "ohos.permission.RECEIVE_SMS", + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {OHOS::Security::AccessToken::PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PERMISSION_USER_FIXED} + }; + OHOS::Security::AccessToken::HapPolicyParams infoManagerTestPolicyPrams = { + .apl = OHOS::Security::AccessToken::ATokenAplEnum::APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1}, + .permStateList = {infoManagerTestState1, infoManagerTestState2, infoManagerTestState3} + }; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(0, tokenID); + int ret = AccessTokenKit::ClearUserGrantedPermissionState(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.SEND_MESSAGES"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.RECEIVE_SMS"); + ASSERT_EQ(PERMISSION_DENIED, ret); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: GetTokenType001 + * @tc.desc: get the token type. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetTokenType001, TestSize.Level0) +{ + AllocTestToken(); + AccessTokenID tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + int ret = AccessTokenKit::GetTokenType(tokenID); + ASSERT_EQ(TOKEN_HAP, ret); + DeleteTestToken(); +} + +/** + * @tc.name: GetHapTokenInfo001 + * @tc.desc: get the token info and verify. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenInfo001, TestSize.Level0) +{ + HapTokenInfo hapTokenInfoRes; + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + int ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + + ASSERT_EQ(hapTokenInfoRes.apl, APL_NORMAL); + ASSERT_EQ(hapTokenInfoRes.userID, TEST_USER_ID); + ASSERT_EQ(hapTokenInfoRes.tokenID, tokenID); + ASSERT_EQ(hapTokenInfoRes.tokenAttr, 0); + ASSERT_EQ(hapTokenInfoRes.instIndex, 0); + + ASSERT_EQ(hapTokenInfoRes.appID, "appIDDesc"); + + ASSERT_EQ(hapTokenInfoRes.bundleName, TEST_BUNDLE_NAME); +} + +/** + * @tc.name: GetHapTokenInfo002 + * @tc.desc: try to get the token info with invalid tokenId. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenInfo002, TestSize.Level0) +{ + HapTokenInfo hapTokenInfoRes; + int ret = AccessTokenKit::GetHapTokenInfo(TEST_TOKENID_INVALID, hapTokenInfoRes); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: DeleteToken001 + * @tc.desc: Cannot get permission definition info after DeleteToken function has been invoked. + * @tc.type: FUNC + * @tc.require:AR000GK6TI + */ +HWTEST_F(AccessTokenKitTest, DeleteToken001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + PermissionDef permDefResultAlpha; + int ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha); + ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, permDefResultAlpha.permissionName); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + PermissionDef defResult; + ret = AccessTokenKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, defResult); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: DeleteToken002 + * @tc.desc: Delete invalid tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TI + */ +HWTEST_F(AccessTokenKitTest, DeleteToken002, TestSize.Level1) +{ + int ret = AccessTokenKit::DeleteToken(TEST_USER_ID_INVALID); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: DeleteToken002 + * @tc.desc: Delete invalid tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TI + */ +HWTEST_F(AccessTokenKitTest, DeleteToken003, TestSize.Level1) +{ + HapTokenInfo hapTokenInfoRes; + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + + int ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: DeleteToken004 + * @tc.desc: alloc a tokenId successfully, delete it successfully the first time and fail to delte it again. + * @tc.type: FUNC + * @tc.require:AR000GK6TI + */ +HWTEST_F(AccessTokenKitTest, DeleteToken004, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + GTEST_LOG_(INFO) << "tokenIdEx.tokenIdExStruct.tokenID :" << tokenIdEx.tokenIdExStruct.tokenID; + AccessTokenID tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + + int ret = AccessTokenKit::DeleteToken(tokenID); + GTEST_LOG_(INFO) << "g_infoManagerTestInfoParms.userID :" << g_infoManagerTestInfoParms.userID; + GTEST_LOG_(INFO) << "g_infoManagerTestInfoParms.bundleName :" << g_infoManagerTestInfoParms.bundleName.c_str(); + GTEST_LOG_(INFO) << "g_infoManagerTestInfoParms.instIndex :" << g_infoManagerTestInfoParms.instIndex; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: GetHapTokenID001 + * @tc.desc: get hap tokenid. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenID001, TestSize.Level1) +{ + HapTokenInfo hapTokenInfoRes; + AccessTokenID tokenID; + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + + int ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ(hapTokenInfoRes.bundleName, TEST_BUNDLE_NAME); +} + +/** + * @tc.name: GetHapTokenID002 + * @tc.desc: cannot get hap tokenid with invalid userId. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenID002, TestSize.Level1) +{ + AccessTokenID tokenID; + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID_INVALID, TEST_BUNDLE_NAME, 0); + ASSERT_EQ(0, tokenID); +} + +/** + * @tc.name: GetHapTokenID003 + * @tc.desc: cannot get hap tokenid with invalid bundlename. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenID003, TestSize.Level1) +{ + AccessTokenID tokenID; + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, "invalid bundlename", 0); + ASSERT_EQ(0, tokenID); +} + +/** + * @tc.name: GetHapTokenID003 + * @tc.desc: cannot get hap tokenid with invalid bundlename. + * @tc.type: FUNC + * @tc.require:AR000GK6TH + */ +HWTEST_F(AccessTokenKitTest, GetHapTokenID004, TestSize.Level1) +{ + AccessTokenID tokenID; + tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0xffff); + ASSERT_EQ(0, tokenID); +} + +/** + * @tc.name: AllocHapToken001 + * @tc.desc: alloc a tokenId successfully, delete it successfully the first time and fail to delte it again. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + GTEST_LOG_(INFO) << "tokenIdEx.tokenIdExStruct.tokenID :" << tokenIdEx.tokenIdExStruct.tokenID; + AccessTokenID tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + int ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: AllocHapToken002 + * @tc.desc: alloc a tokenId successfully, + * and fail to alloc it with the same info and policy again. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken002, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + AccessTokenID tokenID; + int ret; + + tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + + ret = AccessTokenKit::DeleteToken(tokenID); + GTEST_LOG_(INFO) << "DeleteToken ret:" << ret; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + GTEST_LOG_(INFO) << "tokenIdEx.tokenIdExStruct.tokenID :" << tokenIdEx.tokenIdExStruct.tokenID; + + tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + ASSERT_NE(0, tokenID); + + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: AllocHapToken003 + * @tc.desc: cannot alloc a tokenId with invalid bundlename. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken003, TestSize.Level1) +{ + std::string invalidBundleName (INVALID_BUNDLENAME_LEN, 'x'); + AccessTokenIDEx tokenIdEx = {0}; + int ret; + AccessTokenID tokenID; + + DeleteTestToken(); + GTEST_LOG_(INFO) << "get hap token info:" << invalidBundleName.length(); + g_infoManagerTestInfoParms.bundleName = invalidBundleName; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + + tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + ASSERT_EQ(0, tokenID); + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_FAILED, ret); + + g_infoManagerTestInfoParms.bundleName = "accesstoken_test"; +} + +/** + * @tc.name: AllocHapToken004 + * @tc.desc: cannot alloc a tokenId with invalid apl. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken004, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + AccessTokenID tokenID; + ATokenAplEnum typeBackUp = g_infoManagerTestPolicyPrams.apl; + DeleteTestToken(); + + g_infoManagerTestPolicyPrams.apl = (ATokenAplEnum)5; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + + tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + ASSERT_EQ(0, tokenID); + int ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_FAILED, ret); + g_infoManagerTestPolicyPrams.apl = typeBackUp; +} + +/** + * @tc.name: AllocHapToken005 + * @tc.desc: can alloc a tokenId when bundlename in permdef is different with bundlename in info. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken005, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::string backUp; + std::string backUpPermission; + std::string bundleNameBackUp = g_infoManagerTestPermDef1.bundleName; + DeleteTestToken(); + + backUp = g_infoManagerTestPolicyPrams.permList[0].bundleName; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + + g_infoManagerTestPolicyPrams.permList[0].bundleName = "invalid_bundleName"; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp01"; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].bundleName = backUp; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken006 + * @tc.desc: can alloc a tokenId with a invalid permList permissionName. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken006, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::string backUp; + DeleteTestToken(); + + const std::string invalidPermissionName (INVALID_PERMNAME_LEN, 'x'); + backUp = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = invalidPermissionName; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission(invalidPermissionName, permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUp; +} + +/** + * @tc.name: AllocHapToken007 + * @tc.desc: can alloc a tokenId with invalid permdef. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken007, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::string backUp; + std::string backUpPermission; + DeleteTestToken(); + + const std::string invalidBundleName (INVALID_BUNDLENAME_LEN, 'x'); + backUp = g_infoManagerTestPolicyPrams.permList[0].bundleName; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp02"; + g_infoManagerTestPolicyPrams.permList[0].bundleName = invalidBundleName; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].bundleName = backUp; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken008 + * @tc.desc: can alloc a tokenId with invalid permdef. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken008, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::string backUp; + std::string backUpPermission; + DeleteTestToken(); + + const std::string invalidLabel (INVALID_LABEL_LEN, 'x'); + backUp = g_infoManagerTestPolicyPrams.permList[0].label; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp03"; + g_infoManagerTestPolicyPrams.permList[0].label = invalidLabel; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].label = backUp; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken009 + * @tc.desc: can alloc a tokenId with invalid permdef. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken009, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + std::string backUp; + std::string backUpPermission; + DeleteTestToken(); + + const std::string invalidDescription (INVALID_DESCRIPTION_LEN, 'x'); + backUp = g_infoManagerTestPolicyPrams.permList[0].description; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp04"; + g_infoManagerTestPolicyPrams.permList[0].description = invalidDescription; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + + g_infoManagerTestPolicyPrams.permList[0].description = backUp; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +static bool ExistInVector(vector array, unsigned int value) +{ + vector::iterator it; + it = find(array.begin(), array.end(), value); + if (it != array.end()) { + return true; + } else { + return false; + } +} + +/** + * @tc.name: AllocHapToken010 + * @tc.desc: alloc and delete in a loop. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken010, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + AccessTokenID tokenID; + int ret; + bool exist = false; + int allocFlag = 0; + int deleteFlag = 0; + + DeleteTestToken(); + vector obj; + for (int i = 0; i < CYCLE_TIMES; i++) { + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + tokenID = GetAccessTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + + exist = ExistInVector(obj, tokenID); + if (exist) { + allocFlag = 1; + } + obj.push_back(tokenID); + + ret = AccessTokenKit::DeleteToken(tokenID); + if (RET_SUCCESS != ret) { + deleteFlag = 1; + } + } + ASSERT_EQ(allocFlag, 0); + ASSERT_EQ(deleteFlag, 0); +} + +/** + * @tc.name: AllocHapToken011 + * @tc.desc: cannot alloc a tokenId with invalid appIDDesc. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken011, TestSize.Level1) +{ + std::string invalidAppIDDesc (INVALID_APPIDDESC_LEN, 'x'); + std::string backup; + AccessTokenIDEx tokenIdEx = {0}; + + DeleteTestToken(); + backup = g_infoManagerTestInfoParms.appIDDesc; + g_infoManagerTestInfoParms.appIDDesc = invalidAppIDDesc; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + g_infoManagerTestInfoParms.appIDDesc = backup; +} + +/** + * @tc.name: AllocHapToken012 + * @tc.desc: cannot alloc a tokenId with invalid bundleName. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken012, TestSize.Level1) +{ + std::string backup; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestInfoParms.bundleName; + g_infoManagerTestInfoParms.bundleName = ""; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + g_infoManagerTestInfoParms.bundleName = backup; +} + +/** + * @tc.name: AllocHapToken013 + * @tc.desc: cannot alloc a tokenId with invalid appIDDesc. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken013, TestSize.Level1) +{ + std::string backup; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestInfoParms.appIDDesc; + g_infoManagerTestInfoParms.appIDDesc = ""; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); + g_infoManagerTestInfoParms.appIDDesc = backup; +} + +/** + * @tc.name: AllocHapToken014 + * @tc.desc: can alloc a tokenId with permList permissionName as "". + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken014, TestSize.Level1) +{ + std::string backup; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = ""; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission("", permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + g_infoManagerTestPolicyPrams.permList[0].permissionName = backup; +} + +/** + * @tc.name: AllocHapToken015 + * @tc.desc: can alloc a tokenId with permList bundleName as "". + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken015, TestSize.Level1) +{ + std::string backup; + std::string backUpPermission; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestPolicyPrams.permList[0].bundleName; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].bundleName = ""; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp05"; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + PermissionDef permDefResultBeta; + int ret = AccessTokenKit::GetDefPermission( + g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResultBeta); + ASSERT_EQ(RET_FAILED, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[1].permissionName, permDefResultBeta); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].bundleName = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken016 + * @tc.desc: can alloc a tokenId with label as "". + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken016, TestSize.Level1) +{ + std::string backup; + std::string backUpPermission; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestPolicyPrams.permList[0].label; + g_infoManagerTestPolicyPrams.permList[0].label = ""; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp06"; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + PermissionDef permDefResult; + int ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(ret, RET_SUCCESS); + g_infoManagerTestPolicyPrams.permList[0].label = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken017 + * @tc.desc: cannot alloc a tokenId with invalid permdef. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken017, TestSize.Level1) +{ + std::string backUpPermission; + std::string backup; + AccessTokenIDEx tokenIdEx = {0}; + + backup = g_infoManagerTestPolicyPrams.permList[0].description; + g_infoManagerTestPolicyPrams.permList[0].description = ""; + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp07"; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + PermissionDef permDefResult; + int ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(ret, RET_SUCCESS); + g_infoManagerTestPolicyPrams.permList[0].description = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; +} + +/** + * @tc.name: AllocHapToken018 + * @tc.desc: alloc a tokenId with vaild dlptype. + * @tc.type: FUNC + * @tc.require:AR000H4SAB + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken018, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {} + }; + HapInfoParams infoManagerTestInfoParms1 = { + .bundleName = "dlp_test1", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_COMMON, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION + }; + HapInfoParams infoManagerTestInfoParms2 = { + .bundleName = "dlp_test2", + .userID = 1, + .instIndex = 1, + .dlpType = DLP_READ, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION + }; + HapInfoParams infoManagerTestInfoParms3 = { + .bundleName = "dlp_test3", + .userID = 1, + .instIndex = 2, + .dlpType = DLP_FULL_CONTROL, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION + }; + HapTokenInfo hapTokenInfoRes; + AccessTokenID tokenID; + int32_t ret; + + tokenID = GetAccessTokenID(infoManagerTestInfoParms1.userID, infoManagerTestInfoParms1.bundleName, 0); + if (tokenID != 0) { + ret = AccessTokenKit::DeleteToken(tokenID); + } + tokenIdEx= AccessTokenKit::AllocHapToken(infoManagerTestInfoParms1, infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(AccessTokenKit::GetHapDlpFlag(tokenIdEx.tokenIdExStruct.tokenID), 0); + ASSERT_EQ(hapTokenInfoRes.dlpType, DLP_COMMON); + ret = AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_FAILED); + + tokenID = GetAccessTokenID(infoManagerTestInfoParms2.userID, infoManagerTestInfoParms2.bundleName, 1); + if (tokenID != 0) { + ret = AccessTokenKit::DeleteToken(tokenID); + } + tokenIdEx = AccessTokenKit::AllocHapToken(infoManagerTestInfoParms2, infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(hapTokenInfoRes.dlpType, DLP_READ); + ASSERT_EQ(AccessTokenKit::GetHapDlpFlag(tokenIdEx.tokenIdExStruct.tokenID), 1); + ret = AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_FAILED); + + tokenID = GetAccessTokenID(infoManagerTestInfoParms3.userID, infoManagerTestInfoParms3.bundleName, 2); + if (tokenID != 0) { + ret = AccessTokenKit::DeleteToken(tokenID); + } + tokenIdEx = AccessTokenKit::AllocHapToken(infoManagerTestInfoParms3, infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(hapTokenInfoRes.dlpType, DLP_FULL_CONTROL); + ASSERT_EQ(AccessTokenKit::GetHapDlpFlag(tokenIdEx.tokenIdExStruct.tokenID), 1); + ret = AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID, hapTokenInfoRes); + ASSERT_EQ(ret, RET_FAILED); +} + +/** + * @tc.name: AllocHapToken019 + * @tc.desc: cannot alloc a tokenId with invaild dlptype. + * @tc.type: FUNC + * @tc.require:AR000H4SAB + */ +HWTEST_F(AccessTokenKitTest, AllocHapToken019, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {} + }; + HapInfoParams infoManagerTestInfoParms1 = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 4, + .dlpType = INVALID_DLP_TYPE, + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION + }; + + tokenIdEx = AccessTokenKit::AllocHapToken(infoManagerTestInfoParms1, infoManagerTestPolicyPrams); + ASSERT_EQ(0, tokenIdEx.tokenIdExStruct.tokenID); +} + +/** + * @tc.name: UpdateHapToken001 + * @tc.desc: alloc a tokenId successfully, update it successfully and verify it. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken001, TestSize.Level1) +{ + int userID = g_infoManagerTestInfoParms.userID; + const std::string bundleName = g_infoManagerTestInfoParms.bundleName; + int instIndex = g_infoManagerTestInfoParms.instIndex; + + const std::string appIDDesc = "housework app"; + + DeleteTestToken(); + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + GTEST_LOG_(INFO) << "tokenID :" << tokenIdEx.tokenIdExStruct.tokenID; + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + g_infoManagerTestPolicyPrams.apl = APL_SYSTEM_BASIC; + + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(0, ret); + + HapTokenInfo hapTokenInfoRes; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + + ASSERT_EQ(hapTokenInfoRes.appID, "housework app"); + ASSERT_EQ(hapTokenInfoRes.apl, APL_SYSTEM_BASIC); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken002 + * @tc.desc: cannot update hap token info with invalid userId. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken002, TestSize.Level1) +{ + int ret = AccessTokenKit::UpdateHapToken( + TEST_USER_ID_INVALID, "appIDDesc", DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: UpdateHapToken003 + * @tc.desc: cannot update hap token info with invalid appIDDesc. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken003, TestSize.Level1) +{ + int userID = g_infoManagerTestInfoParms.userID; + const std::string bundleName = g_infoManagerTestInfoParms.bundleName; + int instIndex = g_infoManagerTestInfoParms.instIndex; + + const std::string appIDDesc (INVALID_APPIDDESC_LEN, 'x'); + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); + + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_FAILED, ret); + + HapTokenInfo hapTokenInfoRes; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + + ASSERT_EQ(hapTokenInfoRes.appID, "testtesttesttest"); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken004 + * @tc.desc: cannot update a tokenId with invalid apl. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken004, TestSize.Level1) +{ + int userID = g_infoManagerTestInfoParms.userID; + const std::string bundleName = g_infoManagerTestInfoParms.bundleName; + int instIndex = g_infoManagerTestInfoParms.instIndex; + + const std::string appIDDesc = "housework app"; + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); + + g_infoManagerTestPolicyPrams.apl = (ATokenAplEnum)5; + + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_FAILED, ret); + + HapTokenInfo hapTokenInfoRes; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(RET_SUCCESS, ret); + + ASSERT_EQ(hapTokenInfoRes.apl, APL_NORMAL); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken005 + * @tc.desc: cannot update a tokenId with invalid string value. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken005, TestSize.Level1) +{ + std::string backUpPermission; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + PermissionDef permDefResult; + + DeleteTestToken(); + AccessTokenIDEx tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(0, tokenID); + + std::string backup = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = ""; + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(RET_FAILED, ret); + g_infoManagerTestPolicyPrams.permList[0].permissionName = backup; + + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp11"; + backup = g_infoManagerTestPolicyPrams.permList[0].bundleName; + g_infoManagerTestPolicyPrams.permList[0].bundleName = ""; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(RET_FAILED, ret); + g_infoManagerTestPolicyPrams.permList[0].bundleName = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; + + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp12"; + backup = g_infoManagerTestPolicyPrams.permList[0].label; + g_infoManagerTestPolicyPrams.permList[0].label = ""; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].label = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; + + backUpPermission = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp13"; + backup = g_infoManagerTestPolicyPrams.permList[0].description; + g_infoManagerTestPolicyPrams.permList[0].description = ""; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_SUCCESS, ret); + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].description = backup; + g_infoManagerTestPolicyPrams.permList[0].permissionName = backUpPermission; + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken006 + * @tc.desc: update a batch of tokenId. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken006, TestSize.Level1) +{ + int allocFlag = 0; + int updateFlag = 0; + int deleteFlag = 0; + AccessTokenIDEx tokenIdEx = {0}; + AccessTokenID tokenID; + int ret; + vector obj; + bool exist; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + HapInfoParams infoManagerTestInfo = g_infoManagerTestInfoParms; + DeleteTestToken(); + + for (int i = 0; i < CYCLE_TIMES; i++) { + tokenIdEx = AccessTokenKit::AllocHapToken(infoManagerTestInfo, g_infoManagerTestPolicyPrams); + tokenID = GetAccessTokenID(infoManagerTestInfo.userID, + infoManagerTestInfo.bundleName, + infoManagerTestInfo.instIndex); + + exist = ExistInVector(obj, tokenID); + if (exist) { + allocFlag = 1; + break; + } + obj.push_back(tokenID); + infoManagerTestInfo.userID++; + } + + infoManagerTestInfo.instIndex = 1; + g_infoManagerTestPolicyPrams.apl = APL_SYSTEM_BASIC; + for (size_t i = 0; i < obj.size(); i++) { + ret = AccessTokenKit::UpdateHapToken(obj[i], appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + if (RET_SUCCESS != ret) { + updateFlag = 1; + break; + } + } + g_infoManagerTestPolicyPrams.apl = APL_NORMAL; + + for (size_t i = 0; i < obj.size(); i++) { + ret = AccessTokenKit::DeleteToken(obj[i]); + if (RET_SUCCESS != ret) { + deleteFlag = 1; + } + } + ASSERT_EQ(allocFlag, 0); + ASSERT_EQ(updateFlag, 0); + ASSERT_EQ(deleteFlag, 0); +} + +/** + * @tc.name: UpdateHapToken007 + * @tc.desc: add new permissdef. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken007, TestSize.Level1) +{ + int ret; + std::string backup; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + DeleteTestToken(); + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + PermissionDef permDefResult; + /* check permission define before update */ + ret = AccessTokenKit::GetDefPermission("ohos.permission.test3", permDefResult); + ASSERT_EQ(RET_FAILED, ret); + + backup = g_infoManagerTestPolicyPrams.permList[0].permissionName; + g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.test3"; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].permissionName = backup; + + GTEST_LOG_(INFO) << "permissionName :" << g_infoManagerTestPolicyPrams.permList[0].permissionName; + + ret = AccessTokenKit::GetDefPermission("ohos.permission.test3", permDefResult); + if (ret != RET_SUCCESS) { + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + } + ASSERT_EQ(RET_SUCCESS, ret); + ASSERT_EQ("ohos.permission.test3", permDefResult.permissionName); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} +/** + * @tc.name: UpdateHapToken008 + * @tc.desc: modify permissdef's grantMode. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken008, TestSize.Level1) +{ + int ret; + std::string backup; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + DeleteTestToken(); + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + PermissionDef permDefResult; + /* check permission define before update */ + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult.permissionName); + ASSERT_EQ("label", permDefResult.label); + ASSERT_EQ(1, permDefResult.grantMode); + ASSERT_EQ(RET_SUCCESS, ret); + + backup = g_infoManagerTestPolicyPrams.permList[0].label; + g_infoManagerTestPolicyPrams.permList[0].grantMode = 0; + g_infoManagerTestPolicyPrams.permList[0].label = "updated label"; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); + ASSERT_EQ(RET_SUCCESS, ret); + g_infoManagerTestPolicyPrams.permList[0].label = backup; + g_infoManagerTestPolicyPrams.permList[0].grantMode = 1; + + /* check permission define after update */ + ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); + ASSERT_EQ(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult.permissionName); + ASSERT_EQ("updated label", permDefResult.label); + ASSERT_EQ(0, permDefResult.grantMode); + ASSERT_EQ(RET_SUCCESS, ret); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken009 + * @tc.desc: old permission define will not update its grantStatus. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken009, TestSize.Level1) +{ + int ret; + std::vector permDefList; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + PermissionDef infoManagerTestPermDef = g_infoManagerTestPermDef1; + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionState::PERMISSION_DENIED}, + .grantStatus = {3}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + + HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {infoManagerTestPermDef}, + .permStateList = {infoManagerTestState}}; + + DeleteTestToken(); + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.test1"); + ASSERT_EQ(ret, g_infoManagerTestState1.grantStatus[0]); + + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, infoManagerTestPolicyPrams); + + ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.test1"); + ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); + + ret = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +/** + * @tc.name: UpdateHapToken010 + * @tc.desc: update api version. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken010, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + uint32_t apiVersion = DEFAULT_API_VERSION - 1; + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, apiVersion, g_infoManagerTestPolicyPrams); + + HapTokenInfo hapTokenInfoRes; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(apiVersion, hapTokenInfoRes.apiVersion); + + apiVersion = DEFAULT_API_VERSION + 1; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, apiVersion, g_infoManagerTestPolicyPrams); + + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(apiVersion, hapTokenInfoRes.apiVersion); +} + +static void *ThreadTestFunc01(void *args) +{ + ATokenTypeEnum type; + AccessTokenID tokenID; + + for (int i = 0; i < CYCLE_TIMES; i++) { + tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + type = AccessTokenKit::GetTokenType(tokenID); + if (type != TOKEN_HAP) { + GTEST_LOG_(INFO) << "ThreadTestFunc01 failed" << tokenID; + } + } + return NULL; +} + +static void *ThreadTestFunc02(void *args) +{ + int ret; + AccessTokenID tokenID; + HapTokenInfo hapTokenInfoRes; + + for (int i = 0; i < CYCLE_TIMES; i++) { + tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + if (ret != RET_SUCCESS) { + GTEST_LOG_(INFO) << "ThreadTestFunc02 failed" << tokenID; + } + } + return NULL; +} + +/** + * @tc.name: AllocHapToken011 + * @tc.desc: Mulitpulthread test. + * @tc.type: FUNC + * @tc.require:AR000GK6TJ + */ +HWTEST_F(AccessTokenKitTest, Mulitpulthread001, TestSize.Level1) +{ + int ret; + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + pthread_t tid[2]; + (void)pthread_create(&tid[0], 0, &ThreadTestFunc01, NULL); + (void)pthread_create(&tid[1], 0, &ThreadTestFunc01, NULL); + pthread_join(tid[0], NULL); + pthread_join(tid[1], NULL); + + (void)pthread_create(&tid[0], 0, &ThreadTestFunc02, NULL); + (void)pthread_create(&tid[1], 0, &ThreadTestFunc02, NULL); + pthread_join(tid[0], NULL); + pthread_join(tid[1], NULL); + + ret = AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); +} + +void ConcurrencyTask(unsigned int tokenID) +{ + for (int i = 0; i < CYCLE_TIMES; i++) { + AccessTokenKit::GrantPermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_FIXED); + AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + + AccessTokenKit::RevokePermission(tokenID, TEST_PERMISSION_NAME_ALPHA, PERMISSION_USER_SET); + AccessTokenKit::GetPermissionFlag(tokenID, TEST_PERMISSION_NAME_ALPHA); + AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); + } +} + +/** + * @tc.name: ConcurrencyTest001 + * @tc.desc: Concurrency testing + * @tc.type: FUNC + * @tc.require:AR000GM5FC AR000GK6T8 AR000GK6TF + */ +HWTEST_F(AccessTokenKitTest, ConcurrencyTest001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + std::vector threadVec; + for (int i = 0; i < THREAD_NUM; i++) { + threadVec.emplace_back(std::thread(ConcurrencyTask, tokenID)); + } + for (auto it = threadVec.begin(); it != threadVec.end(); it++) { + it->join(); + } +} + +/** + * @tc.name: CheckNativeDCap001 + * @tc.desc: cannot Check native dcap with invalid tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, CheckNativeDCap001, TestSize.Level1) +{ + AccessTokenID tokenID = 0; + const std::string dcap = "AT_CAP"; + int ret = AccessTokenKit::CheckNativeDCap(tokenID, dcap); + ASSERT_EQ(RET_FAILED, ret); + + tokenID = 1; + ret = AccessTokenKit::CheckNativeDCap(tokenID, dcap); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: CheckNativeDCap002 + * @tc.desc: cannot Check native dcap with invalid dcap. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, CheckNativeDCap002, TestSize.Level1) +{ + AccessTokenID tokenID = 0Xff; + const std::string invalidDcap (INVALID_DCAP_LEN, 'x'); + int ret = AccessTokenKit::CheckNativeDCap(tokenID, invalidDcap); + ASSERT_EQ(RET_FAILED, ret); +} + +/** + * @tc.name: GetNativeTokenInfo001 + * @tc.desc: cannot get native token with invalid tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, GetNativeTokenInfo001, TestSize.Level1) +{ + AccessTokenID tokenID = 0; + NativeTokenInfo findInfo; + int ret = AccessTokenKit::GetNativeTokenInfo(tokenID, findInfo); + ASSERT_EQ(ret, RET_FAILED); + + tokenID = 0xff; + ret = AccessTokenKit::GetNativeTokenInfo(tokenID, findInfo); + ASSERT_EQ(ret, RET_FAILED); +} + +/** + * @tc.name: GetTokenTypeFlag001 + * @tc.desc: cannot get token type with tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, GetTokenTypeFlag001, TestSize.Level1) +{ + AccessTokenID tokenID = 0; + ATokenTypeEnum ret = AccessTokenKit::GetTokenTypeFlag(tokenID); + ASSERT_EQ(ret, TOKEN_INVALID); +} + +/** + * @tc.name: GetTokenTypeFlag002 + * @tc.desc: Get token type with native tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, GetTokenTypeFlag002, TestSize.Level1) +{ + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 0, + .aclsNum = 0, + .dcaps = nullptr, + .perms = nullptr, + .acls = nullptr, + .processName = "GetTokenTypeFlag002", + .aplStr = "system_core", + }; + uint64_t tokenId01 = GetAccessTokenId(&infoInstance); + + AccessTokenID tokenID = tokenId01 & 0xffffffff; + ATokenTypeEnum ret = AccessTokenKit::GetTokenTypeFlag(tokenID); + ASSERT_EQ(ret, TOKEN_NATIVE); +} + +/** + * @tc.name: GetSelfPermissionsState001 + * @tc.desc: get permission list state + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState001, TestSize.Level1) +{ + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, TEST_BUNDLE_NAME, 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState perm1 = { + .permissionName = "ohos.permission.testPermDef1", + .state = -1, + }; + PermissionListState perm2 = { + .permissionName = "ohos.permission.testPermDef2", + .state = -1, + }; + PermissionListState perm3 = { + .permissionName = "ohos.permission.testPermDef3", + .state = -1, + }; + PermissionListState perm4 = { + .permissionName = "ohos.permission.testPermDef4", + .state = -1, + }; + + std::vector permsList1; + permsList1.emplace_back(perm1); + permsList1.emplace_back(perm2); + permsList1.emplace_back(perm3); + permsList1.emplace_back(perm4); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList1); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(4, permsList1.size()); + ASSERT_EQ(DYNAMIC_OPER, permsList1[0].state); + ASSERT_EQ(DYNAMIC_OPER, permsList1[1].state); + ASSERT_EQ(SETTING_OPER, permsList1[2].state); + ASSERT_EQ(PASS_OPER, permsList1[3].state); + ASSERT_EQ("ohos.permission.testPermDef1", permsList1[0].permissionName); + ASSERT_EQ("ohos.permission.testPermDef2", permsList1[1].permissionName); + ASSERT_EQ("ohos.permission.testPermDef3", permsList1[2].permissionName); + ASSERT_EQ("ohos.permission.testPermDef4", permsList1[3].permissionName); + + PermissionListState perm5 = { + .permissionName = "ohos.permission.testPermDef5", + .state = -1, + }; + permsList1.emplace_back(perm5); + ret = AccessTokenKit::GetSelfPermissionsState(permsList1); + ASSERT_EQ(INVALID_OPER, permsList1[4].state); + ASSERT_EQ(DYNAMIC_OPER, ret); + + std::vector permsList2; + permsList2.emplace_back(perm3); + permsList2.emplace_back(perm4); + ret = AccessTokenKit::GetSelfPermissionsState(permsList2); + ASSERT_EQ(SETTING_OPER, permsList2[0].state); + ASSERT_EQ(PASS_OPER, permsList2[1].state); + ASSERT_EQ(PASS_OPER, ret); + + permsList2.emplace_back(perm5); + ret = AccessTokenKit::GetSelfPermissionsState(permsList2); + ASSERT_EQ(SETTING_OPER, permsList2[0].state); + ASSERT_EQ(PASS_OPER, permsList2[1].state); + ASSERT_EQ(INVALID_OPER, permsList2[2].state); + ASSERT_EQ(PASS_OPER, ret); + + std::vector permsList3; + permsList3.emplace_back(perm5); + ret = AccessTokenKit::GetSelfPermissionsState(permsList3); + ASSERT_EQ(INVALID_OPER, permsList3[0].state); + ASSERT_EQ(PASS_OPER, ret); +} + +/** + * @tc.name: GetTokenTypeFlag003 + * @tc.desc: Get token type with hap tokenID. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, GetTokenTypeFlag003, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + ATokenTypeEnum ret = AccessTokenKit::GetTokenTypeFlag(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(ret, TOKEN_HAP); + + int res = AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, res); +} + +/** + * @tc.name: DumpTokenInfo001 + * @tc.desc: Get dump token information with invalid tokenID + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo001, TestSize.Level1) +{ + std::string info; + AccessTokenKit::DumpTokenInfo(123, info); + ASSERT_EQ("invalid tokenId", info); +} + +/** + * @tc.name: DumpTokenInfo002 + * @tc.desc: Get dump token information + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo002, TestSize.Level1) +{ + std::string info; + AccessTokenKit::DumpTokenInfo(0, info); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DumpTokenInfo003 + * @tc.desc: Get dump token information + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo003, TestSize.Level1) +{ + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + std::string info; + AccessTokenKit::DumpTokenInfo(tokenID, info); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DeleteRemoteToken001 + * @tc.desc: DeleteRemoteToken with invalid parameters. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DeleteRemoteToken001, TestSize.Level1) +{ + std::string deviceId = "device"; + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + int res = AccessTokenKit::DeleteRemoteToken("", tokenID); + ASSERT_EQ(RET_FAILED, res); + + res = AccessTokenKit::DeleteRemoteToken(deviceId, tokenID); + ASSERT_EQ(RET_FAILED, res); +} + +class CbCustomizeTest : public PermStateChangeCallbackCustomize { +public: + explicit CbCustomizeTest(const PermStateChangeScope &scopeInfo) + : PermStateChangeCallbackCustomize(scopeInfo) + { + GTEST_LOG_(INFO) << "CbCustomizeTest create"; + } + + ~CbCustomizeTest() + {} + + virtual void PermStateChangeCallback(PermStateChangeInfo& result) + { + ready_ = true; + GTEST_LOG_(INFO) << "CbCustomizeTest PermStateChangeCallback"; + GTEST_LOG_(INFO) << "tokenid" << result.tokenID; + GTEST_LOG_(INFO) << "permissionName" << result.permissionName; + } + + bool ready_; +}; + +/** + * @tc.name: RegisterPermStateChangeCallback001 + * @tc.desc: RegisterPermStateChangeCallback permList + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback001, TestSize.Level1) +{ + PermStateChangeScope scopeInfo; + scopeInfo.permList = {"ohos.permission.CAMERA"}; + scopeInfo.tokenIDs = {}; + auto callbackPtr = std::make_shared(scopeInfo); + callbackPtr->ready_ = false; + + int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); + + static PermissionStateFull infoManagerTestStateA = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PERMISSION_DENIED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateA} + }; + + AccessTokenIDEx tokenIdEx = {0}; + AccessTokenID tokenID; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + + tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(0, tokenID); + + ATokenTypeEnum ret = AccessTokenKit::GetTokenTypeFlag(tokenID); + ASSERT_EQ(ret, TOKEN_HAP); + + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_DENIED, res); + + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_GRANTED, res); + + ASSERT_EQ(true, callbackPtr->ready_); + + callbackPtr->ready_ = false; + + res = AccessTokenKit::RevokePermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(true, callbackPtr->ready_); + + res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); + ASSERT_EQ(RET_SUCCESS, res); + + callbackPtr->ready_ = false; + + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(false, callbackPtr->ready_); + + callbackPtr->ready_ = false; + + res = AccessTokenKit::RevokePermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(false, callbackPtr->ready_); + + res = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, res); +} + +/** + * @tc.name: RegisterPermStateChangeCallback002 + * @tc.desc: RegisterPermStateChangeCallback permList + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback002, TestSize.Level1) +{ + PermStateChangeScope scopeInfo; + scopeInfo.permList = {"ohos.permission.GET_BUNDLE_INFO"}; + scopeInfo.tokenIDs = {}; + auto callbackPtr = std::make_shared(scopeInfo); + callbackPtr->ready_ = false; + + int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); + + static PermissionStateFull infoManagerTestStateA = { + .permissionName = "ohos.permission.GET_BUNDLE_INFO", + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static PermissionStateFull infoManagerTestStateB = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_SYSTEM_BASIC, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateA, infoManagerTestStateB} + }; + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_GRANTED, res); + + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(false, callbackPtr->ready_); + + res = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, res); + + res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); + ASSERT_EQ(RET_SUCCESS, res); +} + +/** + * @tc.name: RegisterPermStateChangeCallback003 + * @tc.desc: RegisterPermStateChangeCallback permList + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback003, TestSize.Level1) +{ + PermStateChangeScope scopeInfo; + scopeInfo.permList = {}; + scopeInfo.tokenIDs = {}; + auto callbackPtr = std::make_shared(scopeInfo); + callbackPtr->ready_ = false; + + int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); + + static PermissionStateFull infoManagerTestStateA = { + .permissionName = "ohos.permission.GET_BUNDLE_INFO", + .grantFlags = {1}, + .grantStatus = {PERMISSION_DENIED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static PermissionStateFull infoManagerTestStateB = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PERMISSION_DENIED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_SYSTEM_CORE, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateA, infoManagerTestStateB} + }; + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_DENIED, res); + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_GRANTED, res); + ASSERT_EQ(true, callbackPtr->ready_); + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.GET_BUNDLE_INFO"); + ASSERT_EQ(PERMISSION_DENIED, res); + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.GET_BUNDLE_INFO", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(true, callbackPtr->ready_); + + res = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, res); + + res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); + ASSERT_EQ(RET_SUCCESS, res); +} + +/** + * @tc.name: RegisterPermStateChangeCallback004 + * @tc.desc: RegisterPermStateChangeCallback permList + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback004, TestSize.Level1) +{ + PermStateChangeScope scopeInfo; + scopeInfo.permList = {"ohos.permission.GET_BUNDLE_INFO", "ohos.permission.CAMERA"}; + scopeInfo.tokenIDs = {555555}; // 555555为模拟的tokenid + auto callbackPtr = std::make_shared(scopeInfo); + callbackPtr->ready_ = false; + + int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); + + static PermissionStateFull infoManagerTestStateA = { + .permissionName = "ohos.permission.GET_BUNDLE_INFO", + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static PermissionStateFull infoManagerTestStateB = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateA, infoManagerTestStateB} + }; + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_GRANTED, res); + res = AccessTokenKit::RevokePermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_DENIED, res); + ASSERT_EQ(false, callbackPtr->ready_); + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.GET_BUNDLE_INFO"); + ASSERT_EQ(PERMISSION_GRANTED, res); + res = AccessTokenKit::RevokePermission(tokenID, "ohos.permission.GET_BUNDLE_INFO", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(false, callbackPtr->ready_); + + res = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, res); + + res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); + ASSERT_EQ(RET_SUCCESS, res); +} + +/** + * @tc.name: RegisterPermStateChangeCallback005 + * @tc.desc: RegisterPermStateChangeCallback permList + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback005, TestSize.Level1) +{ + static PermissionStateFull infoManagerTestStateA = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PERMISSION_DENIED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static PermissionStateFull infoManagerTestStateB = { + .permissionName = "ohos.permission.GET_BUNDLE_INFO", + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} + }; + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateA, infoManagerTestStateB} + }; + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, infoManagerTestPolicyPrams); + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + PermStateChangeScope scopeInfo; + scopeInfo.permList = {"ohos.permission.GET_BUNDLE_INFO", "ohos.permission.CAMERA"}; + scopeInfo.tokenIDs = {tokenID, 0}; + auto callbackPtr = std::make_shared(scopeInfo); + callbackPtr->ready_ = false; + + int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA"); + ASSERT_EQ(PERMISSION_DENIED, res); + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.CAMERA", 2); + ASSERT_EQ(RET_SUCCESS, res); + ASSERT_EQ(true, callbackPtr->ready_); + + callbackPtr->ready_ = false; + res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.GET_BUNDLE_INFO"); + ASSERT_EQ(PERMISSION_GRANTED, res); + res = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.GET_BUNDLE_INFO", 2); + ASSERT_EQ(RET_SUCCESS, res); + + ASSERT_EQ(false, callbackPtr->ready_); + + res = AccessTokenKit::DeleteToken(tokenID); + ASSERT_EQ(RET_SUCCESS, res); + + res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); + ASSERT_EQ(RET_SUCCESS, res); +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h new file mode 100644 index 000000000..2328ec147 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_KIT_TEST_H +#define ACCESSTOKEN_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +static const std::string TEST_BUNDLE_NAME = "ohos"; +static const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; +static const std::string TEST_PERMISSION_NAME_BETA = "ohos.permission.BETA"; +static const std::string TEST_PERMISSION_NAME_GAMMA = "ohos.permission.GAMMA"; +static const std::string TEST_PKG_NAME = "com.softbus.test"; +static const int TEST_USER_ID = 0; +static const int TEST_USER_ID_INVALID = -1; +static const unsigned int TEST_TOKENID_INVALID = 0; +static const int INVALID_BUNDLENAME_LEN = 260; +static const int INVALID_APPIDDESC_LEN = 10244; +static const int INVALID_LABEL_LEN = 260; +static const int INVALID_DESCRIPTION_LEN = 260; +static const int INVALID_PERMNAME_LEN = 260; +static const int CYCLE_TIMES = 100; +static const int THREAD_NUM = 3; +static const int INVALID_DCAP_LEN = 1025; +static const int INVALID_DLP_TYPE = 4; +class AccessTokenKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + unsigned int GetAccessTokenID(int userID, std::string bundleName, int instIndex); + void DeleteTestToken() const; + void AllocTestToken() const; + uint64_t selfTokenId_; + std::string udid_; + std::string networkId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_KIT_TEST_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/BUILD.gn new file mode 100644 index 000000000..65e5f21e7 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("accesstokenlib") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_static_library("libnativetoken") { + subsystem_name = "security" + part_name = "access_token" + output_name = "libnativetoken" + + public_configs = [ ":accesstokenlib" ] + + cflags = [ "-Wall" ] + + include_dirs = [ + "include", + "src", + "//third_party/cJSON", + "//third_party/bounds_checking_function/include", + ] + + sources = [ + "src/nativetoken.c", + "src/nativetoken_json_oper.c", + ] + + deps = [ + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + if (build_selinux) { + external_deps += [ "selinux:librestorecon" ] + cflags += [ "-DWITH_SELINUX" ] + } + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken.h b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken.h new file mode 100644 index 000000000..c808faf2c --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#ifndef NATIVE_TOKEN_H +#define NATIVE_TOKEN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MAX_PROCESS_NAME_LEN 256 +#define TOKEN_ID_CFG_FILE_PATH "/data/service/el0/access_token/nativetoken.json" +#define TOKEN_ID_CFG_DIR_PATH "/data/service/el0/access_token" +#define TOKEN_NATIVE_TYPE 1 +#define DEFAULT_AT_VERSION 1 +#define TRANSFER_KEY_WORDS "NativeTokenInfo" +#define MAX_JSON_FILE_LEN 102400 +#define MAX_DCAPS_NUM 32 +#define MAX_DCAP_LEN 1024 +#define MAX_PERM_NUM 64 +#define MAX_PERM_LEN 256 +#define MAX_PARAMTER_LEN 128 +#define SYSTEM_PROP_NATIVE_RECEPTOR "rw.nativetoken.receptor.startup" +#define PATH_MAX_LEN 4096 +#define MAX_RETRY_TIMES 1000 +#define TOKEN_RANDOM_MASK ((1 << 20) - 1) + +#define ATRET_FAILED 1 +#define ATRET_SUCCESS 0 + +#define DCAPS_KEY_NAME "dcaps" +#define PERMS_KEY_NAME "permissions" +#define ACLS_KEY_NAME "nativeAcls" +#define TOKENID_KEY_NAME "tokenId" +#define TOKEN_ATTR_KEY_NAME "tokenAttr" +#define APL_KEY_NAME "APL" +#define VERSION_KEY_NAME "version" +#define PROCESS_KEY_NAME "processName" + +#define SYSTEM_CORE 3 +#define SYSTEM_BASIC 2 +#define NORMAL 1 + +#define INVALID_TOKEN_ID 0 +typedef unsigned int NativeAtId; +typedef unsigned int NativeAtAttr; + +typedef struct { + unsigned int tokenUniqueId : 20; + unsigned int reserved : 7; + unsigned int type : 2; + unsigned int version : 3; +} AtInnerInfo; + +typedef struct { + NativeAtId tokenId; + NativeAtAttr tokenAttr; +} NativeAtIdEx; + +typedef struct TokenList { + NativeAtId tokenId; + int32_t apl; + char *dcaps[MAX_DCAPS_NUM]; + char *perms[MAX_PERM_NUM]; + char *acls[MAX_PERM_NUM]; + int32_t dcapsNum; + int32_t permsNum; + int32_t aclsNum; + char processName[MAX_PROCESS_NAME_LEN + 1]; + struct TokenList *next; +} NativeTokenList; + +typedef struct StrArrayAttribute { + int32_t maxStrNum; + uint32_t maxStrLen; + const char *strKey; +} StrArrayAttr; + +extern int32_t GetFileBuff(const char *cfg, char **retBuff); +#ifdef __cplusplus +} +#endif + +#endif // NATIVE_TOKEN_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_json_oper.h b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_json_oper.h new file mode 100644 index 000000000..2930e0ed7 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_json_oper.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "cJSON.h" +#include "nativetoken.h" + +#ifndef NATIVETOKEN_JSON_OPER_H +#define NATIVETOKEN_JSON_OPER_H + +#ifdef __cplusplus +extern "C" { +#endif + +extern void FreeStrArray(char **arr, int32_t num); +extern uint32_t GetProcessNameFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode); +extern uint32_t GetTokenIdFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode); +extern uint32_t GetAplFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode); +extern uint32_t GetInfoArrFromJson(cJSON *cjsonItem, char *strArr[], int32_t *strNum, StrArrayAttr *attr); +extern cJSON *CreateNativeTokenJsonObject(const NativeTokenList *curr); +extern uint32_t UpdateGoalItemFromRecord(const NativeTokenList *tokenNode, cJSON *record); + +#ifdef __cplusplus +} +#endif + +#endif // NATIVETOKEN_JSON_OPER_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_kit.h b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_kit.h new file mode 100644 index 000000000..34142026b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_kit.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_NATIVE_TOKEN_H +#define INTERFACES_INNER_KITS_NATIVE_TOKEN_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct TokenInfoParams { + int32_t dcapsNum; + int32_t permsNum; + int32_t aclsNum; + const char **dcaps; + const char **perms; + const char **acls; + const char *processName; + const char *aplStr; +} NativeTokenInfoParams; + +extern uint64_t GetAccessTokenId(NativeTokenInfoParams *nativeProcInfo); + +#ifdef __cplusplus +} +#endif + +#endif // INTERFACES_INNER_KITS_NATIVE_TOKEN_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_log.h b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_log.h new file mode 100644 index 000000000..377726427 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/include/nativetoken_log.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_LOG_H +#define ACCESSTOKEN_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#define AT_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt, ##__VA_ARGS__) +#define AT_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt, ##__VA_ARGS__) +#define AT_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt, ##__VA_ARGS__) +#define AT_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, fmt, ##__VA_ARGS__) +#define AT_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, fmt, ##__VA_ARGS__) + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#undef LOG_TAG +#undef LOG_DOMAIN + +#else + +#include +#include + +/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */ +#define LOG_TAG "accssToken_" + +#define AT_LOG_DEBUG(fmt, ...) printf("[%s] debug: " fmt "\n", LOG_TAG, ##__VA_ARGS__) +#define AT_LOG_INFO(fmt, ...) printf("[%s] info: " fmt "\n", LOG_TAG, ##__VA_ARGS__) +#define AT_LOG_WARN(fmt, ...) printf("[%s] warn: " fmt "\n", LOG_TAG, ##__VA_ARGS__) +#define AT_LOG_ERROR(fmt, ...) printf("[%s] error: " fmt "\n", LOG_TAG, ##__VA_ARGS__) +#define AT_LOG_FATAL(fmt, ...) printf("[%s] fatal: " fmt "\n", LOG_TAG, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // ACCESSTOKEN_LOG_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken.c b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken.c new file mode 100644 index 000000000..d9c08e8db --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken.c @@ -0,0 +1,666 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "nativetoken.h" + +#ifdef WITH_SELINUX +#include +#endif // WITH_SELINUX + +#include +#include +#include +#include +#include +#include +#include +#include "securec.h" +#include "nativetoken_json_oper.h" +#include "nativetoken_kit.h" +#include "nativetoken_log.h" + + +NativeTokenList *g_tokenListHead; +int32_t g_isNativeTokenInited = 0; + +int32_t GetFileBuff(const char *cfg, char **retBuff) +{ + struct stat fileStat; + + char filePath[PATH_MAX_LEN + 1] = {0}; + if (realpath(cfg, filePath) == NULL) { + if (errno == ENOENT) { + /* file doesn't exist */ + *retBuff = NULL; + return ATRET_SUCCESS; + } + AT_LOG_ERROR("[ATLIB-%s]:invalid filePath.", __func__); + return ATRET_FAILED; + } + + if (stat(filePath, &fileStat) != 0) { + AT_LOG_ERROR("[ATLIB-%s]:stat file failed.", __func__); + return ATRET_FAILED; + } + + if (fileStat.st_size == 0) { + *retBuff = NULL; + return ATRET_SUCCESS; + } + + if (fileStat.st_size > MAX_JSON_FILE_LEN) { + AT_LOG_ERROR("[ATLIB-%s]:stat file size is invalid.", __func__); + return ATRET_FAILED; + } + + size_t fileSize = (unsigned)fileStat.st_size; + + FILE *cfgFd = fopen(filePath, "r"); + if (cfgFd == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:fopen file failed.", __func__); + return ATRET_FAILED; + } + + char *buff = (char *)malloc((size_t)(fileSize + 1)); + if (buff == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:memory alloc failed.", __func__); + fclose(cfgFd); + return ATRET_FAILED; + } + + if (fread(buff, fileSize, 1, cfgFd) != 1) { + AT_LOG_ERROR("[ATLIB-%s]:fread failed.", __func__); + free(buff); + buff = NULL; + fclose(cfgFd); + return ATRET_FAILED; + } + buff[fileSize] = '\0'; + *retBuff = buff; + fclose(cfgFd); + return ATRET_SUCCESS; +} + +static void StrAttrSet(StrArrayAttr *attr, uint32_t maxStrLen, int32_t maxStrNum, const char *strKey) +{ + attr->maxStrLen = maxStrLen; + attr->maxStrNum = maxStrNum; + attr->strKey = strKey; +} + +static int32_t GetNativeTokenFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode) +{ + uint32_t ret; + StrArrayAttr attr; + + ret = GetProcessNameFromJson(cjsonItem, tokenNode); + ret |= GetTokenIdFromJson(cjsonItem, tokenNode); + ret |= GetAplFromJson(cjsonItem, tokenNode); + + StrAttrSet(&attr, MAX_DCAP_LEN, MAX_DCAPS_NUM, DCAPS_KEY_NAME); + ret |= GetInfoArrFromJson(cjsonItem, tokenNode->dcaps, &(tokenNode->dcapsNum), &attr); + if (ret != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:GetInfoArrFromJson failed for dcaps.", __func__); + return ATRET_FAILED; + } + + StrAttrSet(&attr, MAX_PERM_LEN, MAX_PERM_NUM, PERMS_KEY_NAME); + ret = GetInfoArrFromJson(cjsonItem, tokenNode->perms, &(tokenNode->permsNum), &attr); + if (ret != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenNode->dcapsNum - 1); + AT_LOG_ERROR("[ATLIB-%s]:GetInfoArrFromJson failed for perms.", __func__); + return ATRET_FAILED; + } + + StrAttrSet(&attr, MAX_PERM_LEN, MAX_PERM_NUM, ACLS_KEY_NAME); + ret = GetInfoArrFromJson(cjsonItem, tokenNode->acls, &(tokenNode->aclsNum), &attr); + if (ret != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenNode->dcapsNum - 1); + FreeStrArray(tokenNode->perms, tokenNode->permsNum - 1); + AT_LOG_ERROR("[ATLIB-%s]:GetInfoArrFromJson failed for acls.", __func__); + return ATRET_FAILED; + } + return ATRET_SUCCESS; +} + +static int32_t GetTokenList(const cJSON *object) +{ + NativeTokenList *tmp = NULL; + + if (object == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:object is null.", __func__); + return ATRET_FAILED; + } + int32_t arraySize = cJSON_GetArraySize(object); + + for (int32_t i = 0; i < arraySize; i++) { + tmp = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (tmp == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:memory alloc failed.", __func__); + return ATRET_FAILED; + } + cJSON *cjsonItem = cJSON_GetArrayItem(object, i); + if (cjsonItem == NULL) { + free(tmp); + AT_LOG_ERROR("[ATLIB-%s]:cJSON_GetArrayItem failed.", __func__); + return ATRET_FAILED; + } + if (GetNativeTokenFromJson(cjsonItem, tmp) != ATRET_SUCCESS) { + free(tmp); + return ATRET_FAILED; + } + + tmp->next = g_tokenListHead->next; + g_tokenListHead->next = tmp; + } + return ATRET_SUCCESS; +} + +static int32_t ParseTokenInfo(void) +{ + char *fileBuff = NULL; + cJSON *record = NULL; + int32_t ret; + + ret = GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff); + if (ret != ATRET_SUCCESS) { + return ret; + } + if (fileBuff == NULL) { + return ATRET_SUCCESS; + } + record = cJSON_Parse(fileBuff); + free(fileBuff); + fileBuff = NULL; + + ret = GetTokenList(record); + cJSON_Delete(record); + + return ret; +} + +static int32_t CreateCfgFile(void) +{ + int32_t fd = open(TOKEN_ID_CFG_FILE_PATH, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); + if (fd < 0) { + AT_LOG_ERROR("[ATLIB-%s]:open failed.", __func__); + return ATRET_FAILED; + } + +#ifdef WITH_SELINUX + Restorecon(TOKEN_ID_CFG_FILE_PATH); +#endif // WITH_SELINUX + + close(fd); + fd = -1; + + struct stat buf; + if (stat(TOKEN_ID_CFG_DIR_PATH, &buf) != 0) { + AT_LOG_ERROR("[ATLIB-%s]:stat folder path is invalid %d.", + __func__, errno); + return ATRET_FAILED; + } + if (chown(TOKEN_ID_CFG_FILE_PATH, buf.st_uid, buf.st_gid) != 0) { + AT_LOG_ERROR("[ATLIB-%s]:chown failed, errno is %d.", __func__, errno); + return ATRET_FAILED; + } + + return ATRET_SUCCESS; +} + +static int32_t AtlibInit(void) +{ + g_tokenListHead = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (g_tokenListHead == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:g_tokenListHead memory alloc failed.", __func__); + return ATRET_FAILED; + } + g_tokenListHead->next = NULL; + + int32_t ret = ParseTokenInfo(); + if (ret != ATRET_SUCCESS) { + free(g_tokenListHead); + g_tokenListHead = NULL; + return ret; + } + + if (g_tokenListHead->next == NULL) { + if (CreateCfgFile() != ATRET_SUCCESS) { + return ATRET_FAILED; + } + } + g_isNativeTokenInited = 1; + + return ATRET_SUCCESS; +} + +static int32_t GetRandomTokenId(uint32_t *randNum) +{ + uint32_t random; + ssize_t len; + int32_t fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + return ATRET_FAILED; + } + len = read(fd, &random, sizeof(random)); + (void)close(fd); + + if (len != sizeof(random)) { + AT_LOG_ERROR("[ATLIB-%s]:read failed.", __func__); + return ATRET_FAILED; + } + *randNum = random; + return ATRET_SUCCESS; +} + +static int32_t IsTokenUniqueIdExist(uint32_t tokenUniqueId) +{ + NativeTokenList *tokenNode = g_tokenListHead->next; + while (tokenNode != NULL) { + AtInnerInfo *existToken = (AtInnerInfo *)&(tokenNode->tokenId); + if (tokenUniqueId == existToken->tokenUniqueId) { + return 1; + } + tokenNode = tokenNode->next; + } + return 0; +} + +static NativeAtId CreateNativeTokenId(void) +{ + uint32_t rand; + NativeAtId tokenId; + int32_t ret; + AtInnerInfo *innerId = (AtInnerInfo *)(&tokenId); + int32_t retry = MAX_RETRY_TIMES; + + while (retry > 0) { + ret = GetRandomTokenId(&rand); + if (ret != ATRET_SUCCESS) { + return INVALID_TOKEN_ID; + } + if (IsTokenUniqueIdExist(rand & (TOKEN_RANDOM_MASK)) == 0) { + break; + } + retry--; + } + if (retry == 0) { + AT_LOG_ERROR("[ATLIB-%s]:retry times is 0.", __func__); + return INVALID_TOKEN_ID; + } + + innerId->reserved = 0; + innerId->tokenUniqueId = rand & (TOKEN_RANDOM_MASK); + innerId->type = TOKEN_NATIVE_TYPE; + innerId->version = 1; + return tokenId; +} + +static int32_t GetAplLevel(const char *aplStr) +{ + if (aplStr == NULL) { + return 0; + } + if (strcmp(aplStr, "system_core") == 0) { + return SYSTEM_CORE; // system_core means apl level is 3 + } + if (strcmp(aplStr, "system_basic") == 0) { + return SYSTEM_BASIC; // system_basic means apl level is 2 + } + if (strcmp(aplStr, "normal") == 0) { + return NORMAL; + } + AT_LOG_ERROR("[ATLIB-%s]:aplStr is invalid.", __func__); + return 0; +} + +static void WriteToFile(const cJSON *root) +{ + size_t strLen; + size_t writtenLen; + + char *jsonStr = NULL; + jsonStr = cJSON_PrintUnformatted(root); + if (jsonStr == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_PrintUnformatted failed.", __func__); + return; + } + + do { + int32_t fd = open(TOKEN_ID_CFG_FILE_PATH, O_RDWR | O_CREAT | O_TRUNC, + S_IRUSR | S_IWUSR | S_IRGRP); + if (fd < 0) { + AT_LOG_ERROR("[ATLIB-%s]:open failed.", __func__); + break; + } + strLen = strlen(jsonStr); + writtenLen = write(fd, (void *)jsonStr, (size_t)strLen); + close(fd); + if (writtenLen != strLen) { + AT_LOG_ERROR("[ATLIB-%s]:write failed, writtenLen is %zu.", __func__, writtenLen); + break; + } + } while (0); + + cJSON_free(jsonStr); + return; +} + +static void SaveTokenIdToCfg(const NativeTokenList *curr) +{ + char *fileBuff = NULL; + cJSON *record = NULL; + int32_t ret; + + ret = GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff); + if (ret != ATRET_SUCCESS) { + return; + } + + if (fileBuff == NULL) { + record = cJSON_CreateArray(); + } else { + record = cJSON_Parse(fileBuff); + free(fileBuff); + fileBuff = NULL; + } + + if (record == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:get record failed.", __func__); + return; + } + + cJSON *node = CreateNativeTokenJsonObject(curr); + if (node == NULL) { + cJSON_Delete(record); + return; + } + cJSON_AddItemToArray(record, node); + + WriteToFile(record); + cJSON_Delete(record); + return; +} + +static uint32_t CheckStrArray(const char **strArray, int32_t strNum, int32_t maxNum, uint32_t maxInfoLen) +{ + if (((strArray == NULL) && (strNum != 0)) || + (strNum > maxNum) || (strNum < 0)) { + AT_LOG_ERROR("[ATLIB-%s]:strArray is null or strNum is invalid.", __func__); + return ATRET_FAILED; + } + for (int32_t i = 0; i < strNum; i++) { + if ((strArray[i] == NULL) || (strlen(strArray[i]) > maxInfoLen) || (strlen(strArray[i]) == 0)) { + AT_LOG_ERROR("[ATLIB-%s]:strArray[%d] length is invalid.", __func__, i); + return ATRET_FAILED; + } + } + return ATRET_SUCCESS; +} + +static uint32_t CheckProcessInfo(NativeTokenInfoParams *tokenInfo, int32_t *aplRet) +{ + if ((tokenInfo->processName == NULL) || strlen(tokenInfo->processName) > MAX_PROCESS_NAME_LEN || + strlen(tokenInfo->processName) == 0) { + AT_LOG_ERROR("[ATLIB-%s]:processName is invalid.", __func__); + return ATRET_FAILED; + } + uint32_t retDcap = CheckStrArray(tokenInfo->dcaps, tokenInfo->dcapsNum, MAX_DCAPS_NUM, MAX_DCAP_LEN); + if (retDcap != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:dcaps is invalid.", __func__); + return ATRET_FAILED; + } + uint32_t retPerm = CheckStrArray(tokenInfo->perms, tokenInfo->permsNum, MAX_PERM_NUM, MAX_PERM_LEN); + if (retPerm != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:perms is invalid.", __func__); + return ATRET_FAILED; + } + + uint32_t retAcl = CheckStrArray(tokenInfo->acls, tokenInfo->aclsNum, MAX_PERM_NUM, MAX_PERM_LEN); + if (retAcl != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:acls is invalid.", __func__); + return ATRET_FAILED; + } + + if (tokenInfo->aclsNum > tokenInfo->permsNum) { + AT_LOG_ERROR("[ATLIB-%s]:aclsNum is invalid.", __func__); + return ATRET_FAILED; + } + int32_t apl = GetAplLevel(tokenInfo->aplStr); + if (apl == 0) { + return ATRET_FAILED; + } + *aplRet = apl; + return ATRET_SUCCESS; +} + +static uint32_t CreateStrArray(int32_t num, const char **strArr, char **strArrRes) +{ + for (int32_t i = 0; i < num; i++) { + strArrRes[i] = (char *)malloc(sizeof(char) * (strlen(strArr[i]) + 1)); + if (strArrRes[i] == NULL || + (strcpy_s(strArrRes[i], strlen(strArr[i]) + 1, strArr[i]) != EOK)) { + AT_LOG_ERROR("[ATLIB-%s]:copy strArr[%d] failed.", __func__, i); + FreeStrArray(strArrRes, i); + return ATRET_FAILED; + } + } + return ATRET_SUCCESS; +} + +static uint32_t AddNewTokenToListAndFile(const NativeTokenInfoParams *tokenInfo, + int32_t aplIn, NativeAtId *tokenId) +{ + NativeTokenList *tokenNode; + NativeAtId id; + + id = CreateNativeTokenId(); + if (id == INVALID_TOKEN_ID) { + return ATRET_FAILED; + } + + tokenNode = (NativeTokenList *)malloc(sizeof(NativeTokenList)); + if (tokenNode == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:memory alloc failed.", __func__); + return ATRET_FAILED; + } + tokenNode->tokenId = id; + tokenNode->apl = aplIn; + if (strcpy_s(tokenNode->processName, MAX_PROCESS_NAME_LEN + 1, tokenInfo->processName) != EOK) { + AT_LOG_ERROR("[ATLIB-%s]:strcpy_s failed.", __func__); + free(tokenNode); + return ATRET_FAILED; + } + tokenNode->dcapsNum = tokenInfo->dcapsNum; + tokenNode->permsNum = tokenInfo->permsNum; + tokenNode->aclsNum = tokenInfo->aclsNum; + + if (CreateStrArray(tokenInfo->dcapsNum, tokenInfo->dcaps, tokenNode->dcaps) != ATRET_SUCCESS) { + free(tokenNode); + return ATRET_FAILED; + } + if (CreateStrArray(tokenInfo->permsNum, tokenInfo->perms, tokenNode->perms) != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenInfo->dcapsNum - 1); + free(tokenNode); + return ATRET_FAILED; + } + if (CreateStrArray(tokenInfo->aclsNum, tokenInfo->acls, tokenNode->acls) != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenInfo->dcapsNum - 1); + FreeStrArray(tokenNode->perms, tokenInfo->permsNum - 1); + free(tokenNode); + return ATRET_FAILED; + } + + tokenNode->next = g_tokenListHead->next; + g_tokenListHead->next = tokenNode; + + *tokenId = id; + + SaveTokenIdToCfg(tokenNode); + return ATRET_SUCCESS; +} + +static int32_t CompareTokenInfo(const NativeTokenList *tokenNode, + const char **dcapsIn, int32_t dcapNumIn, int32_t aplIn) +{ + if (tokenNode->apl != aplIn) { + return 1; + } + if (tokenNode->dcapsNum != dcapNumIn) { + return 1; + } + for (int32_t i = 0; i < dcapNumIn; i++) { + if (strcmp(tokenNode->dcaps[i], dcapsIn[i]) != 0) { + return 1; + } + } + return 0; +} + +static int32_t ComparePermsInfo(const NativeTokenList *tokenNode, + const char **permsIn, int32_t permsNumIn) +{ + if (tokenNode->permsNum != permsNumIn) { + return 1; + } + for (int32_t i = 0; i < permsNumIn; i++) { + if (strcmp(tokenNode->perms[i], permsIn[i]) != 0) { + return 1; + } + } + return 0; +} + +static uint32_t UpdateStrArrayInList(char *strArr[], int32_t *strNum, + const char **strArrNew, int32_t strNumNew) +{ + for (int32_t i = 0; i < *strNum; i++) { + free(strArr[i]); + strArr[i] = NULL; + } + + *strNum = strNumNew; + for (int32_t i = 0; i < strNumNew; i++) { + size_t len = strlen(strArrNew[i]) + 1; + strArr[i] = (char *)malloc(sizeof(char) * len); + if (strArr[i] == NULL || (strcpy_s(strArr[i], len, strArrNew[i]) != EOK)) { + AT_LOG_ERROR("[ATLIB-%s]:copy strArr[%d] failed.", __func__, i); + FreeStrArray(strArr, i); + return ATRET_FAILED; + } + } + return ATRET_SUCCESS; +} + +static uint32_t UpdateTokenInfoInList(NativeTokenList *tokenNode, + const NativeTokenInfoParams *tokenInfo) +{ + tokenNode->apl = GetAplLevel(tokenInfo->aplStr); + + uint32_t ret = UpdateStrArrayInList(tokenNode->dcaps, &(tokenNode->dcapsNum), + tokenInfo->dcaps, tokenInfo->dcapsNum); + if (ret != ATRET_SUCCESS) { + return ret; + } + ret = UpdateStrArrayInList(tokenNode->perms, &(tokenNode->permsNum), + tokenInfo->perms, tokenInfo->permsNum); + if (ret != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenNode->dcapsNum - 1); + } + ret = UpdateStrArrayInList(tokenNode->acls, &(tokenNode->aclsNum), + tokenInfo->acls, tokenInfo->aclsNum); + if (ret != ATRET_SUCCESS) { + FreeStrArray(tokenNode->dcaps, tokenNode->dcapsNum - 1); + FreeStrArray(tokenNode->perms, tokenNode->permsNum - 1); + } + return ret; +} + +static uint32_t UpdateInfoInCfgFile(const NativeTokenList *tokenNode) +{ + cJSON *record = NULL; + char *fileBuff = NULL; + uint32_t ret; + + if (GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff) != ATRET_SUCCESS) { + return ATRET_FAILED; + } + + if (fileBuff == NULL) { + record = cJSON_CreateArray(); + } else { + record = cJSON_Parse(fileBuff); + free(fileBuff); + fileBuff = NULL; + } + + if (record == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:get record failed.", __func__); + return ATRET_FAILED; + } + + ret = UpdateGoalItemFromRecord(tokenNode, record); + if (ret != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:UpdateGoalItemFromRecord failed.", __func__); + cJSON_Delete(record); + return ATRET_FAILED; + } + + WriteToFile(record); + cJSON_Delete(record); + return ATRET_SUCCESS; +} + +uint64_t GetAccessTokenId(NativeTokenInfoParams *tokenInfo) +{ + NativeAtId tokenId = 0; + uint64_t result = 0; + int32_t apl; + NativeAtIdEx *atPoint = (NativeAtIdEx *)(&result); + + if ((g_isNativeTokenInited == 0) && (AtlibInit() != ATRET_SUCCESS)) { + return INVALID_TOKEN_ID; + } + uint32_t ret = CheckProcessInfo(tokenInfo, &apl); + if (ret != ATRET_SUCCESS) { + return INVALID_TOKEN_ID; + } + + NativeTokenList *tokenNode = g_tokenListHead->next; + while (tokenNode != NULL) { + if (strcmp(tokenNode->processName, tokenInfo->processName) == 0) { + tokenId = tokenNode->tokenId; + break; + } + tokenNode = tokenNode->next; + } + + if (tokenNode == NULL) { + ret = AddNewTokenToListAndFile(tokenInfo, apl, &tokenId); + } else { + int32_t needTokenUpdate = CompareTokenInfo(tokenNode, tokenInfo->dcaps, tokenInfo->dcapsNum, apl); + int32_t needPermUpdate = ComparePermsInfo(tokenNode, tokenInfo->perms, tokenInfo->permsNum); + if ((needTokenUpdate != 0) || (needPermUpdate != 0)) { + ret = UpdateTokenInfoInList(tokenNode, tokenInfo); + ret |= UpdateInfoInCfgFile(tokenNode); + } + } + if (ret != ATRET_SUCCESS) { + return INVALID_TOKEN_ID; + } + + atPoint->tokenId = tokenId; + atPoint->tokenAttr = 0; + return result; +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c new file mode 100644 index 000000000..25062d1b7 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "nativetoken_json_oper.h" +#include +#include +#include +#include "nativetoken_log.h" + +void FreeStrArray(char **arr, int32_t num) +{ + for (int32_t i = 0; i <= num; i++) { + if (arr[i] != NULL) { + free(arr[i]); + arr[i] = NULL; + } + } +} + +uint32_t GetProcessNameFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode) +{ + cJSON *processNameJson = cJSON_GetObjectItem(cjsonItem, PROCESS_KEY_NAME); + if (!cJSON_IsString(processNameJson) || (strlen(processNameJson->valuestring) > MAX_PROCESS_NAME_LEN)) { + AT_LOG_ERROR("[ATLIB-%s]:processNameJson is invalid.", __func__); + return ATRET_FAILED; + } + + if (strcpy_s(tokenNode->processName, MAX_PROCESS_NAME_LEN + 1, processNameJson->valuestring) != EOK) { + AT_LOG_ERROR("[ATLIB-%s]:strcpy_s failed.", __func__); + return ATRET_FAILED; + } + return ATRET_SUCCESS; +} + +uint32_t GetTokenIdFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode) +{ + cJSON *tokenIdJson = cJSON_GetObjectItem(cjsonItem, TOKENID_KEY_NAME); + if ((!cJSON_IsNumber(tokenIdJson)) || (cJSON_GetNumberValue(tokenIdJson) <= 0)) { + AT_LOG_ERROR("[ATLIB-%s]:tokenIdJson is invalid.", __func__); + return ATRET_FAILED; + } + + AtInnerInfo *atIdInfo = (AtInnerInfo *)&(tokenIdJson->valueint); + if (atIdInfo->type != TOKEN_NATIVE_TYPE) { + AT_LOG_ERROR("[ATLIB-%s]:tokenId type is invalid.", __func__); + return ATRET_FAILED; + } + + tokenNode->tokenId = (NativeAtId)tokenIdJson->valueint; + return ATRET_SUCCESS; +} + +uint32_t GetAplFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode) +{ + cJSON *aplJson = cJSON_GetObjectItem(cjsonItem, APL_KEY_NAME); + if (!cJSON_IsNumber(aplJson)) { + AT_LOG_ERROR("[ATLIB-%s]:aplJson is invalid.", __func__); + return ATRET_FAILED; + } + int32_t apl = cJSON_GetNumberValue(aplJson); + if (apl <= 0 || apl > SYSTEM_CORE) { + AT_LOG_ERROR("[ATLIB-%s]:apl = %d in file is invalid.", __func__, apl); + return ATRET_FAILED; + } + tokenNode->apl = aplJson->valueint; + return ATRET_SUCCESS; +} + +uint32_t GetInfoArrFromJson(cJSON *cjsonItem, char *strArr[], int32_t *strNum, StrArrayAttr *attr) +{ + cJSON *strArrJson = cJSON_GetObjectItem(cjsonItem, attr->strKey); + int32_t size = cJSON_GetArraySize(strArrJson); + if (size > attr->maxStrNum) { + AT_LOG_ERROR("[ATLIB-%s]:size = %d is invalid.", __func__, size); + return ATRET_FAILED; + } + *strNum = size; + + for (int32_t i = 0; i < size; i++) { + cJSON *item = cJSON_GetArrayItem(strArrJson, i); + if ((item == NULL) || (!cJSON_IsString(item)) || (item->valuestring == NULL)) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_GetArrayItem failed.", __func__); + return ATRET_FAILED; + } + size_t length = strlen(item->valuestring); + if (length > attr->maxStrLen) { + AT_LOG_ERROR("[ATLIB-%s]:item length %zu is invalid.", __func__, length); + return ATRET_FAILED; + } + strArr[i] = (char *)malloc(sizeof(char) * (length + 1)); + if (strArr[i] == NULL) { + FreeStrArray(strArr, i - 1); + AT_LOG_ERROR("[ATLIB-%s]:malloc invalid.", __func__); + return ATRET_FAILED; + } + if (strcpy_s(strArr[i], length + 1, item->valuestring) != EOK) { + FreeStrArray(strArr, i); + AT_LOG_ERROR("[ATLIB-%s]:strcpy_s failed.", __func__); + return ATRET_FAILED; + } + } + return ATRET_SUCCESS; +} + +static int32_t AddStrArrayInfo(cJSON *object, char* const strArray[], int32_t strNum, const char *strKey) +{ + cJSON *strJsonArr = cJSON_CreateArray(); + if (strJsonArr == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:CreateArray failed, strKey :%s.", __func__, strKey); + return ATRET_FAILED; + } + for (int32_t i = 0; i < strNum; i++) { + cJSON *item = cJSON_CreateString(strArray[i]); + if (item == NULL || !cJSON_AddItemToArray(strJsonArr, item)) { + AT_LOG_ERROR("[ATLIB-%s]:AddItemToArray failed, strKey : %s.", __func__, strKey); + cJSON_Delete(item); + cJSON_Delete(strJsonArr); + return ATRET_FAILED; + } + } + if (!cJSON_AddItemToObject(object, strKey, strJsonArr)) { + AT_LOG_ERROR("[ATLIB-%s]:AddItemToObject failed, strKey : %s.", __func__, strKey); + cJSON_Delete(strJsonArr); + return ATRET_FAILED; + } + return ATRET_SUCCESS; +} + +int32_t SetNativeTokenJsonObject(const NativeTokenList *curr, cJSON *object) +{ + cJSON *item = cJSON_CreateString(curr->processName); + if (item == NULL || !cJSON_AddItemToObject(object, PROCESS_KEY_NAME, item)) { + AT_LOG_ERROR("[ATLIB-%s]:processName cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(item); + return ATRET_FAILED; + } + + item = cJSON_CreateNumber(curr->apl); + if (item == NULL || !cJSON_AddItemToObject(object, APL_KEY_NAME, item)) { + AT_LOG_ERROR("[ATLIB-%s]:APL cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(item); + return ATRET_FAILED; + } + + item = cJSON_CreateNumber(DEFAULT_AT_VERSION); + if (item == NULL || !cJSON_AddItemToObject(object, VERSION_KEY_NAME, item)) { + AT_LOG_ERROR("[ATLIB-%s]:version cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(item); + return ATRET_FAILED; + } + + item = cJSON_CreateNumber(curr->tokenId); + if (item == NULL || !cJSON_AddItemToObject(object, TOKENID_KEY_NAME, item)) { + AT_LOG_ERROR("[ATLIB-%s]:tokenId cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(item); + return ATRET_FAILED; + } + + item = cJSON_CreateNumber(0); + if (item == NULL || !cJSON_AddItemToObject(object, TOKEN_ATTR_KEY_NAME, item)) { + AT_LOG_ERROR("[ATLIB-%s]:tokenAttr cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(item); + return ATRET_FAILED; + } + + int32_t ret = AddStrArrayInfo(object, curr->dcaps, curr->dcapsNum, DCAPS_KEY_NAME); + if (ret != ATRET_SUCCESS) { + return ret; + } + + ret = AddStrArrayInfo(object, curr->perms, curr->permsNum, PERMS_KEY_NAME); + if (ret != ATRET_SUCCESS) { + return ret; + } + + ret = AddStrArrayInfo(object, curr->acls, curr->aclsNum, ACLS_KEY_NAME); + return ret; +} + +cJSON *CreateNativeTokenJsonObject(const NativeTokenList *curr) +{ + cJSON *object = cJSON_CreateObject(); + if (object == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_CreateObject failed.", __func__); + return NULL; + } + if (SetNativeTokenJsonObject(curr, object) != ATRET_SUCCESS) { + cJSON_Delete(object); + return NULL; + } + + return object; +} + +static uint32_t UpdateStrArrayType(char* const strArr[], int32_t strNum, const char *strKey, cJSON *record) +{ + cJSON *strArrJson = cJSON_CreateArray(); + if (strArrJson == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_CreateArray failed.", __func__); + return ATRET_FAILED; + } + for (int32_t i = 0; i < strNum; i++) { + cJSON *item = cJSON_CreateString(strArr[i]); + if (item == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_CreateString failed.", __func__); + cJSON_Delete(strArrJson); + return ATRET_FAILED; + } + if (!cJSON_AddItemToArray(strArrJson, item)) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_AddItemToArray failed.", __func__); + cJSON_Delete(item); + cJSON_Delete(strArrJson); + return ATRET_FAILED; + } + } + if (cJSON_GetObjectItem(record, strKey) != NULL) { + if (!cJSON_ReplaceItemInObject(record, strKey, strArrJson)) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_ReplaceItemInObject failed.", __func__); + cJSON_Delete(strArrJson); + return ATRET_FAILED; + } + } else { + if (!cJSON_AddItemToObject(record, strKey, strArrJson)) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_AddItemToObject failed.", __func__); + cJSON_Delete(strArrJson); + return ATRET_FAILED; + } + } + + return ATRET_SUCCESS; +} + +static uint32_t UpdateItemcontent(const NativeTokenList *tokenNode, cJSON *record) +{ + cJSON *itemApl = cJSON_CreateNumber(tokenNode->apl); + if (itemApl == NULL) { + return ATRET_FAILED; + } + if (!cJSON_ReplaceItemInObject(record, APL_KEY_NAME, itemApl)) { + cJSON_Delete(itemApl); + AT_LOG_ERROR("[ATLIB-%s]:APL update failed.", __func__); + return ATRET_FAILED; + } + + uint32_t ret = UpdateStrArrayType(tokenNode->dcaps, tokenNode->dcapsNum, DCAPS_KEY_NAME, record); + if (ret != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:dcaps update failed.", __func__); + return ATRET_FAILED; + } + + ret = UpdateStrArrayType(tokenNode->perms, tokenNode->permsNum, PERMS_KEY_NAME, record); + if (ret != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:perms update failed.", __func__); + return ATRET_FAILED; + } + + ret = UpdateStrArrayType(tokenNode->acls, tokenNode->aclsNum, ACLS_KEY_NAME, record); + if (ret != ATRET_SUCCESS) { + AT_LOG_ERROR("[ATLIB-%s]:acls update failed.", __func__); + return ATRET_FAILED; + } + return ATRET_SUCCESS; +} + +uint32_t UpdateGoalItemFromRecord(const NativeTokenList *tokenNode, cJSON *record) +{ + int32_t arraySize = cJSON_GetArraySize(record); + for (int32_t i = 0; i < arraySize; i++) { + cJSON *cjsonItem = cJSON_GetArrayItem(record, i); + if (cjsonItem == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:cJSON_GetArrayItem failed.", __func__); + return ATRET_FAILED; + } + cJSON *processNameJson = cJSON_GetObjectItem(cjsonItem, PROCESS_KEY_NAME); + if (processNameJson == NULL) { + AT_LOG_ERROR("[ATLIB-%s]:processNameJson is null.", __func__); + return ATRET_FAILED; + } + if (strcmp(processNameJson->valuestring, tokenNode->processName) == 0) { + return UpdateItemcontent(tokenNode, cjsonItem); + } + } + AT_LOG_ERROR("[ATLIB-%s]:cannot find process in config file.", __func__); + return ATRET_FAILED; +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/BUILD.gn new file mode 100644 index 000000000..ca884c8a0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libnativetoken_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//third_party/cJSON", + "//third_party/bounds_checking_function/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + ] + + sources = [ "unittest/src/nativetoken_kit_test.cpp" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libnativetoken_test" ] +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.cpp b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.cpp new file mode 100644 index 000000000..d9f9827e0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.cpp @@ -0,0 +1,738 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "nativetoken_kit_test.h" +#include +#include +#include +#include "securec.h" +#include "nativetoken.h" +#include "nativetoken_kit.h" + +using namespace testing::ext; +using namespace OHOS::Security; + +extern NativeTokenList *g_tokenListHead; +extern int32_t g_isNativeTokenInited; +extern int32_t GetFileBuff(const char *cfg, char **retBuff); + +void TokenLibKitTest::SetUpTestCase() +{} + +void TokenLibKitTest::TearDownTestCase() +{} + +void TokenLibKitTest::SetUp() +{ + g_isNativeTokenInited = 0; +} + +void TokenLibKitTest::TearDown() +{ + while (g_tokenListHead->next != nullptr) { + NativeTokenList *tmp = g_tokenListHead->next; + g_tokenListHead->next = tmp->next; + free(tmp); + tmp = nullptr; + } +} + +int32_t Start(const char *processName) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + uint64_t tokenId; + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + const char **acls = new const char *[1]; + acls[0] = "ohos.permission.test1"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 2, + .permsNum = 2, + .aclsNum = 1, + .dcaps = dcaps, + .perms = perms, + .acls = acls, + .processName = processName, + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + delete[] dcaps; + delete[] perms; + delete[] acls; + return tokenId; +} + +/** + * @tc.name: GetAccessTokenId001 + * @tc.desc: cannot getAccessTokenId with invalid processName. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId001, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + int32_t dcapNum = 2; + uint64_t tokenId; + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = dcapNum, + .permsNum = 2, + .aclsNum = 0, + .dcaps = dcaps, + .perms = perms, + .acls = nullptr, + .aplStr = "system_core", + }; + infoInstance.processName = ""; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + infoInstance.processName = nullptr; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + /* 257 is invalid processName length */ + const std::string invalidProcName (257, 'x'); + infoInstance.processName = invalidProcName.c_str(); + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + /* 255 is valid processName length */ + const std::string validProcName01 (255, 'x'); + infoInstance.processName = validProcName01.c_str(); + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + /* 256 is valid processName length */ + const std::string validProcName02 (256, 'x'); + infoInstance.processName = validProcName02.c_str(); + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + delete[] dcaps; + delete[] perms; +} + +/** + * @tc.name: GetAccessTokenId002 + * @tc.desc: cannot getAccessTokenId with invalid dcapNum. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId002, TestSize.Level1) +{ + const char **dcaps = new const char *[32]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + int32_t dcapNum = -1; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .permsNum = 0, + .aclsNum = 0, + .dcaps = dcaps, + .perms = nullptr, + .aplStr = "system_core", + }; + infoInstance.dcapsNum = dcapNum; + infoInstance.processName = "GetAccessTokenId002"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + /* 33 is invalid dcapNum */ + dcapNum = 33; + infoInstance.dcapsNum = dcapNum; + infoInstance.processName = "GetAccessTokenId002_00"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + for (int32_t i = 0; i < 32; i++) { + dcaps[i] = "AT_CAP"; + } + /* 32 is valid dcapNum */ + dcapNum = 32; + infoInstance.dcapsNum = dcapNum; + infoInstance.processName = "GetAccessTokenId002_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + /* 31 is valid dcapNum */ + dcapNum = 31; + infoInstance.dcapsNum = dcapNum; + infoInstance.processName = "GetAccessTokenId002_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] dcaps; +} + +/** + * @tc.name: GetAccessTokenId003 + * @tc.desc: cannot getAccessTokenId with invalid dcaps. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId003, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + int32_t dcapNum = 2; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .permsNum = 0, + .aclsNum = 0, + .dcaps = dcaps, + .perms = nullptr, + .aplStr = "system_core", + }; + infoInstance.dcapsNum = dcapNum; + infoInstance.dcaps = nullptr; + infoInstance.processName = "GetAccessTokenId003"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + dcapNum = 0; + infoInstance.dcapsNum = dcapNum; + infoInstance.dcaps = nullptr; + infoInstance.processName = "GetAccessTokenId003_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + dcapNum = 2; + /* 1025 is invalid dcap length */ + const std::string invalidDcap (1025, 'x'); + dcaps[0] = invalidDcap.c_str(); + infoInstance.dcapsNum = dcapNum; + infoInstance.dcaps = dcaps; + infoInstance.processName = "GetAccessTokenId003_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + /* 1024 is valid dcap length */ + const std::string validDcap01 (1024, 'x'); + dcaps[0] = validDcap01.c_str(); + infoInstance.dcapsNum = dcapNum; + infoInstance.dcaps = dcaps; + infoInstance.processName = "GetAccessTokenId003_03"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + /* 1023 is valid dcap length */ + const std::string validDcap02 (1023, 'x'); + dcaps[0] = validDcap02.c_str(); + infoInstance.dcapsNum = dcapNum; + infoInstance.dcaps = dcaps; + infoInstance.processName = "GetAccessTokenId003_04"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] dcaps; +} + +/** + * @tc.name: GetAccessTokenId004 + * @tc.desc: cannot getAccessTokenId with invalid APL. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId004, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + int32_t dcapNum = 2; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = dcapNum, + .permsNum = 0, + .aclsNum = 0, + .dcaps = dcaps, + .perms = nullptr, + .processName = "GetAccessTokenId003", + }; + + infoInstance.aplStr = nullptr, + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + infoInstance.aplStr = "system_invalid", + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + delete[] dcaps; +} + +/** + * @tc.name: GetAccessTokenId005 + * @tc.desc: Get AccessTokenId successfully. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId005, TestSize.Level1) +{ + uint64_t tokenId01 = Start("GetAccessTokenId005"); + ASSERT_NE(tokenId01, 0); + uint64_t tokenId02 = Start("GetAccessTokenId005"); + ASSERT_NE(tokenId02, 0); + + ASSERT_EQ(tokenId01, tokenId02); +} + +/** + * @tc.name: GetAccessTokenId006 + * @tc.desc: Get AccessTokenId with new processName and check g_tokenListHead. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId006, TestSize.Level1) +{ + uint64_t tokenID; + tokenID = Start("GetAccessTokenId006"); + ASSERT_NE(tokenID, 0); + + char *fileBuff = nullptr; + int32_t ret = GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff); + ASSERT_EQ(ret, ATRET_SUCCESS); + string s = "GetAccessTokenId006"; + char *pos = strstr(fileBuff, s.c_str()); + ASSERT_NE(pos, nullptr); +} + +/** + * @tc.name: GetAccessTokenId007 + * @tc.desc: cannot getAccessTokenId with invalid dcapNum. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId007, TestSize.Level1) +{ + const char **perms = new const char *[MAX_PERM_NUM]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + int32_t permsNum = -1; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .aplStr = "system_core", + }; + + infoInstance.permsNum = permsNum; + infoInstance.processName = "GetAccessTokenId007"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + permsNum = MAX_PERM_NUM + 1; + infoInstance.permsNum = permsNum; + infoInstance.processName = "GetAccessTokenId007_00"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + for (int32_t i = 0; i < MAX_PERM_NUM; i++) { + perms[i] = "ohos.permission.test"; + } + + permsNum = MAX_PERM_NUM; + infoInstance.permsNum = permsNum; + infoInstance.processName = "GetAccessTokenId007_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + permsNum = MAX_PERM_NUM - 1; + infoInstance.permsNum = permsNum; + infoInstance.processName = "GetAccessTokenId007_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] perms; +} + +/** + * @tc.name: GetAccessTokenId008 + * @tc.desc: Get AccessTokenId with new processName. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId008, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + uint64_t tokenId; + const char **acls = new const char *[2]; + acls[0] = "ohos.permission.test1"; + acls[1] = "ohos.permission.test2"; + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 2, + .permsNum = 2, + .aclsNum = 2, + .dcaps = dcaps, + .perms = perms, + .acls = acls, + .processName = "GetAccessTokenId008", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] perms; + delete[] dcaps; + delete[] acls; +} + +/** + * @tc.name: GetAccessTokenId009 + * @tc.desc: cannot getAccessTokenId with invalid perms. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId009, TestSize.Level1) +{ + const char **perms = new const char *[2]; + perms[0] = "AT_CAP"; + perms[1] = "ST_CAP"; + int32_t permsNum = 2; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .dcaps = nullptr, + .aplStr = "system_core", + }; + + infoInstance.permsNum = permsNum; + infoInstance.perms = nullptr; + infoInstance.processName = "GetAccessTokenId009"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + permsNum = 0; + infoInstance.permsNum = permsNum; + infoInstance.perms = nullptr; + infoInstance.processName = "GetAccessTokenId009_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + permsNum = 2; + /* 1025 is invalid dcap length */ + const std::string invalidDcap (MAX_PERM_LEN + 1, 'x'); + perms[0] = invalidDcap.c_str(); + infoInstance.permsNum = permsNum; + infoInstance.perms = perms; + infoInstance.processName = "GetAccessTokenId009_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + const std::string validDcap01 (MAX_PERM_LEN, 'x'); + perms[0] = validDcap01.c_str(); + infoInstance.permsNum = permsNum; + infoInstance.perms = perms; + infoInstance.processName = "GetAccessTokenId009_03"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + const std::string validDcap02 (MAX_PERM_LEN - 1, 'x'); + perms[0] = validDcap02.c_str(); + infoInstance.permsNum = permsNum; + infoInstance.perms = perms; + infoInstance.processName = "GetAccessTokenId009_04"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] perms; +} + +/** + * @tc.name: GetAccessTokenId010 + * @tc.desc: Get a batch of AccessTokenId. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId010, TestSize.Level1) +{ + char processName[200][MAX_PROCESS_NAME_LEN]; + /* enable 200 process before fondation is prepared */ + for (int32_t i = 0; i < 200; i++) { + processName[i][0] = '\0'; + int32_t ret = sprintf_s(processName[i], MAX_PROCESS_NAME_LEN, "processName_%d", i); + ASSERT_NE(ret, 0); + uint64_t tokenId = Start(processName[i]); + ASSERT_NE(tokenId, 0); + } + char *fileBuff = nullptr; + int32_t ret = GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff); + ASSERT_EQ(ret, 0); + for (int32_t i = 0; i < 200; i++) { + char *pos = strstr(fileBuff, processName[i]); + ASSERT_NE(pos, nullptr); + } + free(fileBuff); +} + +/** + * @tc.name: GetAccessTokenId011 + * @tc.desc: Get AccessTokenId and check the config file. + * @tc.type: FUNC + * @tc.require:AR000GK6TD + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId011, TestSize.Level1) +{ + Start("process1"); + Start("process2"); + Start("process3"); + Start("process4"); + Start("process5"); + Start("foundation"); + Start("process6"); + Start("process7"); + Start("process8"); + Start("process9"); + Start("process10"); + Start("process15"); + Start("process16"); + Start("process17"); + Start("process18"); + Start("process19"); + + char *fileBuff = nullptr; + int32_t ret = GetFileBuff(TOKEN_ID_CFG_FILE_PATH, &fileBuff); + ASSERT_EQ(ret, 0); + char *pos = strstr(fileBuff, "process1"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process2"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process3"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process4"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process5"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process6"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process7"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process8"); + ASSERT_NE(pos, nullptr); + pos = strstr(fileBuff, "process9"); + ASSERT_NE(pos, nullptr); + free(fileBuff); +} + +/** + * @tc.name: GetAccessTokenId012 + * @tc.desc: Get AccessTokenId with valid acls. + * @tc.type: FUNC + * @tc.require:AR000H09K6 + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId012, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + uint64_t tokenId; + const char **acls = new const char *[2]; + acls[0] = "ohos.permission.test1"; + acls[1] = "ohos.permission.test2"; + + NativeTokenInfoParams infoInstance = { + .dcapsNum = 2, + .permsNum = 0, + .aclsNum = 2, + .dcaps = dcaps, + .perms = nullptr, + .acls = acls, + .processName = "GetAccessTokenId008", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + infoInstance.acls = nullptr; + infoInstance.aclsNum = 0; + + delete[] dcaps; + delete[] acls; +} + +/** + * @tc.name: GetAccessTokenId013 + * @tc.desc: cannot getAccessTokenId with invalid acls. + * @tc.type: FUNC + * @tc.require:AR000H09K6 + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId013, TestSize.Level1) +{ + const char **acls = new const char *[2]; + acls[0] = "AT_CAP"; + acls[1] = "ST_CAP"; + int32_t aclsNum = 2; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .dcaps = nullptr, + .perms = acls, + .aplStr = "system_core", + }; + + infoInstance.aclsNum = aclsNum; + infoInstance.acls = nullptr; + infoInstance.processName = "GetAccessTokenId013"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + aclsNum = 0; + infoInstance.aclsNum = aclsNum; + infoInstance.acls = nullptr; + infoInstance.processName = "GetAccessTokenId013_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + aclsNum = 1; + const std::string invalidAcl (MAX_PERM_LEN + 1, 'x'); + acls[0] = invalidAcl.c_str(); + infoInstance.aclsNum = aclsNum; + infoInstance.acls = acls; + infoInstance.processName = "GetAccessTokenId013_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + const std::string validcAcl01 (MAX_PERM_LEN, 'x'); + acls[0] = validcAcl01.c_str(); + infoInstance.aclsNum = aclsNum; + infoInstance.acls = acls; + infoInstance.processName = "GetAccessTokenId013_03"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + const std::string validcAcl02 (MAX_PERM_LEN - 1, 'x'); + acls[0] = validcAcl02.c_str(); + infoInstance.aclsNum = aclsNum; + infoInstance.acls = acls; + infoInstance.processName = "GetAccessTokenId013_04"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] acls; +} + +/** + * @tc.name: GetAccessTokenId014 + * @tc.desc: getAccessTokenId success with perms and acls. + * @tc.type: FUNC + * @tc.require:AR000H09K7 + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId014, TestSize.Level0) +{ + uint64_t tokenId; + const char **acls = new const char *[1]; + acls[0] = "ohos.permission.PERMISSION_USED_STATS"; + const char **perms = new const char *[3]; + perms[0] = "ohos.permission.PERMISSION_USED_STATS"; // system_core + perms[1] = "ohos.permission.PLACE_CALL"; // system_basic + perms[2] = "ohos.permission.unknown"; // invalid + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 3, + .dcaps = nullptr, + .perms = perms, + .aplStr = "system_basic", + }; + + infoInstance.acls = nullptr; + infoInstance.aclsNum = 0; + infoInstance.processName = "GetAccessTokenId014_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + infoInstance.acls = acls; + infoInstance.aclsNum = 1; + infoInstance.processName = "GetAccessTokenId014_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] perms; + delete[] acls; +} + +/** + * @tc.name: GetAccessTokenId015 + * @tc.desc: cannot getAccessTokenId with invalid aclsNum. + * @tc.type: FUNC + * @tc.require:AR000H09K6 + */ +HWTEST_F(TokenLibKitTest, GetAccessTokenId015, TestSize.Level1) +{ + const char **perms = new const char *[MAX_PERM_NUM + 1]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + int32_t permsNum = 2; + uint64_t tokenId; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = perms, + .aplStr = "system_core", + }; + + infoInstance.permsNum = permsNum; + infoInstance.aclsNum = -1; + infoInstance.processName = "GetAccessTokenId015"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + for (int32_t i = 0; i < MAX_PERM_NUM + 1; i++) { + perms[i] = "ohos.permission.test"; + } + + infoInstance.permsNum = MAX_PERM_NUM; + infoInstance.aclsNum = MAX_PERM_NUM + 1; + infoInstance.processName = "GetAccessTokenId015_00"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + permsNum = MAX_PERM_NUM; + infoInstance.permsNum = permsNum; + infoInstance.aclsNum = permsNum; + infoInstance.processName = "GetAccessTokenId015_01"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + permsNum = MAX_PERM_NUM - 1; + infoInstance.permsNum = permsNum; + infoInstance.aclsNum = permsNum; + infoInstance.processName = "GetAccessTokenId015_02"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + permsNum = MAX_PERM_NUM - 1; + infoInstance.permsNum = permsNum; + infoInstance.aclsNum = permsNum + 1; + infoInstance.processName = "GetAccessTokenId015_03"; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_EQ(tokenId, 0); + + delete[] perms; +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.h b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.h new file mode 100644 index 000000000..c63ffcc61 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/nativetoken/test/unittest/src/nativetoken_kit_test.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_KIT_TEST_H +#define TOKENSYNC_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +static const int32_t BUFF_LEN = 102400; +static const int32_t DELAY_ONE_SECONDS = 5; +static const int32_t DELAY_FIVE_SECONDS = 10; +class TokenLibKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + void ResetFile(void); + void PthreadCloseTrigger(void); +}; +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_KIT_TEST_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/privacy/BUILD.gn new file mode 100644 index 000000000..42ec2da9f --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("pricacy") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_shared_library("libprivacy_sdk") { + subsystem_name = "security" + part_name = "access_token" + + output_name = "libprivacy_sdk" + + public_configs = [ ":pricacy" ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "include", + "src", + "//base/security/access_token/frameworks/privacy/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + ] + + sources = [ + "src/perm_active_status_change_callback.cpp", + "src/perm_active_status_change_callback_stub.cpp", + "src/perm_active_status_customized_cbk.cpp", + "src/privacy_death_recipient.cpp", + "src/privacy_kit.cpp", + "src/privacy_manager_client.cpp", + "src/privacy_manager_proxy.cpp", + ] + + deps = [ + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/frameworks/privacy:privacy_communication_adapter_cxx", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + cflags_cc = [ + "-DHILOG_ENABLE", + "-DDEBUG_API_PERFORMANCE", + ] + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/active_change_response_info.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/active_change_response_info.h new file mode 100644 index 000000000..fb0103a3a --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/active_change_response_info.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACTIVE_CHANGE_RESPONSE_INFO_H +#define ACTIVE_CHANGE_RESPONSE_INFO_H + +#include +#include + +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum ActiveChangeType { + PERM_INACTIVE = 0, + PERM_ACTIVE_IN_FOREGROUND = 1, + PERM_ACTIVE_IN_BACKGROUND = 2, +}; + +struct ActiveChangeResponse { + AccessTokenID tokenID; + std::string permissionName; + std::string deviceId; + ActiveChangeType type; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // ACTIVE_CHANGE_RESPONSE_INFO_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/on_permission_used_record_callback.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/on_permission_used_record_callback.h new file mode 100644 index 000000000..acb51194f --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/on_permission_used_record_callback.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ON_PERMISSION_USED_RECORD_CALLBACK_H +#define ON_PERMISSION_USED_RECORD_CALLBACK_H + +#include "errors.h" +#include "iremote_broker.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class OnPermissionUsedRecordCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.OnPermissionUsedRecordCallback"); + + virtual void OnQueried(ErrCode code, PermissionUsedResult& result) = 0; + + enum { + ON_QUERIED = 0, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ON_PERMISSION_USED_RECORD_CALLBACK_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback.h new file mode 100644 index 000000000..d1c7c95f8 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_STATUS_CHANGE_CALLBACK_H +#define PERM_ACTIVE_STATUS_CHANGE_CALLBACK_H + +#include +#include + +#include "active_change_response_info.h" +#include "perm_active_status_change_callback_stub.h" +#include "perm_active_status_customized_cbk.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusChangeCallback : public PermActiveStatusChangeCallbackStub { +public: + explicit PermActiveStatusChangeCallback(const std::shared_ptr &subscriber); + ~PermActiveStatusChangeCallback() override; + + void ActiveStatusChangeCallback(ActiveChangeResponse& result) override; + + void Stop(); + +private: + std::shared_ptr customizedCallback_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERM_ACTIVE_STATUS_CHANGE_CALLBACK_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback_stub.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback_stub.h new file mode 100644 index 000000000..cc9a6c81a --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_change_callback_stub.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_STATUS_CHANGE_CALLBACK_STUB_H +#define PERM_ACTIVE_STATUS_CHANGE_CALLBACK_STUB_H + + +#include "i_perm_active_status_callback.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusChangeCallbackStub : public IRemoteStub { +public: + PermActiveStatusChangeCallbackStub() = default; + virtual ~PermActiveStatusChangeCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERM_ACTIVE_STATUS_CHANGE_CALLBACK_STUB_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_customized_cbk.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_customized_cbk.h new file mode 100644 index 000000000..014361cbf --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/perm_active_status_customized_cbk.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_STATUS_CUSTOMIZED_CBK_H +#define PERM_ACTIVE_STATUS_CUSTOMIZED_CBK_H + +#include +#include + +#include "access_token.h" +#include "active_change_response_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusCustomizedCbk { +public: + PermActiveStatusCustomizedCbk(); + explicit PermActiveStatusCustomizedCbk(const std::vector& permList); + virtual ~PermActiveStatusCustomizedCbk(); + + virtual void ActiveStatusChangeCallback(ActiveChangeResponse& result) = 0; + + void GetPermList(std::vector& permList) const; + +private: + std::vector permList_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERM_ACTIVE_STATUS_CUSTOMIZED_CBK_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_request.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_request.h new file mode 100644 index 000000000..1fcdd9f2d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_request.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_REQUEST_H +#define PERMISSION_USED_REQUEST_H + +#include +#include + +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef enum PermissionUsageFlagEnum { + FLAG_PERMISSION_USAGE_SUMMARY = 0, + FLAG_PERMISSION_USAGE_DETAIL = 1, +} PermissionUsageFlag; + +struct PermissionUsedRequest { + AccessTokenID tokenId = 0; + bool isRemote = false; + std::string deviceId; + std::string bundleName; + std::vector permissionList; + int64_t beginTimeMillis = 0; + int64_t endTimeMillis = 0; + PermissionUsageFlag flag = FLAG_PERMISSION_USAGE_SUMMARY; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_USED_REQUEST_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_result.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_result.h new file mode 100644 index 000000000..c52a1ccd6 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/permission_used_result.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RESPONSE_H +#define PERMISSION_USED_RESPONSE_H + +#include +#include +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct UsedRecordDetail { + int32_t status = 0; + int64_t timestamp = 0L; + int64_t accessDuration = 0L; +}; + +struct PermissionUsedRecord { + std::string permissionName; + int32_t accessCount = 0; + int32_t rejectCount = 0; + int64_t lastAccessTime = 0L; + int64_t lastRejectTime = 0L; + int64_t lastAccessDuration = 0L; + std::vector accessRecords; + std::vector rejectRecords; +}; + +struct BundleUsedRecord { + AccessTokenID tokenId; + bool isRemote; + std::string deviceId; + std::string bundleName; + std::vector permissionRecords; +}; + +struct PermissionUsedResult { + int64_t beginTimeMillis = 0L; + int64_t endTimeMillis = 0L; + std::vector bundleRecords; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_USED_RESPONSE_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/include/privacy_kit.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/privacy_kit.h new file mode 100644 index 000000000..f86a3d01a --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/include/privacy_kit.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_PRIVACY_KIT_H +#define INTERFACES_INNER_KITS_PRIVACY_KIT_H + +#include + +#include "access_token.h" +#include "on_permission_used_record_callback.h" +#include "permission_used_request.h" +#include "permission_used_result.h" +#include "perm_active_status_customized_cbk.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyKit { +public: + static int32_t AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount); + static int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + static int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + static int32_t RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID); + static int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); + static int32_t GetPermissionUsedRecords( + const PermissionUsedRequest& request, const sptr& callback); + static std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName); + static int32_t RegisterPermActiveStatusCallback(const std::shared_ptr& callback); + static int32_t UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback); + static bool IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback.cpp new file mode 100644 index 000000000..38da6c498 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_active_status_change_callback.h" + +#include "access_token.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionActiveStatusChangeCallback" +}; +PermActiveStatusChangeCallback::PermActiveStatusChangeCallback( + const std::shared_ptr &customizedCallback) + : customizedCallback_(customizedCallback) +{} + +PermActiveStatusChangeCallback::~PermActiveStatusChangeCallback() +{} + +void PermActiveStatusChangeCallback::ActiveStatusChangeCallback(ActiveChangeResponse& result) +{ + if (customizedCallback_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "customizedCallback_ is nullptr"); + return; + } + + customizedCallback_->ActiveStatusChangeCallback(result); +} + +void PermActiveStatusChangeCallback::Stop() +{} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback_stub.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback_stub.cpp new file mode 100644 index 000000000..fa4d4e035 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_change_callback_stub.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_active_status_change_callback_stub.h" + +#include "accesstoken_log.h" +#include "perm_active_response_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermActiveStatusChangeCallbackStub" +}; +} + +int32_t PermActiveStatusChangeCallbackStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, code: 0x%{public}x", code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != IPermActiveStatusCallback::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return RET_FAILED; + } + + int32_t msgCode = static_cast(code); + if (msgCode == IPermActiveStatusCallback::PERM_ACTIVE_STATUS_CHANGE) { + sptr resultSptr = data.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + + ActiveStatusChangeCallback(resultSptr->changeResponse); + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_customized_cbk.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_customized_cbk.cpp new file mode 100644 index 000000000..b220f7ac0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/perm_active_status_customized_cbk.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_active_status_customized_cbk.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +PermActiveStatusCustomizedCbk::PermActiveStatusCustomizedCbk() +{} + +PermActiveStatusCustomizedCbk::PermActiveStatusCustomizedCbk( + const std::vector& permList) : permList_(permList) +{} + +PermActiveStatusCustomizedCbk::~PermActiveStatusCustomizedCbk() +{} + +void PermActiveStatusCustomizedCbk::GetPermList(std::vector& permList) const +{ + permList = permList_; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.cpp new file mode 100644 index 000000000..6322643b8 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "privacy_death_recipient.h" + +#include "accesstoken_log.h" +#include "privacy_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyDeathRecipient" +}; +} // namespace + +void PrivacyDeathRecipient::OnRemoteDied(const wptr& object) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + PrivacyManagerClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.h new file mode 100644 index 000000000..5670393ac --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_death_recipient.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef PRIVACY_DEATH_RECIPIENT_H +#define PRIVACY_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyDeathRecipient : public IRemoteObject::DeathRecipient { +public: + PrivacyDeathRecipient() {} + virtual ~PrivacyDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_DEATH_RECIPIENT_H + diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_kit.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_kit.cpp new file mode 100644 index 000000000..6c3bc3168 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_kit.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "constant_common.h" +#include "privacy_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyKit"}; +} // namespace + +int32_t PrivacyKit::AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, permissionName=%{public}s,", + tokenID, permissionName.c_str()); + return PrivacyManagerClient::GetInstance().AddPermissionUsedRecord( + tokenID, permissionName, successCount, failCount); +} + +int32_t PrivacyKit::StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, permissionName=%{public}s", + tokenID, permissionName.c_str()); + return PrivacyManagerClient::GetInstance().StartUsingPermission(tokenID, permissionName); +} + +int32_t PrivacyKit::StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, permissionName=%{public}s", + tokenID, permissionName.c_str()); + return PrivacyManagerClient::GetInstance().StopUsingPermission(tokenID, permissionName); +} + +int32_t PrivacyKit::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=0x%{public}x, deviceID=%{public}s", + tokenID, ConstantCommon::EncryptDevId(deviceID).c_str()); + return PrivacyManagerClient::GetInstance().RemovePermissionUsedRecords(tokenID, deviceID); +} + +int32_t PrivacyKit::GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result) +{ + return PrivacyManagerClient::GetInstance().GetPermissionUsedRecords(request, result); +} + +int32_t PrivacyKit::GetPermissionUsedRecords( + const PermissionUsedRequest& request, const sptr& callback) +{ + return PrivacyManagerClient::GetInstance().GetPermissionUsedRecords(request, callback); +} + +std::string PrivacyKit::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=%{public}d, permissionName=%{public}s", + tokenID, permissionName.c_str()); + return PrivacyManagerClient::GetInstance().DumpRecordInfo(tokenID, permissionName); +} + +int32_t PrivacyKit::RegisterPermActiveStatusCallback(const std::shared_ptr& callback) +{ + return PrivacyManagerClient::GetInstance().RegisterPermActiveStatusCallback(callback); +} + +int32_t PrivacyKit::UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback) +{ + return PrivacyManagerClient::GetInstance().UnRegisterPermActiveStatusCallback(callback); +} + +bool PrivacyKit::IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + return PrivacyManagerClient::GetInstance().IsAllowUsingPermission(tokenID, permissionName); +} + +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.cpp new file mode 100644 index 000000000..7ca048f3d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.cpp @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "privacy_manager_client.h" + +#include +#include "accesstoken_log.h" +#include "data_validator.h" +#include "iservice_registry.h" +#include "privacy_manager_proxy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerClient" +}; +} // namespace + +const static int32_t ERROR = -1; +const static int32_t MAX_PERM_LIST_SIZE = 200; + +PrivacyManagerClient& PrivacyManagerClient::GetInstance() +{ + static PrivacyManagerClient instance; + return instance; +} + +PrivacyManagerClient::PrivacyManagerClient() +{} + +PrivacyManagerClient::~PrivacyManagerClient() +{} + +int32_t PrivacyManagerClient::AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) +{ + if (!DataValidator::IsTokenIDValid(tokenID) || !DataValidator::IsPermissionNameValid(permissionName) || + (successCount < 0 || failCount < 0)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "parameter is invalid"); + return ERROR; + } + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + return proxy->AddPermissionUsedRecord(tokenID, permissionName, successCount, failCount); +} + +int32_t PrivacyManagerClient::StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + if (!DataValidator::IsTokenIDValid(tokenID) || !DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "parameter is invalid"); + return ERROR; + } + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + return proxy->StartUsingPermission(tokenID, permissionName); +} + +int32_t PrivacyManagerClient::StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + if (!DataValidator::IsTokenIDValid(tokenID) || !DataValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "parameter is invalid"); + return ERROR; + } + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + return proxy->StopUsingPermission(tokenID, permissionName); +} + +int32_t PrivacyManagerClient::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) +{ + if (!DataValidator::IsTokenIDValid(tokenID) && !DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "parameter is invalid"); + return ERROR; + } + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + return proxy->RemovePermissionUsedRecords(tokenID, deviceID); +} + +int32_t PrivacyManagerClient::GetPermissionUsedRecords( + const PermissionUsedRequest& request, PermissionUsedResult& result) +{ + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + + PermissionUsedRequestParcel requestParcel; + PermissionUsedResultParcel reultParcel; + requestParcel.request = request; + int32_t ret = proxy->GetPermissionUsedRecords(requestParcel, reultParcel); + result = reultParcel.result; + return ret; +} + +int32_t PrivacyManagerClient::GetPermissionUsedRecords(const PermissionUsedRequest& request, + const sptr& callback) +{ + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + + PermissionUsedRequestParcel requestParcel; + requestParcel.request = request; + return proxy->GetPermissionUsedRecords(requestParcel, callback); +} + +std::string PrivacyManagerClient::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) +{ + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ""; + } + + return proxy->DumpRecordInfo(tokenID, permissionName); +} + +int32_t PrivacyManagerClient::CreateActiveStatusChangeCbk( + const std::shared_ptr& callback, sptr& callbackObject) +{ + std::lock_guard lock(activeCbkMutex_); + + if (activeCbkMap_.size() == MAX_PERM_LIST_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "the maximum number of subscribers has been reached"); + return ERROR; + } + + auto goalCallback = activeCbkMap_.find(callback); + if (goalCallback != activeCbkMap_.end()) { + callbackObject = goalCallback->second->AsObject(); + ACCESSTOKEN_LOG_ERROR(LABEL, "activeCbkMap_ already has such callback"); + return ERROR; + } else { + sptr callbackWraped = + new (std::nothrow) PermActiveStatusChangeCallback(callback); + if (!callbackWraped) { + ACCESSTOKEN_LOG_ERROR(LABEL, "memory allocation for callbackWraped failed!"); + return ERROR; + } + ACCESSTOKEN_LOG_INFO(LABEL, "callbackObject added"); + callbackObject = callbackWraped->AsObject(); + activeCbkMap_[callback] = callbackWraped; + } + return RET_SUCCESS; +} + +int32_t PrivacyManagerClient::RegisterPermActiveStatusCallback( + const std::shared_ptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called!"); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "customizedCb is nullptr"); + return ERROR; + } + + sptr callbackObject = nullptr; + int32_t result = CreateActiveStatusChangeCbk(callback, callbackObject); + if (result != RET_SUCCESS) { + return result; + } + + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + std::vector permList; + callback->GetPermList(permList); + + return proxy->RegisterPermActiveStatusCallback(permList, callbackObject); +} + +int32_t PrivacyManagerClient::UnRegisterPermActiveStatusCallback( + const std::shared_ptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called!"); + + std::lock_guard lock(activeCbkMutex_); + auto goalCallback = activeCbkMap_.find(callback); + if (goalCallback == activeCbkMap_.end()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "goalCallback already is not exist"); + return ERROR; + } + + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return ERROR; + } + + int32_t result = proxy->UnRegisterPermActiveStatusCallback(goalCallback->second->AsObject()); + if (result == RET_SUCCESS) { + activeCbkMap_.erase(goalCallback); + } + return result; +} + +void PrivacyManagerClient::InitProxy() +{ + std::lock_guard lock(proxyMutex_); + if (proxy_ == nullptr) { + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); + return; + } + auto privacySa = sam->GetSystemAbility(IPrivacyManager::SA_ID_PRIVACY_MANAGER_SERVICE); + if (privacySa == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", + IPrivacyManager::SA_ID_PRIVACY_MANAGER_SERVICE); + return; + } + + serviceDeathObserver_ = new (std::nothrow) PrivacyDeathRecipient(); + if (serviceDeathObserver_ != nullptr) { + privacySa->AddDeathRecipient(serviceDeathObserver_); + } + proxy_ = iface_cast(privacySa); + if (proxy_ == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); + } + } +} + +bool PrivacyManagerClient::IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + auto proxy = GetProxy(); + if (proxy == nullptr) { + // ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return false; + } + + return proxy->IsAllowUsingPermission(tokenID, permissionName); +} + +void PrivacyManagerClient::OnRemoteDiedHandle() +{ + { + std::lock_guard lock(proxyMutex_); + proxy_ = nullptr; + } + InitProxy(); +} + +sptr PrivacyManagerClient::GetProxy() +{ + if (proxy_ == nullptr) { + InitProxy(); + } + return proxy_; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.h new file mode 100644 index 000000000..0cd621ba3 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_client.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRIVACY_MANAGER_CLIENT_H +#define PRIVACY_MANAGER_CLIENT_H + +#include +#include +#include +#include + +#include "i_privacy_manager.h" +#include "perm_active_status_change_callback.h" +#include "perm_active_status_customized_cbk.h" +#include "privacy_death_recipient.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyManagerClient final { +public: + static PrivacyManagerClient& GetInstance(); + + virtual ~PrivacyManagerClient(); + + int32_t AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount); + int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + int32_t RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID); + int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); + int32_t GetPermissionUsedRecords( + const PermissionUsedRequest& request, const sptr& callback); + std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName); + int32_t RegisterPermActiveStatusCallback(const std::shared_ptr& callback); + int32_t UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback); + int32_t CreateActiveStatusChangeCbk( + const std::shared_ptr& callback, sptr& callbackObject); + bool IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + void OnRemoteDiedHandle(); +private: + PrivacyManagerClient(); + + DISALLOW_COPY_AND_MOVE(PrivacyManagerClient); + std::mutex proxyMutex_; + sptr proxy_ = nullptr; + sptr serviceDeathObserver_ = nullptr; + void InitProxy(); + sptr GetProxy(); + +private: + std::mutex activeCbkMutex_; + std::map, sptr> activeCbkMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_MANAGER_CLIENT_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp new file mode 100644 index 000000000..765d5ec62 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp @@ -0,0 +1,340 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_manager_proxy.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerProxy" +}; +} + +const static int32_t ERROR = -1; + +PrivacyManagerProxy::PrivacyManagerProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +PrivacyManagerProxy::~PrivacyManagerProxy() +{} + +int32_t PrivacyManagerProxy::AddPermissionUsedRecord(AccessTokenID tokenID, const std::string& permissionName, + int32_t successCount, int32_t failCount) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return ERROR; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(permissionName)"); + return ERROR; + } + if (!data.WriteInt32(successCount)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(successCount)"); + return ERROR; + } + if (!data.WriteInt32(failCount)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(failCount)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::ADD_PERMISSION_USED_RECORD, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "add result fail, result: %{public}d", requestResult); + } + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +int32_t PrivacyManagerProxy::StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return ERROR; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(permissionName)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::START_USING_PERMISSION, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "add result fail, result: %{public}d", requestResult); + } + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +int32_t PrivacyManagerProxy::StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return ERROR; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(permissionName)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::STOP_USING_PERMISSION, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "add result fail, result: %{public}d", requestResult); + } + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +int32_t PrivacyManagerProxy::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return ERROR; + } + if (!data.WriteString(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(deviceID)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::DELETE_PERMISSION_USED_RECORDS, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "add result fail, result: %{public}d", requestResult); + } + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +int32_t PrivacyManagerProxy::GetPermissionUsedRecords(const PermissionUsedRequestParcel& request, + PermissionUsedResultParcel& result) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteParcelable(&request)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable(request)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::GET_PERMISSION_USED_RECORDS, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return ERROR; + } + + sptr resultSptr = reply.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return ERROR; + } + result = *resultSptr; + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +int32_t PrivacyManagerProxy::GetPermissionUsedRecords(const PermissionUsedRequestParcel& request, + const sptr& callback) +{ + MessageParcel data; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteParcelable(&request)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable(request)"); + return ERROR; + } + if (!data.WriteRemoteObject(callback->AsObject())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteRemoteObject(callback)"); + return ERROR; + } + + MessageParcel reply; + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::GET_PERMISSION_USED_RECORDS_ASYNC, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return ERROR; + } + int32_t ret = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", ret); + return ret; +} + +std::string PrivacyManagerProxy::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + MessageParcel reply; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return ""; + } + if (!data.WriteString(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(%{public}s)", permissionName.c_str()); + return ""; + } + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::DUMP_RECORD_INFO, data, reply); + if (!requestResult) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return ""; + } + std::string dumpInfo = reply.ReadString(); + return dumpInfo; +} + +int32_t PrivacyManagerProxy::RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called."); + MessageParcel data; + if (!data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write WriteInterfaceToken."); + return ERROR; + } + + uint32_t listSize = permList.size(); + if (!data.WriteUint32(listSize)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write listSize"); + return ERROR; + } + for (uint32_t i = 0; i < listSize; i++) { + if (!data.WriteString(permList[i])) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permList[%{public}d], %{public}s", i, permList[i].c_str()); + return ERROR; + } + } + + if (!data.WriteRemoteObject(callback)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write remote object."); + return ERROR; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return ERROR; + } + int32_t requestResult = remote->SendRequest( + static_cast(IPrivacyManager::InterfaceCode::REGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d.", requestResult); + return ERROR; + } + + int32_t result; + if (!reply.ReadInt32(result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadInt32 fail"); + return ERROR; + } + return result; +} + +int32_t PrivacyManagerProxy::UnRegisterPermActiveStatusCallback(const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called."); + MessageParcel data; + if (!data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write WriteInterfaceToken."); + return ERROR; + } + if (!data.WriteRemoteObject(callback)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write remote object."); + return ERROR; + } + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return ERROR; + } + int32_t requestResult = remote->SendRequest( + static_cast(IPrivacyManager::InterfaceCode::UNREGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d.", requestResult); + return ERROR; + } + + int32_t result; + if (!reply.ReadInt32(result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadInt32 fail"); + return ERROR; + } + return result; +} + +bool PrivacyManagerProxy::IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +{ + MessageParcel data; + MessageParcel reply; + data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + // ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); + return false; + } + if (!data.WriteString(permissionName)) { + // ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(%{public}s)", permissionName.c_str()); + return false; + } + int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::DUMP_RECORD_INFO, data, reply); + if (!requestResult) { + // ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return false; + } + bool allowperInfo = reply.ReadBool(); + return allowperInfo; +} + + +bool PrivacyManagerProxy::SendRequest( + IPrivacyManager::InterfaceCode code, MessageParcel& data, MessageParcel& reply) +{ + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return false; + } + + int32_t result = remote->SendRequest(static_cast(code), data, reply, option); + if (result != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "SendRequest fail, result: %{public}d", result); + return false; + } + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.h new file mode 100644 index 000000000..4f409592b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/src/privacy_manager_proxy.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRIVACY_MANAGER_PROXY_H +#define PRIVACY_MANAGER_PROXY_H + +#include + +#include "i_privacy_manager.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyManagerProxy : public IRemoteProxy { +public: + explicit PrivacyManagerProxy(const sptr& impl); + ~PrivacyManagerProxy() override; + + int32_t AddPermissionUsedRecord( + AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) override; + int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) override; + int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) override; + int32_t RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) override; + int32_t GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) override; + int32_t GetPermissionUsedRecords(const PermissionUsedRequestParcel& request, + const sptr& callback) override; + std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) override; + int32_t RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) override; + int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) override; + bool IsAllowUsingPermission(AccessTokenID tokenID, const std::string& permissionName) override; +private: + bool SendRequest(IPrivacyManager::InterfaceCode code, MessageParcel& data, MessageParcel& reply); + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_MANAGER_PROXY_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/test/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/BUILD.gn new file mode 100644 index 000000000..e5c392571 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libprivacy_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/interfaces/innerkits/token_setproc/include", + "//base/security/access_token/services/privacymanager/include/record", + ] + + sources = [ "unittest/src/privacy_kit_test.cpp" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + "//base/security/access_token/services/privacymanager:privacy_manager_service", + ] + external_deps = [ + "c_utils:utils", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libprivacy_sdk_test" ] +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp new file mode 100644 index 000000000..c6f6fa74c --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp @@ -0,0 +1,863 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_kit_test.h" + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "parameter.h" +#include "privacy_kit.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +const static int32_t RET_NO_ERROR = 0; +const static int32_t RET_ERROR = -1; + +static HapPolicyParams g_PolicyPramsA = { + .apl = APL_NORMAL, + .domain = "test.domain.A", +}; + +static HapInfoParams g_InfoParmsA = { + .userID = 1, + .bundleName = "ohos.privacy_test.bundleA", + .instIndex = 0, + .appIDDesc = "privacy_test.bundleA" +}; + +static HapPolicyParams g_PolicyPramsB = { + .apl = APL_NORMAL, + .domain = "test.domain.B", +}; + +static HapInfoParams g_InfoParmsB = { + .userID = 1, + .bundleName = "ohos.privacy_test.bundleB", + .instIndex = 0, + .appIDDesc = "privacy_test.bundleB" +}; + +static PermissionStateFull g_infoManagerTestStateA = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestStateB = { + .permissionName = "ohos.permission.MICROPHONE", + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; +static HapPolicyParams g_PolicyPramsE = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB} +}; +static HapInfoParams g_InfoParmsE = { + .userID = 1, + .bundleName = "ohos.privacy_test.bundleE", + .instIndex = 0, + .appIDDesc = "privacy_test.bundleE" +}; + +static AccessTokenID g_selfTokenId = 0; +static AccessTokenID g_TokenId_A = 0; +static AccessTokenID g_TokenId_B = 0; +static AccessTokenID g_TokenId_E = 0; + +void PrivacyKitTest::SetUpTestCase() +{ + g_selfTokenId = GetSelfTokenID(); +} + +void PrivacyKitTest::TearDownTestCase() +{ +} + +void PrivacyKitTest::SetUp() +{ + AccessTokenKit::AllocHapToken(g_InfoParmsA, g_PolicyPramsA); + AccessTokenKit::AllocHapToken(g_InfoParmsB, g_PolicyPramsB); + AccessTokenKit::AllocHapToken(g_InfoParmsE, g_PolicyPramsE); + + g_TokenId_A = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, + g_InfoParmsA.bundleName, + g_InfoParmsA.instIndex); + g_TokenId_B = AccessTokenKit::GetHapTokenID(g_InfoParmsB.userID, + g_InfoParmsB.bundleName, + g_InfoParmsB.instIndex); + g_TokenId_E = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, + g_InfoParmsE.bundleName, + g_InfoParmsE.instIndex); + + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); // 100 is userID + SetSelfTokenID(tokenId); +} + +void PrivacyKitTest::TearDown() +{ + SetSelfTokenID(g_selfTokenId); + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, + g_InfoParmsA.bundleName, + g_InfoParmsA.instIndex); + AccessTokenKit::DeleteToken(tokenId); + + tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsB.userID, + g_InfoParmsB.bundleName, + g_InfoParmsB.instIndex); + AccessTokenKit::DeleteToken(tokenId); + + tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, + g_InfoParmsE.bundleName, + g_InfoParmsE.instIndex); + AccessTokenKit::DeleteToken(tokenId); +} + +std::string PrivacyKitTest::GetLocalDeviceUdid() +{ + const int32_t DEVICE_UUID_LENGTH = 65; + char udid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(udid, DEVICE_UUID_LENGTH); + return udid; +} + +void PrivacyKitTest::BuildQueryRequest(AccessTokenID tokenId, const std::string deviceId, const std::string& bundleName, + const std::vector permissionList, PermissionUsedRequest& request) +{ + request.tokenId = tokenId; + request.isRemote = false; + request.deviceId = deviceId; + request.bundleName = bundleName; + request.permissionList = permissionList; + request.beginTimeMillis = 0; + request.endTimeMillis = 0; + request.flag = FLAG_PERMISSION_USAGE_SUMMARY; +} + +void PrivacyKitTest::CheckPermissionUsedResult(const PermissionUsedRequest& request, const PermissionUsedResult& result, + int32_t permRecordSize, int32_t totalSuccessCount, int32_t totalFailCount) +{ + int32_t successCount = 0; + int32_t failCount = 0; + ASSERT_EQ(request.tokenId, result.bundleRecords[0].tokenId); + ASSERT_EQ(request.isRemote, result.bundleRecords[0].isRemote); + ASSERT_EQ(request.deviceId, result.bundleRecords[0].deviceId); + ASSERT_EQ(request.bundleName, result.bundleRecords[0].bundleName); + ASSERT_EQ(permRecordSize, result.bundleRecords[0].permissionRecords.size()); + for (int32_t i = 0; i < permRecordSize; i++) { + successCount += result.bundleRecords[0].permissionRecords[i].accessCount; + failCount += result.bundleRecords[0].permissionRecords[i].rejectCount; + } + ASSERT_EQ(totalSuccessCount, successCount); + ASSERT_EQ(totalFailCount, failCount); +} + +static void SetTokenID(std::vector& g_InfoParms_List, + std::vector& g_TokenId_List, int32_t number) +{ + SetSelfTokenID(g_selfTokenId); + for (int32_t i = 0; i < number; i++) { + HapInfoParams g_InfoParmsTmp = { + .userID = i, + .bundleName = "ohos.privacy_test.bundle" + std::to_string(i), + .instIndex = i, + .appIDDesc = "privacy_test.bundle" + std::to_string(i) + }; + g_InfoParms_List.push_back(g_InfoParmsTmp); + HapPolicyParams g_PolicyPramsTmp = { + .apl = APL_NORMAL, + .domain = "test.domain." + std::to_string(i) + }; + AccessTokenKit::AllocHapToken(g_InfoParmsTmp, g_PolicyPramsTmp); + AccessTokenID g_TokenId_Tmp = AccessTokenKit::GetHapTokenID(g_InfoParmsTmp.userID, + g_InfoParmsTmp.bundleName, + g_InfoParmsTmp.instIndex); + g_TokenId_List.push_back(g_TokenId_Tmp); + } + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); + SetSelfTokenID(tokenId); +} + +static void DeleteTokenID(std::vector& g_InfoParms_List) +{ + SetSelfTokenID(g_selfTokenId); + for (size_t i = 0; i < g_InfoParms_List.size(); i++) { + AccessTokenID g_TokenId_Tmp = AccessTokenKit::GetHapTokenID(g_InfoParms_List[i].userID, + g_InfoParms_List[i].bundleName, + g_InfoParms_List[i].instIndex); + AccessTokenKit::DeleteToken(g_TokenId_Tmp); + } + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); + SetSelfTokenID(tokenId); +} + +/** + * @tc.name: AddPermissionUsedRecord001 + * @tc.desc: cannot AddPermissionUsedRecord with illegal tokenId and permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord001, TestSize.Level1) +{ + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord( + 0, "ohos.permission.READ_CONTACTS", 1, 0)); + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "", 1, 0)); + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord( + g_TokenId_A, "ohos.permission.READ_CONTACTS", -1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); +} + +/** + * @tc.name: AddPermissionUsedRecord002 + * @tc.desc: cannot AddPermissionUsedRecord with invalid tokenId and permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord002, TestSize.Level1) +{ + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.test", 1, 0)); + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord(123, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.READ_CONTACTS", 0, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(123, "", "", permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); + + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); +} + +/** + * @tc.name: AddPermissionUsedRecord003 + * @tc.desc: cannot AddPermissionUsedRecord with native tokenId. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord003, TestSize.Level1) +{ + const char **dcaps = new const char *[2]; + dcaps[0] = "AT_CAP"; + dcaps[1] = "ST_CAP"; + uint64_t tokenId; + const char **acls = new const char *[2]; + acls[0] = "ohos.permission.test1"; + acls[1] = "ohos.permission.test2"; + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 2, + .permsNum = 2, + .aclsNum = 2, + .dcaps = dcaps, + .perms = perms, + .acls = acls, + .processName = "GetAccessTokenId008", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + delete[] perms; + delete[] dcaps; + delete[] acls; + + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord( + tokenId, "ohos.permission.READ_CONTACTS", 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(tokenId, "", "", permissionList, request); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); +} + +/** + * @tc.name: AddPermissionUsedRecord004 + * @tc.desc: AddPermissionUsedRecord user_grant permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord004, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.WRITE_CONTACTS", 0, 1)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.LOCATION", 1, 1)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + ASSERT_EQ(1, result.bundleRecords.size()); + CheckPermissionUsedResult(request, result, 3, 2, 2); +} + +/** + * @tc.name: AddPermissionUsedRecord005 + * @tc.desc: AddPermissionUsedRecord user_grant permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord005, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.LOCATION", 0, 1)); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_B, "ohos.permission.CAMERA", 0, 1)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_B, "ohos.permission.LOCATION", 1, 0)); + + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + ASSERT_EQ(1, result.bundleRecords.size()); + CheckPermissionUsedResult(request, result, 2, 1, 1); + + BuildQueryRequest(g_TokenId_B, GetLocalDeviceUdid(), g_InfoParmsB.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + ASSERT_EQ(1, result.bundleRecords.size()); + CheckPermissionUsedResult(request, result, 2, 1, 1); +} + +/** + * @tc.name: AddPermissionUsedRecord006 + * @tc.desc: AddPermissionUsedRecord permission combine records. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord006, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + ASSERT_EQ(1, result.bundleRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords[0].accessRecords.size()); + CheckPermissionUsedResult(request, result, 1, 4, 0); + + sleep(61); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords.size()); + ASSERT_EQ(2, result.bundleRecords[0].permissionRecords[0].accessRecords.size()); + CheckPermissionUsedResult(request, result, 1, 5, 0); +} + +/** + * @tc.name: AddPermissionUsedRecord007 + * @tc.desc: AddPermissionUsedRecord user_grant permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord007, TestSize.Level1) +{ + std::vector g_InfoParms_List; + std::vector g_TokenId_List; + SetTokenID(g_InfoParms_List, g_TokenId_List, 100); + std::vector addPermissionList = { + "ohos.permission.ANSWER_CALL", + "ohos.permission.READ_CALENDAR", + }; + for (int32_t i = 0; i < 200; i++) { + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_List[i % 100], + addPermissionList[i % 2], 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_List[i % 100], GetLocalDeviceUdid(), + g_InfoParms_List[i % 100].bundleName, permissionList, request); + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + } + sleep(70); + for (int32_t i = 0; i < 100; i++) { + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_List[i], GetLocalDeviceUdid(), + g_InfoParms_List[i].bundleName, permissionList, request); + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords[0].accessRecords.size()); + CheckPermissionUsedResult(request, result, 1, 2, 0); + } + DeleteTokenID(g_InfoParms_List); +} + +/** + * @tc.name: RemovePermissionUsedRecords001 + * @tc.desc: cannot RemovePermissionUsedRecords with illegal tokenId and deviceID. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, RemovePermissionUsedRecords001, TestSize.Level1) +{ + ASSERT_EQ(RET_ERROR, PrivacyKit::RemovePermissionUsedRecords(0, "")); +} + +/** + * @tc.name: RemovePermissionUsedRecords002 + * @tc.desc: RemovePermissionUsedRecords with invalid tokenId and deviceID. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, RemovePermissionUsedRecords002, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::RemovePermissionUsedRecords(g_TokenId_A, "invalid_device")); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::RemovePermissionUsedRecords(123, GetLocalDeviceUdid())); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); +} + +/** + * @tc.name: RemovePermissionUsedRecords003 + * @tc.desc: RemovePermissionUsedRecords with valid tokenId and deviceID. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, RemovePermissionUsedRecords003, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::RemovePermissionUsedRecords(g_TokenId_A, "")); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); +} + +/** + * @tc.name: GetPermissionUsedRecords001 + * @tc.desc: cannot GetPermissionUsedRecords with invalid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords001, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + request.beginTimeMillis = -1; + request.endTimeMillis = -1; + ASSERT_EQ(RET_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + request.beginTimeMillis = 3; + request.endTimeMillis = 1; + ASSERT_EQ(RET_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + + request.flag = (PermissionUsageFlag)-1; + ASSERT_EQ(RET_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); +} + +/** + * @tc.name: GetPermissionUsedRecords002 + * @tc.desc: cannot GetPermissionUsedRecords with valid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords002, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.READ_CALENDAR", 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + // query by tokenId + BuildQueryRequest(g_TokenId_A, "", "", permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + request.deviceId = GetLocalDeviceUdid(); + request.bundleName = g_InfoParmsA.bundleName; + CheckPermissionUsedResult(request, result, 3, 3, 0); + + // query by unmatched tokenId, deviceId and bundle Name + BuildQueryRequest(123, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); + + // query by invalid permission Name + permissionList.clear(); + permissionList.emplace_back("invalid permission"); + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(0, result.bundleRecords.size()); +} + +/** + * @tc.name: GetPermissionUsedRecords003 + * @tc.desc: can GetPermissionUsedRecords with valid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords003, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.MICROPHONE", 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + CheckPermissionUsedResult(request, result, 1, 4, 0); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.READ_CALENDAR", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.WRITE_CALENDAR", 1, 0)); + + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + CheckPermissionUsedResult(request, result, 4, 7, 0); +} + +/** + * @tc.name: GetPermissionUsedRecords004 + * @tc.desc: can GetPermissionUsedRecords with valid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords004, TestSize.Level1) +{ + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, "ohos.permission.READ_CALENDAR", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_B, "ohos.permission.CAMERA", 1, 0)); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_B, "ohos.permission.READ_CALENDAR", 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(0, GetLocalDeviceUdid(), "", permissionList, request); + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + if (result.bundleRecords.size() < 2) { + ASSERT_EQ(RET_NO_ERROR, RET_ERROR); + } +} + +/** + * @tc.name: GetPermissionUsedRecordsAsync001 + * @tc.desc: cannot GetPermissionUsedRecordsAsync with invalid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync001, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, permission, 1, 0)); + PermissionUsedRequest request; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), "", permissionList, request); + request.beginTimeMillis = -1; + request.endTimeMillis = -1; + OHOS::sptr callback(new TestCallBack()); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, callback)); +} + +/** + * @tc.name: GetPermissionUsedRecordsAsync002 + * @tc.desc: cannot GetPermissionUsedRecordsAsync with valid query time. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync002, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, permission, 1, 0)); + PermissionUsedRequest request; + std::vector permissionList; + BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), "", permissionList, request); + OHOS::sptr callback(new TestCallBack()); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, callback)); +} + +/** + * @tc.name: DumpRecordInfo001 + * @tc.desc: cannot DumpRecordInfo with invalid params. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo001, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + + // invalid tokenId + std::string info = PrivacyKit::DumpRecordInfo(123, permission); + ASSERT_EQ(true, info.empty()); + + // invalid permission + info = PrivacyKit::DumpRecordInfo(g_TokenId_A, "invalid permission"); + ASSERT_EQ(true, info.empty()); +} + +/** + * @tc.name: DumpRecordInfo002 + * @tc.desc: cannot DumpRecordInfo with no record. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo002, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, permission, 1, 0)); + + std::string info = PrivacyKit::DumpRecordInfo(g_TokenId_A, ""); + ASSERT_EQ(false, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, permission); + ASSERT_EQ(false, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, ""); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DumpRecordInfo003 + * @tc.desc: cannot DumpRecordInfo with record. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo003, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + + std::string info = PrivacyKit::DumpRecordInfo(g_TokenId_A, ""); + ASSERT_EQ(true, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, ""); + ASSERT_EQ(true, info.empty()); +} + + +HWTEST_F(PrivacyKitTest, IsAllowUsingPermission001, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + // invalid tokenId + bool info = PrivacyKit::IsAllowUsingPermission(123, "ohos.permission.CAMERA"); + ASSERT_EQ(true, info); + + // invalid permission + info = PrivacyKit::IsAllowUsingPermission(g_TokenId_A, "invalid permission"); + ASSERT_EQ(true, info); +} + + +class CbCustomizeTest1 : public PermActiveStatusCustomizedCbk { +public: + explicit CbCustomizeTest1(const std::vector &permList) + : PermActiveStatusCustomizedCbk(permList) + { + GTEST_LOG_(INFO) << "CbCustomizeTest1 create"; + } + + ~CbCustomizeTest1() + {} + + virtual void ActiveStatusChangeCallback(ActiveChangeResponse& result) + { + type_ = result.type; + GTEST_LOG_(INFO) << "CbCustomizeTest1 ActiveChangeResponse"; + GTEST_LOG_(INFO) << "CbCustomizeTest1 tokenid " << result.tokenID; + GTEST_LOG_(INFO) << "CbCustomizeTest1 permissionName " << result.permissionName; + GTEST_LOG_(INFO) << "CbCustomizeTest1 deviceId " << result.deviceId; + GTEST_LOG_(INFO) << "CbCustomizeTest1 type " << result.type; + } + + ActiveChangeType type_ = PERM_INACTIVE; +}; + +class CbCustomizeTest2 : public PermActiveStatusCustomizedCbk { +public: + explicit CbCustomizeTest2(const std::vector &permList) + : PermActiveStatusCustomizedCbk(permList) + { + GTEST_LOG_(INFO) << "CbCustomizeTest2 create"; + } + + ~CbCustomizeTest2() + {} + + virtual void ActiveStatusChangeCallback(ActiveChangeResponse& result) + { + type_ = result.type; + GTEST_LOG_(INFO) << "CbCustomizeTest2 ActiveChangeResponse"; + GTEST_LOG_(INFO) << "CbCustomizeTest2 tokenid " << result.tokenID; + GTEST_LOG_(INFO) << "CbCustomizeTest2 permissionName " << result.permissionName; + GTEST_LOG_(INFO) << "CbCustomizeTest2 deviceId " << result.deviceId; + GTEST_LOG_(INFO) << "CbCustomizeTest2 type " << result.type; + } + + ActiveChangeType type_; +}; + +/** + * @tc.name: RegisterPermActiveStatusCallback001 + * @tc.desc: RegisterPermActiveStatusCallback with valid permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback001, TestSize.Level1) +{ + std::vector permList = {"ohos.permission.CAMERA"}; + + auto callbackPtr = std::make_shared(permList); + callbackPtr->type_ = PERM_INACTIVE; + + int32_t res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr); + + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr->type_); + + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); + + res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr); + ASSERT_EQ(RET_NO_ERROR, res); + callbackPtr->type_ = PERM_INACTIVE; + + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); + + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); +} + +/** + * @tc.name: RegisterPermActiveStatusCallback002 + * @tc.desc: RegisterPermActiveStatusCallback with valid permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ + +HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback002, TestSize.Level1) +{ + std::vector permList1 = {"ohos.permission.CAMERA"}; + auto callbackPtr1 = std::make_shared(permList1); + callbackPtr1->type_ = PERM_INACTIVE; + + std::vector permList2 = {"ohos.permission.MICROPHONE"}; + auto callbackPtr2 = std::make_shared(permList2); + callbackPtr2->type_ = PERM_INACTIVE; + + int32_t res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr1); + res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr2); + + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr1->type_); + ASSERT_EQ(PERM_INACTIVE, callbackPtr2->type_); + + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_INACTIVE, callbackPtr1->type_); + + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.MICROPHONE"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_INACTIVE, callbackPtr1->type_); + ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr2->type_); + + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.MICROPHONE"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s + ASSERT_EQ(PERM_INACTIVE, callbackPtr2->type_); + + res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr1); + ASSERT_EQ(RET_NO_ERROR, res); + res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr2); + ASSERT_EQ(RET_NO_ERROR, res); +} + +/** + * @tc.name: IsAllowUsingPermission001 + * @tc.desc: IsAllowUsingPermission with valid permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ + diff --git a/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.h b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.h new file mode 100644 index 000000000..03729b708 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRIVACY_KIT_TEST_H +#define PRIVACY_KIT_TEST_H + +#include +#include + +#include "on_permission_used_record_callback_stub.h" +#include "permission_used_request.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + class TestCallBack : public OnPermissionUsedRecordCallbackStub { + public: + TestCallBack() = default; + virtual ~TestCallBack() = default; + + void OnQueried(ErrCode code, PermissionUsedResult& result) + { + GTEST_LOG_(INFO) << "TestCallBack, code :" << code << ", bundleSize :" << result.bundleRecords.size(); + } + }; + std::string GetLocalDeviceUdid(); + void BuildQueryRequest(AccessTokenID tokenId, const std::string deviceId, const std::string& bundleName, + const std::vector permissionList, PermissionUsedRequest& request); + void CheckPermissionUsedResult(const PermissionUsedRequest& request, const PermissionUsedResult& result, + int32_t permRecordSize, int32_t totalSuccessCount, int32_t totalFailCount); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_KIT_TEST_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/token_callback/BUILD.gn new file mode 100644 index 000000000..aab55f801 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("token_callback") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_shared_library("libtoken_callback_sdk") { + subsystem_name = "security" + part_name = "access_token" + + output_name = "libtoken_callback_sdk" + + public_configs = [ ":token_callback" ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "include", + "src", + "//base/security/access_token/frameworks/privacy/include", + "//base/security/access_token/frameworks/common/include", + ] + + sources = [ + "src/token_callback_proxy.cpp", + "src/token_callback_stub.cpp", + ] + + deps = [ + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + cflags_cc = [ + "-DHILOG_ENABLE", + "-DDEBUG_API_PERFORMANCE", + ] + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/i_token_callback.h b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/i_token_callback.h new file mode 100644 index 000000000..091577b5c --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/i_token_callback.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_TOKEN_CALLBACK_H +#define I_TOKEN_CALLBACK_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class ITokenCallback : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.tokencallback"); + + virtual void GrantResultsCallback( + const std::vector &permissions, const std::vector &grantResults) = 0; + + enum InterfaceCode { + GRANT_RESULT_CALLBACK = 0, + }; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // I_TOKEN_CALLBACK_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_proxy.h b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_proxy.h new file mode 100644 index 000000000..bba2db4e2 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_proxy.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H +#define PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H + +#include "i_token_callback.h" + +#include "iremote_proxy.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenCallbackProxy : public IRemoteProxy { +public: + explicit TokenCallbackProxy(const sptr& impl); + ~TokenCallbackProxy() override; + + virtual void GrantResultsCallback( + const std::vector &permissions, const std::vector &grantResults) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_stub.h b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_stub.h new file mode 100644 index 000000000..541b01c19 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/include/token_callback_stub.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_TOKEN_CALLBACK_STUB_H +#define I_TOKEN_CALLBACK_STUB_H + +#include "i_token_callback.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenCallbackStub : public IRemoteStub { +public: + TokenCallbackStub() = default; + virtual ~TokenCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // I_TOKEN_CALLBACK_STUB_H \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_proxy.cpp b/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_proxy.cpp new file mode 100644 index 000000000..b7fc7b759 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_proxy.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_callback_proxy.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenCallbackProxy" +}; +static const int32_t LIST_SIZE_MAX = 1024; +} + +TokenCallbackProxy::TokenCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +TokenCallbackProxy::~TokenCallbackProxy() +{} + +void TokenCallbackProxy::GrantResultsCallback( + const std::vector &permissions, const std::vector &grantResults) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(ITokenCallback::GetDescriptor())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor"); + return; + } + + uint32_t listSize = permissions.size(); + uint32_t resultSize = grantResults.size(); + if ((listSize > LIST_SIZE_MAX) || (resultSize != listSize)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "listSize %{public}d or resultSize %{public}d is invalid", listSize, resultSize); + return; + } + if (!data.WriteUint32(listSize)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write listSize"); + return; + } + for (uint32_t i = 0; i < listSize; i++) { + if (!data.WriteString(permissions[i])) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permList[%{public}d], %{public}s", i, permissions[i].c_str()); + return; + } + } + + if (!data.WriteUint32(resultSize)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write resultSize"); + return; + } + for (uint32_t i = 0; i < resultSize; i++) { + if (!data.WriteInt32(grantResults[i])) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permList[%{public}d], %{public}d", i, grantResults[i]); + return; + } + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenCallback::GRANT_RESULT_CALLBACK), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "SendRequest success"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_stub.cpp b/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_stub.cpp new file mode 100644 index 000000000..e51cd4c87 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_callback/src/token_callback_stub.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_callback_stub.h" + +#include "accesstoken_log.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "TokenCallbackStub" +}; +static const int32_t LIST_SIZE_MAX = 200; +static const int32_t FAILED = -1; +} + +static std::string to_utf8(std::u16string str16) +{ + return std::wstring_convert, char16_t> {}.to_bytes(str16); +} + +int32_t TokenCallbackStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, code: 0x%{public}x", code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != ITokenCallback::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return FAILED; + } + + int32_t msgCode = static_cast(code); + if (msgCode == ITokenCallback::GRANT_RESULT_CALLBACK) { + uint32_t permListSize = data.ReadUint32(); + if (permListSize > LIST_SIZE_MAX) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read permListSize fail %{public}u", permListSize); + return FAILED; + } + std::vector permList; + for (uint32_t i = 0; i < permListSize; i++) { + std::u16string u16Perm = data.ReadString16(); + std::string perm = to_utf8(u16Perm); + permList.emplace_back(perm); + } + + uint32_t statusListSize = data.ReadUint32(); + if (statusListSize != permListSize) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read statusListSize fail %{public}u", statusListSize); + return FAILED; + } + std::vector grantResults; + for (uint32_t i = 0; i < permListSize; i++) { + int32_t res = data.ReadInt32(); + grantResults.emplace_back(res); + } + GrantResultsCallback(permList, grantResults); + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return 0; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/BUILD.gn new file mode 100644 index 000000000..c9e91906d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/BUILD.gn @@ -0,0 +1,40 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +config("token_setproc") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_static_library("libtoken_setproc") { + subsystem_name = "security" + part_name = "access_token" + output_name = "libtoken_setproc" + + public_configs = [ ":token_setproc" ] + + cflags = [ "-Wall" ] + + include_dirs = [ + "include", + "src", + ] + + sources = [ "src/token_setproc.c" ] + + deps = [] + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/include/token_setproc.h b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/include/token_setproc.h new file mode 100644 index 000000000..aa1b77bd5 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/include/token_setproc.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SETPROC_H +#define TOKEN_SETPROC_H +#include + +#ifdef __cplusplus +extern "C" { +#endif + +uint64_t GetSelfTokenID(); + +int SetSelfTokenID(uint64_t tokenID); + +uint64_t GetFirstCallerTokenID(); + +int SetFirstCallerTokenID(uint64_t tokenID); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/src/token_setproc.c b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/src/token_setproc.c new file mode 100644 index 000000000..8ca00b881 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/src/token_setproc.c @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_setproc.h" + +#include +#include +#include +#include + +#define ACCESS_TOKEN_ID_IOCTL_BASE 'A' + +enum { + GET_TOKEN_ID = 1, + SET_TOKEN_ID, + GET_FTOKEN_ID, + SET_FTOKEN_ID, + ACCESS_TOKENID_MAX_NR, +}; + +#define ACCESS_TOKENID_GET_TOKENID \ + _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_TOKEN_ID, uint64_t) +#define ACCESS_TOKENID_SET_TOKENID \ + _IOW(ACCESS_TOKEN_ID_IOCTL_BASE, SET_TOKEN_ID, uint64_t) +#define ACCESS_TOKENID_GET_FTOKENID \ + _IOR(ACCESS_TOKEN_ID_IOCTL_BASE, GET_FTOKEN_ID, uint64_t) +#define ACCESS_TOKENID_SET_FTOKENID \ + _IOW(ACCESS_TOKEN_ID_IOCTL_BASE, SET_FTOKEN_ID, uint64_t) + +#define ACCESS_TOKEN_OK 0 +#define ACCESS_TOKEN_ERROR (-1) + +#define INVAL_TOKEN_ID 0x0 +#define TOKEN_ID_LOWMASK 0xffffffff + +#define TOKENID_DEVNODE "/dev/access_token_id" + +uint64_t GetSelfTokenID(void) +{ + uint64_t token = INVAL_TOKEN_ID; + int fd = open(TOKENID_DEVNODE, O_RDWR); + if (fd < 0) { + return INVAL_TOKEN_ID; + } + int ret = ioctl(fd, ACCESS_TOKENID_GET_TOKENID, &token); + if (ret) { + close(fd); + return INVAL_TOKEN_ID; + } + + close(fd); + return token; +} + +int SetSelfTokenID(uint64_t tokenID) +{ + int fd = open(TOKENID_DEVNODE, O_RDWR); + if (fd < 0) { + return ACCESS_TOKEN_ERROR; + } + int ret = ioctl(fd, ACCESS_TOKENID_SET_TOKENID, &tokenID); + if (ret) { + close(fd); + return ACCESS_TOKEN_ERROR; + } + + close(fd); + return ACCESS_TOKEN_OK; +} + +uint64_t GetFirstCallerTokenID(void) +{ + uint64_t token = INVAL_TOKEN_ID; + int fd = open(TOKENID_DEVNODE, O_RDWR); + if (fd < 0) { + return INVAL_TOKEN_ID; + } + int ret = ioctl(fd, ACCESS_TOKENID_GET_FTOKENID, &token); + if (ret) { + close(fd); + return INVAL_TOKEN_ID; + } + + close(fd); + return token; +} + + +int SetFirstCallerTokenID(uint64_t tokenID) +{ + int fd = open(TOKENID_DEVNODE, O_RDWR); + if (fd < 0) { + return ACCESS_TOKEN_ERROR; + } + int ret = ioctl(fd, ACCESS_TOKENID_SET_FTOKENID, &tokenID); + if (ret) { + close(fd); + return ACCESS_TOKEN_ERROR; + } + + close(fd); + return ACCESS_TOKEN_OK; +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/BUILD.gn new file mode 100644 index 000000000..b6e11d2ad --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/BUILD.gn @@ -0,0 +1,38 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libtoken_setproc_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//base/security/access_token/interfaces/innerkits/token_setproc/include", + ] + + sources = [ "unittest/src/tokensetproc_kit_test.cpp" ] + cflags_cc = [ "-fexceptions" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libtoken_setproc_test" ] +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.cpp b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.cpp new file mode 100644 index 000000000..c6f94bbc0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tokensetproc_kit_test.h" + +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS::Security; + +void TokensetprocKitTest::SetUpTestCase() +{} + +void TokensetprocKitTest::TearDownTestCase() +{} + +void TokensetprocKitTest::SetUp() +{} + +void TokensetprocKitTest::TearDown() +{} \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.h b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.h new file mode 100644 index 000000000..2da208d9b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/token_setproc/test/unittest/src/tokensetproc_kit_test.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_KIT_TEST_H +#define TOKENSYNC_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +class TokensetprocKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace Security +} // namespace OHOS +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/tokensync/BUILD.gn new file mode 100644 index 000000000..40ba7d399 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") + +config("tokensync") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +if (is_standard_system) { + ohos_shared_library("libtokensync_sdk") { + subsystem_name = "security" + part_name = "access_token" + + output_name = "libtokensync_sdk" + + public_configs = [ ":tokensync" ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "include", + "src", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "src/token_sync_death_recipient.cpp", + "src/token_sync_kit.cpp", + "src/token_sync_load_callback.cpp", + "src/token_sync_manager_client.cpp", + "src/token_sync_manager_proxy.cpp", + ] + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + } +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/include/token_sync_kit.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/include/token_sync_kit.h new file mode 100644 index 000000000..24c65f0d0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/include/token_sync_kit.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_INNER_KITS_TOKENSYNC_KIT_H +#define INTERFACES_INNER_KITS_TOKENSYNC_KIT_H + +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncKit { +public: + static int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID); + static int DeleteRemoteHapTokenInfo(AccessTokenID tokenID); + static int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.cpp new file mode 100644 index 000000000..aaa86fe08 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_death_recipient.h" + +#include "token_sync_manager_client.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncDeathRecipient"}; +} + +void TokenSyncDeathRecipient::OnRemoteDied(const wptr& onject) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); + + TokenSyncManagerClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.h new file mode 100644 index 000000000..4007d086e --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_death_recipient.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_DEATH_RECIPIENT_H +#define TOKEN_SYNC_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncDeathRecipient : public IRemoteObject::DeathRecipient { +public: + TokenSyncDeathRecipient() + {} + + virtual ~TokenSyncDeathRecipient() = default; + void OnRemoteDied(const wptr& onject) override; +private: +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_DEATH_RECIPIENT_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_kit.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_kit.cpp new file mode 100644 index 000000000..28de089ff --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_kit.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_kit.h" + +#include +#include + +#include "accesstoken_log.h" +#include "constant_common.h" +#include "token_sync_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +using namespace std; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncKit"}; +} // namespace + +int TokenSyncKit::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo(deviceID, tokenID); +} + +int TokenSyncKit::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID=%{public}d", __func__, tokenID); + return TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(tokenID); +} + +int TokenSyncKit::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called tokenID=%{public}d", __func__, tokenInfo.baseInfo.tokenID); + return TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.cpp new file mode 100644 index 000000000..2914dcd25 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_load_callback.h" + +#include "accesstoken_log.h" +#include "i_token_sync_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncLoadCallBack"}; +} + +TokenSyncLoadCallback::TokenSyncLoadCallback() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "enter"); +} + +void TokenSyncLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, + const sptr& remoteObject) +{ + if (systemAbilityId != ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "start aystemabilityId is not TokenSync!"); + return; + } + + if (remoteObject == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remoteObject is null."); + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnLoadSystemAbilitySuccess start systemAbilityId: %{public}d success!", + systemAbilityId); + + TokenSyncManagerClient::GetInstance().FinishStartSASuccess(remoteObject); +} + +void TokenSyncLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + if (systemAbilityId != ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "start aystemabilityId is not TokenSync!"); + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnLoadSystemAbilityFail systemAbilityId: %{public}d failed.", systemAbilityId); + + TokenSyncManagerClient::GetInstance().FinishStartSAFailed(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.h new file mode 100644 index 000000000..ba5c2f95a --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_load_callback.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_LOAD_CALLBACK_H +#define TOKEN_SYNC_LOAD_CALLBACK_H + +#include "system_ability_load_callback_stub.h" +#include "i_token_sync_manager.h" +#include "token_sync_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncLoadCallback : public SystemAbilityLoadCallbackStub { +public: + explicit TokenSyncLoadCallback(); + + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr& remoteObject); + void OnLoadSystemAbilityFail(int32_t systemAbilityId); +private: +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_LOAD_CALLBACK_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp new file mode 100644 index 000000000..7cbe9665d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_manager_client.h" + +#include "accesstoken_log.h" +#include "hap_token_info_for_sync_parcel.h" +#include "native_token_info_for_sync_parcel.h" +#include "iservice_registry.h" +#include "token_sync_death_recipient.h" +#include "token_sync_load_callback.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerClient"}; +} // namespace + +TokenSyncManagerClient& TokenSyncManagerClient::GetInstance() +{ + static TokenSyncManagerClient instance; + return instance; +} + +TokenSyncManagerClient::TokenSyncManagerClient() +{} + +TokenSyncManagerClient::~TokenSyncManagerClient() +{} + +int TokenSyncManagerClient::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return -1; + } + return proxy->GetRemoteHapTokenInfo(deviceID, tokenID); +} + +int TokenSyncManagerClient::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return -1; + } + return proxy->DeleteRemoteHapTokenInfo(tokenID); +} + +int TokenSyncManagerClient::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return -1; + } + return proxy->UpdateRemoteHapTokenInfo(tokenInfo); +} + +void TokenSyncManagerClient::LoadTokenSync() +{ + { + std::unique_lock lock(tokenSyncMutex_); + ready_ = false; + } + + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetSystemAbilityManager return null"); + return; + } + + sptr ptrTokenSyncLoadCallback = new (std::nothrow) TokenSyncLoadCallback(); + if (ptrTokenSyncLoadCallback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new ptrTokenSyncLoadCallback fail."); + return; + } + + int32_t result = sam->LoadSystemAbility(ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE, + ptrTokenSyncLoadCallback); + if (result != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "LoadSystemAbility %{public}d failed", + ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE); + return; + } + + { + std::unique_lock lock(tokenSyncMutex_); + // wait_for release lock and block until time out(60s) or match the condition with notice + auto waitStatus = tokenSyncCon_.wait_for(lock, std::chrono::milliseconds(TOKEN_SYNC_LOAD_SA_TIMEOUT_MS), + [this]() { return ready_; }); + if (!waitStatus) { + // time out or loadcallback fail + ACCESSTOKEN_LOG_WARN(LABEL, "tokensync load sa timeout"); + return; + } + } + + if (GetRemoteObject() == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "remote object is null"); + return; + } + sptr ptrTokenSyncDeathRecipient = new (std::nothrow) TokenSyncDeathRecipient(); + if (ptrTokenSyncDeathRecipient == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new TokenSyncDeathRecipient fail."); + return; + } + // add death recipient to reset token_sync + GetRemoteObject()->AddDeathRecipient(ptrTokenSyncDeathRecipient); +} + +void TokenSyncManagerClient::FinishStartSASuccess(const sptr& remoteObject) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "get tokensync sa success."); + + SetRemoteObject(remoteObject); + + // get lock which wait_for release and send a notice so that wait_for can out of block + { + std::unique_lock lock(tokenSyncMutex_); + ready_ = true; + } + + tokenSyncCon_.notify_one(); +} + +void TokenSyncManagerClient::FinishStartSAFailed() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "get tokensync sa failed."); + + SetRemoteObject(nullptr); + + // get lock which wait_for release and send a notice + { + std::unique_lock lock(tokenSyncMutex_); + ready_ = true; + } + + tokenSyncCon_.notify_one(); +} + +void TokenSyncManagerClient::SetRemoteObject(const sptr& remoteObject) +{ + std::unique_lock lock(remoteMutex_); + remoteObject_ = remoteObject; +} + +sptr TokenSyncManagerClient::GetRemoteObject() +{ + std::unique_lock lock(remoteMutex_); + return remoteObject_; +} + +void TokenSyncManagerClient::OnRemoteDiedHandle() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Remote service died."); + + SetRemoteObject(nullptr); + + std::unique_lock lock(tokenSyncMutex_); + ready_ = false; +} + +sptr TokenSyncManagerClient::GetProxy() +{ + if (GetRemoteObject() == nullptr) { + LoadTokenSync(); + } + + auto proxy = iface_cast(GetRemoteObject()); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "iface_cast get null"); + return nullptr; + } + return proxy; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.h new file mode 100644 index 000000000..4a58c28f2 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_client.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_CLIENT_H +#define ACCESSTOKEN_MANAGER_CLIENT_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "i_token_sync_manager.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncManagerClient final { +public: + static const int TOKEN_SYNC_LOAD_SA_TIMEOUT_MS = 60000; + + static TokenSyncManagerClient& GetInstance(); + + virtual ~TokenSyncManagerClient(); + + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID); + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID); + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo); + void LoadTokenSync(); + void FinishStartSASuccess(const sptr& remoteObject); + void FinishStartSAFailed(); + void SetRemoteObject(const sptr& remoteObject); + sptr GetRemoteObject(); + void OnRemoteDiedHandle(); + +private: + std::condition_variable tokenSyncCon_; + std::mutex tokenSyncMutex_; + std::mutex remoteMutex_; + bool ready_ = false; + sptr remoteObject_ = nullptr; + + TokenSyncManagerClient(); + + DISALLOW_COPY_AND_MOVE(TokenSyncManagerClient); + + sptr GetProxy(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_CLIENT_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp new file mode 100644 index 000000000..ac3625e60 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_manager_proxy.h" + +#include "accesstoken_log.h" +#include "parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerProxy"}; +} + +TokenSyncManagerProxy::TokenSyncManagerProxy(const sptr& impl) : IRemoteProxy(impl) +{} + +TokenSyncManagerProxy::~TokenSyncManagerProxy() +{} + +int TokenSyncManagerProxy::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write deviceID"); + return -1; + } + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return -1; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::GET_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return -1; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int TokenSyncManagerProxy::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return -1; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::DELETE_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return -1; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int TokenSyncManagerProxy::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + + HapTokenInfoForSyncParcel tokenInfoParcel; + tokenInfoParcel.hapTokenInfoForSyncParams = tokenInfo; + + if (!data.WriteParcelable(&tokenInfoParcel)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenInfo"); + return -1; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::UPDATE_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return -1; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h new file mode 100644 index 000000000..9568bfa6d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_MANAGER_PROXY_H +#define TOKENSYNC_MANAGER_PROXY_H + +#include + +#include "access_token.h" +#include "hap_token_info_for_sync_parcel.h" +#include "i_token_sync_manager.h" +#include "iremote_broker.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncManagerProxy : public IRemoteProxy { +public: + explicit TokenSyncManagerProxy(const sptr& impl); + ~TokenSyncManagerProxy() override; + + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) override; + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_MANAGER_PROXY_H diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/BUILD.gn b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/BUILD.gn new file mode 100644 index 000000000..19728ed2c --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/BUILD.gn @@ -0,0 +1,42 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libtokensync_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + + sources = [ "unittest/src/token_sync_kit_test.cpp" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + #"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", + "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", + ] + external_deps = [ "c_utils:utils" ] +} + +group("unittest") { + testonly = true + deps = [ ":libtokensync_sdk_test" ] +} diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp new file mode 100644 index 000000000..1c46de6b0 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_kit_test.h" + +#include "token_sync_kit.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +void TokenSyncKitTest::SetUpTestCase() +{} + +void TokenSyncKitTest::TearDownTestCase() +{ +} + +void TokenSyncKitTest::SetUp() +{ +} + +void TokenSyncKitTest::TearDown() +{} + diff --git a/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h new file mode 100644 index 000000000..7f9e942d3 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKENSYNC_KIT_TEST_H +#define TOKENSYNC_KIT_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKENSYNC_KIT_TEST_H diff --git a/security_access_token-yl_0822/interfaces/kits/BUILD.gn b/security_access_token-yl_0822/interfaces/kits/BUILD.gn new file mode 100644 index 000000000..efa0874c6 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("napi_packages") { + deps = [] + if (support_jsapi) { + deps += [ + "//base/security/access_token/interfaces/kits/accesstoken:libabilityaccessctrl", + "//base/security/access_token/interfaces/kits/common:libnapi_common", + "//base/security/access_token/interfaces/kits/privacy:libprivacymanager", + ] + } +} diff --git a/security_access_token-yl_0822/interfaces/kits/accesstoken/BUILD.gn b/security_access_token-yl_0822/interfaces/kits/accesstoken/BUILD.gn new file mode 100644 index 000000000..71bd9856d --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/accesstoken/BUILD.gn @@ -0,0 +1,40 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("libabilityaccessctrl") { + include_dirs = [ + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/kits/accesstoken/napi/include", + "//foundation/arkui/napi/interfaces/inner_api", + "//foundation/arkui/napi/interfaces/kits", + ] + + sources = [ "//base/security/access_token/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//foundation/arkui/napi:ace_napi", + ] + cflags_cc = [ "-DHILOG_ENABLE" ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "security" + part_name = "access_token" +} diff --git a/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/include/napi_atmanager.h b/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/include/napi_atmanager.h new file mode 100644 index 000000000..167e816c9 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/include/napi_atmanager.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_KITS_ACCESSTOKEN_NAPI_INCLUDE_NAPI_ATMANAGER_H +#define INTERFACES_KITS_ACCESSTOKEN_NAPI_INCLUDE_NAPI_ATMANAGER_H + +#include +#include +#include +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const int AT_PERM_OPERA_FAIL = -1; +const int AT_PERM_OPERA_SUCC = 0; +const int VALUE_BUFFER_SIZE = 256; +const int ASYNC_CALL_BACK_VALUES_NUM = 2; +const int VERIFY_OR_FLAG_INPUT_MAX_VALUES = 2; +const int GRANT_OR_REVOKE_INPUT_MAX_VALUES = 4; + +static thread_local napi_ref atManagerRef_; +const std::string ATMANAGER_CLASS_NAME = "atManager"; + +struct AtManagerAsyncContext { + napi_env env = nullptr; + uint32_t tokenId = 0; + char permissionName[ VALUE_BUFFER_SIZE ] = { 0 }; + size_t pNameLen = 0; + int flag = 0; + int result = AT_PERM_OPERA_FAIL; // default failed + + napi_deferred deferred = nullptr; // promise handle + napi_ref callbackRef = nullptr; // callback handle + napi_async_work work = nullptr; // work handle +}; + +class NapiAtManager { +public: + static napi_value Init(napi_env env, napi_value exports); + +private: + static napi_value JsConstructor(napi_env env, napi_callback_info cbinfo); + static napi_value CreateAtManager(napi_env env, napi_callback_info cbInfo); + static napi_value VerifyAccessToken(napi_env env, napi_callback_info info); + static napi_value VerifyAccessTokenSync(napi_env env, napi_callback_info info); + static napi_value GrantUserGrantedPermission(napi_env env, napi_callback_info info); + static napi_value RevokeUserGrantedPermission(napi_env env, napi_callback_info info); + static napi_value GetPermissionFlags(napi_env env, napi_callback_info info); + + static void ParseInputVerifyPermissionOrGetFlag(const napi_env env, const napi_callback_info info, + AtManagerAsyncContext& asyncContext); + static void VerifyAccessTokenExecute(napi_env env, void *data); + static void VerifyAccessTokenComplete(napi_env env, napi_status status, void *data); + static void ParseInputGrantOrRevokePermission(const napi_env env, const napi_callback_info info, + AtManagerAsyncContext& asyncContext); + static void GrantUserGrantedPermissionExcute(napi_env env, void *data); + static void GrantUserGrantedPermissionComplete(napi_env env, napi_status status, void *data); + static void RevokeUserGrantedPermissionExcute(napi_env env, void *data); + static void RevokeUserGrantedPermissionComplete(napi_env env, napi_status status, void *data); + static void GetPermissionFlagsExcute(napi_env env, void *data); + static void GetPermissionFlagsComplete(napi_env env, napi_status status, void *data); + static void SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports); + +#endif /* INTERFACES_KITS_ACCESSTOKEN_NAPI_INCLUDE_NAPI_ATMANAGER_H */ diff --git a/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp b/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp new file mode 100644 index 000000000..a74f44ccc --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp @@ -0,0 +1,588 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "napi_atmanager.h" + +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenAbilityAccessCtrl" +}; +} // namespace + +void NapiAtManager::SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName) +{ + napi_value prop = nullptr; + napi_create_int32(env, objValue, &prop); + napi_set_named_property(env, dstObj, propName, prop); +} + +napi_value NapiAtManager::Init(napi_env env, napi_value exports) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "enter init."); + + napi_property_descriptor descriptor[] = { DECLARE_NAPI_FUNCTION("createAtManager", CreateAtManager) }; + + NAPI_CALL(env, napi_define_properties(env, + exports, sizeof(descriptor) / sizeof(napi_property_descriptor), descriptor)); + + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("verifyAccessToken", VerifyAccessToken), + DECLARE_NAPI_FUNCTION("verifyAccessTokenSync", VerifyAccessTokenSync), + DECLARE_NAPI_FUNCTION("grantUserGrantedPermission", GrantUserGrantedPermission), + DECLARE_NAPI_FUNCTION("revokeUserGrantedPermission", RevokeUserGrantedPermission), + DECLARE_NAPI_FUNCTION("getPermissionFlags", GetPermissionFlags) + }; + + napi_value cons = nullptr; + NAPI_CALL(env, napi_define_class(env, ATMANAGER_CLASS_NAME.c_str(), ATMANAGER_CLASS_NAME.size(), + JsConstructor, nullptr, sizeof(properties) / sizeof(napi_property_descriptor), properties, &cons)); + + NAPI_CALL(env, napi_create_reference(env, cons, 1, &atManagerRef_)); + NAPI_CALL(env, napi_set_named_property(env, exports, ATMANAGER_CLASS_NAME.c_str(), cons)); + + napi_value GrantStatus = nullptr; + napi_create_object(env, &GrantStatus); + + SetNamedProperty(env, GrantStatus, PERMISSION_DENIED, "PERMISSION_DENIED"); + SetNamedProperty(env, GrantStatus, PERMISSION_GRANTED, "PERMISSION_GRANTED"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("GrantStatus", GrantStatus), + }; + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + + return exports; +} + +napi_value NapiAtManager::JsConstructor(napi_env env, napi_callback_info cbinfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "enter JsConstructor"); + + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, nullptr)); + + return thisVar; +} + +napi_value NapiAtManager::CreateAtManager(napi_env env, napi_callback_info cbInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "enter CreateAtManager"); + + napi_value instance = nullptr; + napi_value cons = nullptr; + + if (napi_get_reference_value(env, atManagerRef_, &cons) != napi_ok) { + return nullptr; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "Get a reference to the global variable atManagerRef_ complete"); + + if (napi_new_instance(env, cons, 0, nullptr, &instance) != napi_ok) { + return nullptr; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "New the js instance complete"); + + return instance; +} + +void NapiAtManager::ParseInputVerifyPermissionOrGetFlag(const napi_env env, const napi_callback_info info, + AtManagerAsyncContext& asyncContext) +{ + size_t argc = VERIFY_OR_FLAG_INPUT_MAX_VALUES; + + napi_value argv[VERIFY_OR_FLAG_INPUT_MAX_VALUES] = { 0 }; + napi_value thisVar = nullptr; + + void *data = nullptr; + + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + + asyncContext.env = env; + + // parse input tokenId and permissionName + for (size_t i = 0; i < argc; i++) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + + if (valueType == napi_number) { + napi_get_value_uint32(env, argv[i], &(asyncContext.tokenId)); // get tokenId + } else if (valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext.permissionName, + VALUE_BUFFER_SIZE + 1, &(asyncContext.pNameLen)); // get permissionName + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "Type matching failed"); + return; + } + } + + asyncContext.result = AT_PERM_OPERA_SUCC; + + ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenID = %{public}d, permissionName = %{public}s", asyncContext.tokenId, + asyncContext.permissionName); +} + +void NapiAtManager::VerifyAccessTokenExecute(napi_env env, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + + // use innerkit class method to verify permission + asyncContext->result = AccessTokenKit::VerifyAccessToken(asyncContext->tokenId, + asyncContext->permissionName); +} + +void NapiAtManager::VerifyAccessTokenComplete(napi_env env, napi_status status, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + napi_value result; + + ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenId = %{public}d, permissionName = %{public}s, verify result = %{public}d.", + asyncContext->tokenId, asyncContext->permissionName, asyncContext->result); + + // only resolve, no reject currently + napi_create_int32(env, asyncContext->result, &result); // verify result + napi_resolve_deferred(env, asyncContext->deferred, result); + + // after return the result, free resources + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; +} + +napi_value NapiAtManager::VerifyAccessToken(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "VerifyAccessToken begin."); + + auto *asyncContext = new AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + ParseInputVerifyPermissionOrGetFlag(env, info, *asyncContext); + if (asyncContext->result == AT_PERM_OPERA_FAIL) { + delete asyncContext; + return nullptr; + } + + // after get input, keep result default failed + asyncContext->result = AT_PERM_OPERA_FAIL; + + napi_value result = nullptr; + napi_create_promise(env, &(asyncContext->deferred), &result); // create delay promise object + + napi_value resource = nullptr; // resource name + napi_create_string_utf8(env, "VerifyAccessToken", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( // define work + env, nullptr, resource, VerifyAccessTokenExecute, VerifyAccessTokenComplete, + reinterpret_cast(asyncContext), &(asyncContext->work)); + napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result + + ACCESSTOKEN_LOG_DEBUG(LABEL, "VerifyAccessToken end."); + + return result; +} + +napi_value NapiAtManager::VerifyAccessTokenSync(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "VerifyAccessToken begin."); + + auto *asyncContext = new AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + ParseInputVerifyPermissionOrGetFlag(env, info, *asyncContext); + if (asyncContext->result == AT_PERM_OPERA_FAIL) { + delete asyncContext; + return nullptr; + } + + // use innerkit class method to verify permission + asyncContext->result = AccessTokenKit::VerifyAccessToken(asyncContext->tokenId, + asyncContext->permissionName); + + napi_value result = nullptr; + napi_create_int32(env, asyncContext->result, &result); // verify result + + ACCESSTOKEN_LOG_DEBUG(LABEL, "VerifyAccessToken end."); + + return result; +} + +void NapiAtManager::ParseInputGrantOrRevokePermission(const napi_env env, const napi_callback_info info, + AtManagerAsyncContext& asyncContext) +{ + size_t argc = GRANT_OR_REVOKE_INPUT_MAX_VALUES; + + napi_value argv[GRANT_OR_REVOKE_INPUT_MAX_VALUES] = {nullptr}; + napi_value thisVar = nullptr; + + void *data = nullptr; + + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + + asyncContext.env = env; + + // parse input tokenId and permissionName + for (size_t i = 0; i < argc; i++) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + + if ((i == 0) && (valueType == napi_number)) { + napi_get_value_uint32(env, argv[i], &(asyncContext.tokenId)); // get tokenId + } else if (valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext.permissionName, + VALUE_BUFFER_SIZE + 1, &(asyncContext.pNameLen)); // get permissionName + } else if (valueType == napi_number) { + napi_get_value_int32(env, argv[i], &(asyncContext.flag)); // get flag + } else if (valueType == napi_function) { + napi_create_reference(env, argv[i], 1, &asyncContext.callbackRef); // get probably callback + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "Type matching failed"); + return; + } + } + + asyncContext.result = AT_PERM_OPERA_SUCC; + + ACCESSTOKEN_LOG_DEBUG(LABEL, "tokenID = %{public}d, permissionName = %{public}s, flag = %{public}d", + asyncContext.tokenId, asyncContext.permissionName, asyncContext.flag); +} + +void NapiAtManager::GrantUserGrantedPermissionExcute(napi_env env, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + PermissionDef permissionDef; + + // struct init, can not use = { 0 } or memset otherwise program crashdump + permissionDef.grantMode = 0; + permissionDef.availableLevel = APL_NORMAL; + permissionDef.provisionEnable = false; + permissionDef.distributedSceneEnable = false; + permissionDef.labelId = 0; + permissionDef.descriptionId = 0; + + // use innerkit class method to check if the permission grantmode is USER_GRANT-0 + int ret = AccessTokenKit::GetDefPermission(asyncContext->permissionName, permissionDef); + if (ret) { + // this means permission is undefined, return failed + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "permissionName = %{public}s, grantmode = %{public}d.", asyncContext->permissionName, + permissionDef.grantMode); + + // only user_grant permission can use innerkit class method to grant permission, system_grant return failed + if (permissionDef.grantMode == USER_GRANT) { + asyncContext->result = AccessTokenKit::GrantPermission(asyncContext->tokenId, asyncContext->permissionName, + asyncContext->flag); + + ACCESSTOKEN_LOG_DEBUG(LABEL, + "tokenId = %{public}d, permissionName = %{public}s, flag = %{public}d, grant result = %{public}d.", + asyncContext->tokenId, asyncContext->permissionName, asyncContext->flag, asyncContext->result); + } +} + +void NapiAtManager::GrantUserGrantedPermissionComplete(napi_env env, napi_status status, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; // for AsyncCallback + + // no err, results[0] remain nullptr + napi_create_int32(env, asyncContext->result, &results[ASYNC_CALL_BACK_VALUES_NUM - 1]); + + if (asyncContext->deferred) { + // promise type, no reject currently + napi_resolve_deferred(env, asyncContext->deferred, results[ASYNC_CALL_BACK_VALUES_NUM - 1]); + } else { + // callback type + napi_value callback = nullptr; + napi_value thisValue = nullptr; // recv napi value + napi_value thatValue = nullptr; // result napi value + + // set call function params->napi_call_function(env, recv, func, argc, argv, result) + napi_get_undefined(env, &thisValue); // can not null otherwise js code can not get return + napi_create_int32(env, 0, &thatValue); // can not null otherwise js code can not get return + napi_get_reference_value(env, asyncContext->callbackRef, &callback); + napi_call_function(env, thisValue, callback, ASYNC_CALL_BACK_VALUES_NUM, results, &thatValue); + napi_delete_reference(env, asyncContext->callbackRef); // release callback handle + } + + // after return the result, free resources + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; +} + +napi_value NapiAtManager::GrantUserGrantedPermission(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GrantUserGrantedPermission begin."); + + auto *asyncContext = new (std::nothrow) AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + ParseInputGrantOrRevokePermission(env, info, *asyncContext); + if (asyncContext->result == AT_PERM_OPERA_FAIL) { + delete asyncContext; + return nullptr; + } + + // after get input, keep result default failed + asyncContext->result = AT_PERM_OPERA_FAIL; + + napi_value result = nullptr; + + if (asyncContext->callbackRef == nullptr) { + // when callback null, create delay promise object for returning result in async work complete function + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + // callback not null, use callback type to return result + napi_get_undefined(env, &result); + } + + napi_value resource = nullptr; // resource name + napi_create_string_utf8(env, "GrantUserGrantedPermission", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( // define work + env, nullptr, resource, GrantUserGrantedPermissionExcute, GrantUserGrantedPermissionComplete, + reinterpret_cast(asyncContext), &(asyncContext->work)); + + napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result + + ACCESSTOKEN_LOG_DEBUG(LABEL, "GrantUserGrantedPermission end."); + + return result; +} + +void NapiAtManager::RevokeUserGrantedPermissionExcute(napi_env env, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + PermissionDef permissionDef; + + // struct init, can not use = { 0 } or memset otherwise program crashdump + permissionDef.grantMode = 0; + permissionDef.availableLevel = APL_NORMAL; + permissionDef.provisionEnable = false; + permissionDef.distributedSceneEnable = false; + permissionDef.labelId = 0; + permissionDef.descriptionId = 0; + + // use innerkit class method to check if the permission grantmode is USER_GRANT-0 + int ret = AccessTokenKit::GetDefPermission(asyncContext->permissionName, permissionDef); + if (ret) { + // this means permission is undefined, return failed + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "permissionName = %{public}s, grantmode = %{public}d.", asyncContext->permissionName, + permissionDef.grantMode); + + // only user_grant permission can use innerkit class method to grant permission, system_grant return failed + if (permissionDef.grantMode == USER_GRANT) { + asyncContext->result = AccessTokenKit::RevokePermission(asyncContext->tokenId, asyncContext->permissionName, + asyncContext->flag); + + ACCESSTOKEN_LOG_DEBUG(LABEL, + "tokenId = %{public}d, permissionName = %{public}s, flag = %{public}d, revoke result = %{public}d.", + asyncContext->tokenId, asyncContext->permissionName, asyncContext->flag, asyncContext->result); + } +} + +void NapiAtManager::RevokeUserGrantedPermissionComplete(napi_env env, napi_status status, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; // for AsyncCallback + + // no err, results[0] remain nullptr + napi_create_int32(env, asyncContext->result, &results[ASYNC_CALL_BACK_VALUES_NUM - 1]); + + if (asyncContext->deferred) { + // promise type, no reject currently + napi_resolve_deferred(env, asyncContext->deferred, results[ASYNC_CALL_BACK_VALUES_NUM - 1]); + } else { + // callback type + napi_value callback = nullptr; + napi_value thisValue = nullptr; // recv napi value + napi_value thatValue = nullptr; // result napi value + + // set call function params->napi_call_function(env, recv, func, argc, argv, result) + napi_get_undefined(env, &thisValue); // can not null otherwise js code can not get return + napi_create_int32(env, 0, &thatValue); // can not null otherwise js code can not get return + napi_get_reference_value(env, asyncContext->callbackRef, &callback); + napi_call_function(env, thisValue, callback, ASYNC_CALL_BACK_VALUES_NUM, results, &thatValue); + napi_delete_reference(env, asyncContext->callbackRef); // release callback handle + } + + // after return the result, free resources + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; +} + +napi_value NapiAtManager::RevokeUserGrantedPermission(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RevokeUserGrantedPermission begin."); + + auto *asyncContext = new AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + ParseInputGrantOrRevokePermission(env, info, *asyncContext); + if (asyncContext->result == AT_PERM_OPERA_FAIL) { + delete asyncContext; + return nullptr; + } + + // after get input, keep result default failed + asyncContext->result = AT_PERM_OPERA_FAIL; + + napi_value result = nullptr; + + if (asyncContext->callbackRef == nullptr) { + // when callback null, create delay promise object for returning result in async work complete function + napi_create_promise(env, &(asyncContext->deferred), &result); + } else { + // callback not null, use callback type to return result + napi_get_undefined(env, &result); + } + + napi_value resource = nullptr; // resource name + napi_create_string_utf8(env, "RevokeUserGrantedPermission", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( // define work + env, nullptr, resource, RevokeUserGrantedPermissionExcute, RevokeUserGrantedPermissionComplete, + reinterpret_cast(asyncContext), &(asyncContext->work)); + + napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result + + ACCESSTOKEN_LOG_DEBUG(LABEL, "RevokeUserGrantedPermission end."); + + return result; +} + +void NapiAtManager::GetPermissionFlagsExcute(napi_env env, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + + // use innerkit class method to get permission flag + asyncContext->flag = AccessTokenKit::GetPermissionFlag(asyncContext->tokenId, + asyncContext->permissionName); +} + +void NapiAtManager::GetPermissionFlagsComplete(napi_env env, napi_status status, void *data) +{ + AtManagerAsyncContext* asyncContext = reinterpret_cast(data); + napi_value result; + + ACCESSTOKEN_LOG_DEBUG(LABEL, "permissionName = %{public}s, tokenId = %{public}d, flag = %{public}d.", + asyncContext->permissionName, asyncContext->tokenId, asyncContext->flag); + + // only resolve, no reject currently + napi_create_int32(env, asyncContext->flag, &result); + napi_resolve_deferred(env, asyncContext->deferred, result); + + // after return the result, free resources + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; +} + +napi_value NapiAtManager::GetPermissionFlags(napi_env env, napi_callback_info info) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetPermissionFlags begin."); + + auto *asyncContext = new AtManagerAsyncContext(); // for async work deliver data + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + ParseInputVerifyPermissionOrGetFlag(env, info, *asyncContext); + if (asyncContext->result == AT_PERM_OPERA_FAIL) { + delete asyncContext; + return nullptr; + } + + // after get input, keep result default failed + asyncContext->result = AT_PERM_OPERA_FAIL; + + napi_value result = nullptr; + napi_create_promise(env, &(asyncContext->deferred), &result); // create delay promise object + + napi_value resource = nullptr; // resource name + napi_create_string_utf8(env, "VerifyAccessToken", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( // define work + env, nullptr, resource, GetPermissionFlagsExcute, GetPermissionFlagsComplete, + reinterpret_cast(asyncContext), &(asyncContext->work)); + napi_queue_async_work(env, asyncContext->work); // add async work handle to the napi queue and wait for result + + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetPermissionFlags end."); + + return result; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + ACCESSTOKEN_LOG_DEBUG(OHOS::Security::AccessToken::LABEL, "Register end, start init."); + + return OHOS::Security::AccessToken::NapiAtManager::Init(env, exports); +} +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "abilityAccessCtrl", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void AbilityAccessCtrlmoduleRegister(void) +{ + napi_module_register(&_module); +} diff --git a/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn b/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn new file mode 100644 index 000000000..8852db898 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +module_output_path = "access_token/interfaces_kit" + +config("access_token_kits_config_benchmarktest") { + visibility = [ ":*" ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/token_setproc/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include/permission_def.h", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_benchmarktest("NapiAtmanagerTest") { + module_out_path = module_output_path + + sources = [ "napi_atmanager_test.cpp" ] + configs = [ ":access_token_kits_config_benchmarktest" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//third_party/benchmark", + "//third_party/googletest:gtest_main", + ] +} + +group("benchmarktest") { + testonly = true + deps = [ ":NapiAtmanagerTest" ] +} diff --git a/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/napi_atmanager_test.cpp b/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/napi_atmanager_test.cpp new file mode 100644 index 000000000..9b08c8398 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/accesstoken/test/benchmarktest/napi_atmanager_test.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#undef private +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "permission_def.h" + +using namespace std; +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::AccessToken; + +namespace { +int32_t TOKENID = 0; + +static const std::string BENCHMARK_TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA"; +PermissionDef PERMISSIONDEF = { + .permissionName = "ohos.permission.test1", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +class NapiAtmanagerTest : public benchmark::Fixture { +public: + void SetUp(const ::benchmark::State &state) + {} + void TearDown(const ::benchmark::State &state) + {} +}; + +/** + * @tc.name: VerifyAccessTokenTestCase001 + * @tc.desc: VerifyAccessToken + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(NapiAtmanagerTest, VerifyAccessTokenTestCase001)( + benchmark::State &st) +{ + GTEST_LOG_(INFO) << "NapiAtmanagerTest VerifyAccessTokenTestCase001 start!"; + for (auto _ : st) { + EXPECT_EQ(AccessTokenKit::VerifyAccessToken(TOKENID, BENCHMARK_TEST_PERMISSION_NAME_ALPHA), -1); + } +} + +BENCHMARK_REGISTER_F(NapiAtmanagerTest, VerifyAccessTokenTestCase001)->Iterations(100)-> + Repetitions(3)->ReportAggregatesOnly(); + +/** + * @tc.name: GetPermissionFlagsTestCase002 + * @tc.desc: GetPermissionFlags + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(NapiAtmanagerTest, GetPermissionFlagsTestCase002)( + benchmark::State &st) +{ + GTEST_LOG_(INFO) << "NapiAtmanagerTest GetPermissionFlagsTestCase002 start!"; + for (auto _ : st) { + EXPECT_EQ(AccessTokenKit::GetPermissionFlag(TOKENID, BENCHMARK_TEST_PERMISSION_NAME_ALPHA), 0); + } +} + +BENCHMARK_REGISTER_F(NapiAtmanagerTest, GetPermissionFlagsTestCase002)->Iterations(100)-> + Repetitions(3)->ReportAggregatesOnly(); + +/** + * @tc.name: GetDefPermissionTestCase003 + * @tc.desc: GetDefPermission + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(NapiAtmanagerTest, GetDefPermissionTestCase003)( + benchmark::State &st) +{ + GTEST_LOG_(INFO) << "NapiAtmanagerTest GetDefPermissionTestCase003 start!"; + for (auto _ : st) { + EXPECT_EQ(AccessTokenKit::GetDefPermission(BENCHMARK_TEST_PERMISSION_NAME_ALPHA, PERMISSIONDEF), -1); + } +} + +BENCHMARK_REGISTER_F(NapiAtmanagerTest, GetDefPermissionTestCase003)->Iterations(100)-> + Repetitions(3)->ReportAggregatesOnly(); + +/** + * @tc.name: RevokeUserGrantedPermissionTestCase004 + * @tc.desc: RevokeUserGrantedPermission + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(NapiAtmanagerTest, RevokeUserGrantedPermissionTestCase004)( + benchmark::State &st) +{ + GTEST_LOG_(INFO) << "NapiAtmanagerTest RevokeUserGrantedPermissionTestCase004 start!"; + for (auto _ : st) { + EXPECT_EQ(AccessTokenKit::RevokePermission(TOKENID, BENCHMARK_TEST_PERMISSION_NAME_ALPHA, 0), -1); + } +} + +BENCHMARK_REGISTER_F(NapiAtmanagerTest, RevokeUserGrantedPermissionTestCase004)->Iterations(100)-> + Repetitions(3)->ReportAggregatesOnly(); + +/** + * @tc.name: GrantPermissionTestCase005 + * @tc.desc: GrantPermission + * @tc.type: FUNC + * @tc.require: + */ +BENCHMARK_F(NapiAtmanagerTest, GrantPermissionTestCase005)( + benchmark::State &st) +{ + GTEST_LOG_(INFO) << "NapiAtmanagerTest GrantPermissionTestCase005 start!"; + for (auto _ : st) { + EXPECT_EQ(AccessTokenKit::GrantPermission(TOKENID, BENCHMARK_TEST_PERMISSION_NAME_ALPHA, 0), -1); + } +} + +BENCHMARK_REGISTER_F(NapiAtmanagerTest, GrantPermissionTestCase005)->Iterations(100)-> + Repetitions(3)->ReportAggregatesOnly(); +} // namespace + +BENCHMARK_MAIN(); \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/kits/common/BUILD.gn b/security_access_token-yl_0822/interfaces/kits/common/BUILD.gn new file mode 100644 index 000000000..7e98c3eea --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/common/BUILD.gn @@ -0,0 +1,33 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_static_library("libnapi_common") { + include_dirs = [ + "include", + "//base/security/access_token/frameworks/common/include", + "//foundation/arkui/napi/interfaces/inner_api", + "//foundation/arkui/napi/interfaces/kits", + ] + + sources = [ "src/napi_common.cpp" ] + + deps = [ "//foundation/arkui/napi:ace_napi" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + subsystem_name = "security" + part_name = "access_token" + output_name = "libnativetoken" +} diff --git a/security_access_token-yl_0822/interfaces/kits/common/include/napi_common.h b/security_access_token-yl_0822/interfaces/kits/common/include/napi_common.h new file mode 100644 index 000000000..22c776293 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/common/include/napi_common.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_PRIVACY_KITS_NAPI_COMMON_H +#define INTERFACES_PRIVACY_KITS_NAPI_COMMON_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const int ARGS_TWO = 2; +const int ARGS_THREE = 3; +const int ARGS_FIVE = 5; +const int ASYNC_CALL_BACK_VALUES_NUM = 2; +const int PARAM0 = 0; +const int PARAM1 = 1; +const int PARAM2 = 2; +const int PARAM3 = 3; + +bool ParseBool(const napi_env env, const napi_value value); +int32_t ParseInt32(const napi_env env, const napi_value value); +int64_t ParseInt64(const napi_env env, const napi_value value); +uint32_t ParseUint32(const napi_env env, const napi_value value); +std::string ParseString(const napi_env env, const napi_value value); +std::vector ParseStringArray(const napi_env env, const napi_value value); +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_PRIVACY_KITS_NAPI_COMMON_H */ + diff --git a/security_access_token-yl_0822/interfaces/kits/common/src/napi_common.cpp b/security_access_token-yl_0822/interfaces/kits/common/src/napi_common.cpp new file mode 100644 index 000000000..28c487953 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/common/src/napi_common.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "napi_common.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PRIVACY, "CommonNapi"}; +} // namespace + +static bool inline Check(const napi_env env, const napi_value value, const napi_valuetype type) +{ + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, value, &valuetype); + if (valuetype != type) { + ACCESSTOKEN_LOG_ERROR(LABEL, "value type dismatch"); + return false; + } + return true; +} + +bool ParseBool(const napi_env env, const napi_value value) +{ + if (!Check(env, value, napi_boolean)) { + return 0; + } + bool result = 0; + if (napi_get_value_bool(env, value, &result) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get value bool"); + return 0; + } + return result; +} + +int32_t ParseInt32(const napi_env env, const napi_value value) +{ + if (!Check(env, value, napi_number)) { + return 0; + } + int32_t result = 0; + if (napi_get_value_int32(env, value, &result) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get value int32"); + return 0; + } + return result; +} + +int64_t ParseInt64(const napi_env env, const napi_value value) +{ + if (!Check(env, value, napi_number)) { + return 0; + } + int64_t result = 0; + if (napi_get_value_int64(env, value, &result) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get value int64"); + return 0; + } + return result; +} + +uint32_t ParseUint32(const napi_env env, const napi_value value) +{ + if (!Check(env, value, napi_number)) { + return 0; + } + uint32_t result = 0; + if (napi_get_value_uint32(env, value, &result) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get value uint32"); + return 0; + } + return result; +} + +std::string ParseString(const napi_env env, const napi_value value) +{ + if (!Check(env, value, napi_string)) { + return ""; + } + size_t size; + + if (napi_get_value_string_utf8(env, value, nullptr, 0, &size) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get string size"); + return ""; + } + std::string str; + str.reserve(size + 1); + str.resize(size); + if (napi_get_value_string_utf8(env, value, str.data(), size + 1, &size) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get string value"); + return ""; + } + return str; +} + +std::vector ParseStringArray(const napi_env env, const napi_value value) +{ + std::vector res; + uint32_t length = 0; + napi_valuetype valuetype = napi_undefined; + + napi_get_array_length(env, value, &length); + napi_value valueArray; + for (uint32_t i = 0; i < length; i++) { + napi_get_element(env, value, i, &valueArray); + + napi_typeof(env, valueArray, &valuetype); + if (valuetype == napi_string) { + res.emplace_back(ParseString(env, valueArray)); + } + } + return res; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/BUILD.gn b/security_access_token-yl_0822/interfaces/kits/privacy/BUILD.gn new file mode 100644 index 000000000..fb369bd60 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("libprivacymanager") { + include_dirs = [ + "napi/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/interfaces/kits/common/include", + "//foundation/arkui/napi/interfaces/inner_api", + "//foundation/arkui/napi/interfaces/kits", + "//commonlibrary/c_utils/base/include", + ] + + sources = [ + "napi/src/napi_context_common.cpp", + "napi/src/native_module.cpp", + "napi/src/permission_record_manager_napi.cpp", + ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + "//base/security/access_token/interfaces/kits/common:libnapi_common", + "//foundation/arkui/napi:ace_napi", + ] + cflags_cc = [ "-DHILOG_ENABLE" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "security" + part_name = "access_token" +} diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/napi_context_common.h b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/napi_context_common.h new file mode 100644 index 000000000..2cf08dbf8 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/napi_context_common.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_PRIVACY_KITS_NAPI_CONTEXT_COMMON_H +#define INTERFACES_PRIVACY_KITS_NAPI_CONTEXT_COMMON_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PrivacyAsyncWorkData { + explicit PrivacyAsyncWorkData(napi_env env); + virtual ~PrivacyAsyncWorkData(); + + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_PRIVACY_KITS_NAPI_CONTEXT_COMMON_H */ diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/native_module.h b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/native_module.h new file mode 100644 index 000000000..0e6d833bc --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/native_module.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_PRIVACY_KITS_NATIVE_MODULE_H +#define INTERFACES_PRIVACY_KITS_NATIVE_MODULE_H + +#include +#include +#include +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports); +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_PRIVACY_KITS_NATIVE_MODULE_H */ diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/permission_record_manager_napi.h b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/permission_record_manager_napi.h new file mode 100644 index 000000000..fbe729de1 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/include/permission_record_manager_napi.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_KITS_PERMISSION_USED_MANAGER_NAPI_H +#define INTERFACES_KITS_PERMISSION_USED_MANAGER_NAPI_H + +#include + +#include "access_token.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_context_common.h" +#include "napi_common.h" +#include "permission_used_request.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct RecordManagerAsyncContext : public PrivacyAsyncWorkData { + explicit RecordManagerAsyncContext(napi_env env) : PrivacyAsyncWorkData(env) {} + + AccessTokenID tokenId = 0; + std::string permissionName; + int32_t successCount = 0; + int32_t failCount = 0; + PermissionUsedRequest request; + PermissionUsedResult result; + int32_t retCode = -1; +}; + +napi_value AddPermissionUsedRecord(napi_env env, napi_callback_info cbinfo); +napi_value StartUsingPermission(napi_env env, napi_callback_info cbinfo); +napi_value StopUsingPermission(napi_env env, napi_callback_info cbinfo); +napi_value GetPermissionUsedRecords(napi_env env, napi_callback_info cbinfo); +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_KITS_PERMISSION_USED_MANAGER_NAPI_H */ diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/napi_context_common.cpp b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/napi_context_common.cpp new file mode 100644 index 000000000..b36467c88 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/napi_context_common.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "napi_context_common.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +PrivacyAsyncWorkData::PrivacyAsyncWorkData(napi_env envValue) +{ + env = envValue; +} + +PrivacyAsyncWorkData::~PrivacyAsyncWorkData() +{ + if (callbackRef) { + napi_delete_reference(env, callbackRef); + callbackRef = nullptr; + } + + if (asyncWork) { + napi_delete_async_work(env, asyncWork); + asyncWork = nullptr; + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/native_module.cpp b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/native_module.cpp new file mode 100644 index 000000000..a5f2e7d70 --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/native_module.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "native_module.h" +#include "permission_record_manager_napi.h" +#include "permission_used_request.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor descriptor[] = { + DECLARE_NAPI_FUNCTION("addPermissionUsedRecord", AddPermissionUsedRecord), + DECLARE_NAPI_FUNCTION("startUsingPermission", StartUsingPermission), + DECLARE_NAPI_FUNCTION("stopUsingPermission", StopUsingPermission), + DECLARE_NAPI_FUNCTION("getPermissionUsedRecords", GetPermissionUsedRecords) + }; + + napi_define_properties(env, exports, sizeof(descriptor) / sizeof(descriptor[0]), descriptor); + + napi_value permissionUsageFlag = nullptr; + napi_create_object(env, &permissionUsageFlag); + + napi_value prop = nullptr; + napi_create_int32(env, FLAG_PERMISSION_USAGE_SUMMARY, &prop); + napi_set_named_property(env, permissionUsageFlag, "FLAG_PERMISSION_USAGE_SUMMARY", prop); + + prop = nullptr; + napi_create_int32(env, FLAG_PERMISSION_USAGE_DETAIL, &prop); + napi_set_named_property(env, permissionUsageFlag, "FLAG_PERMISSION_USAGE_DETAIL", prop); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("PermissionUsageFlag ", permissionUsageFlag), + }; + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(exportFuncs[0]), exportFuncs); + + return exports; +} +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "privacyManager", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterPrivacyModule(void) +{ + napi_module_register(&_module); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/permission_record_manager_napi.cpp b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/permission_record_manager_napi.cpp new file mode 100644 index 000000000..7798f1e7b --- /dev/null +++ b/security_access_token-yl_0822/interfaces/kits/privacy/napi/src/permission_record_manager_napi.cpp @@ -0,0 +1,553 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "permission_record_manager_napi.h" + +#include "privacy_kit.h" +#include "accesstoken_log.h" +#include "napi_context_common.h" +#include "napi_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordManagerNapi"}; +} // namespace +static void ParseAddPermissionRecord( + const napi_env env, const napi_callback_info info, RecordManagerAsyncContext& asyncContext) +{ + size_t argc = ARGS_FIVE; + napi_value argv[ARGS_FIVE] = { 0 }; + napi_value thisVar = nullptr; + void* data = nullptr; + + NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + asyncContext.env = env; + asyncContext.tokenId = ParseUint32(env, argv[PARAM0]); + asyncContext.permissionName = ParseString(env, argv[PARAM1]); + asyncContext.successCount = ParseInt32(env, argv[PARAM2]); + asyncContext.failCount = ParseInt32(env, argv[PARAM3]); + if (argc == ARGS_FIVE) { + napi_valuetype valueType = napi_undefined; + NAPI_CALL_RETURN_VOID(env, napi_typeof(env, argv[ARGS_FIVE - 1], &valueType)); + if (valueType == napi_function) { + NAPI_CALL_RETURN_VOID(env, + napi_create_reference(env, argv[ARGS_FIVE - 1], 1, &asyncContext.callbackRef)); + } + } +} + +static void ParseStartAndStopUsingPermission( + const napi_env env, const napi_callback_info info, RecordManagerAsyncContext& asyncContext) +{ + size_t argc = ARGS_THREE; + napi_value argv[ARGS_THREE] = { 0 }; + napi_value thisVar = nullptr; + void* data = nullptr; + + NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + + asyncContext.env = env; + asyncContext.tokenId = ParseUint32(env, argv[PARAM0]); + asyncContext.permissionName = ParseString(env, argv[PARAM1]); + if (argc == ARGS_THREE) { + napi_valuetype valueType = napi_undefined; + NAPI_CALL_RETURN_VOID(env, napi_typeof(env, argv[ARGS_THREE - 1], &valueType)) ; + if (valueType == napi_function) { + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, + argv[ARGS_THREE - 1], 1, &asyncContext.callbackRef)); + } + } +} + +static void ConvertDetailUsedRecord(napi_env env, napi_value value, const UsedRecordDetail& detailRecord) +{ + napi_value nStatus; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, detailRecord.status, &nStatus)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "status", nStatus)); + + napi_value nTimestamp; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, detailRecord.timestamp, &nTimestamp)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "timestamp", nTimestamp)); + + napi_value nAccessDuration; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, detailRecord.accessDuration, &nAccessDuration)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "accessDuration", nAccessDuration)); +} + +static void ConvertPermissionUsedRecord(napi_env env, napi_value value, const PermissionUsedRecord& permissionRecord) +{ + napi_value nPermissionName; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, + permissionRecord.permissionName.c_str(), NAPI_AUTO_LENGTH, &nPermissionName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "permissionName", nPermissionName)); + + napi_value nAccessCount; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, permissionRecord.accessCount, &nAccessCount)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "accessCount", nAccessCount)); + + napi_value nRejectCount; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, permissionRecord.rejectCount, &nRejectCount)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "rejectCount", nRejectCount)); + + napi_value nLastAccessTime; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, permissionRecord.lastAccessTime, &nLastAccessTime)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "lastAccessTime", nLastAccessTime)); + + napi_value nLastRejectTime; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, permissionRecord.lastRejectTime, &nLastRejectTime)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "lastRejectTime", nLastRejectTime)); + + napi_value nLastAccessDuration; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, permissionRecord.lastAccessDuration, &nLastAccessDuration)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "lastAccessDuration", nLastAccessDuration)); + + size_t index = 0; + napi_value objAccessRecords; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &objAccessRecords)); + for (const auto& accRecord : permissionRecord.accessRecords) { + napi_value objAccessRecord; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAccessRecord)); + ConvertDetailUsedRecord(env, objAccessRecord, accRecord); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objAccessRecords, index, objAccessRecord)); + index++; + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "accessRecords", objAccessRecords)); + + index = 0; + napi_value objRejectRecords; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &objRejectRecords)); + for (const auto& rejRecord : permissionRecord.rejectRecords) { + napi_value objRejectRecord; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objRejectRecord)); + ConvertDetailUsedRecord(env, objRejectRecord, rejRecord); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objRejectRecords, index, objRejectRecord)); + index++; + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "rejectRecords", objRejectRecords)); +} + +static void ConvertBundleUsedRecord(napi_env env, napi_value value, const BundleUsedRecord& bundleRecord) +{ + napi_value nTokenId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleRecord.tokenId, &nTokenId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "tokenId", nTokenId)); + + napi_value nIsRemote; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, bundleRecord.isRemote, &nIsRemote)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "isRemote", nIsRemote)); + + napi_value nDeviceId; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, + bundleRecord.deviceId.c_str(), NAPI_AUTO_LENGTH, &nDeviceId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "deviceId", nDeviceId)); + + napi_value nBundleName; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, + bundleRecord.bundleName.c_str(), NAPI_AUTO_LENGTH, &nBundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "bundleName", nBundleName)); + size_t index = 0; + napi_value objPermissionRecords; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &objPermissionRecords)); + for (const auto& permRecord : bundleRecord.permissionRecords) { + napi_value objPermissionRecord; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objPermissionRecord)); + ConvertPermissionUsedRecord(env, objPermissionRecord, permRecord); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objPermissionRecords, index, objPermissionRecord)); + index++; + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "permissionRecords", objPermissionRecords)); +} + +static void ProcessRecordResult(napi_env env, napi_value value, const PermissionUsedResult& result) +{ + napi_value nBeginTimestamp; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, result.beginTimeMillis, &nBeginTimestamp)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "beginTime", nBeginTimestamp)); + + napi_value nEndTimestamp; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, result.endTimeMillis, &nEndTimestamp)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "endTime", nEndTimestamp)); + + size_t index = 0; + napi_value objBundleRecords; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &objBundleRecords)); + for (const auto& bundleRecord : result.bundleRecords) { + napi_value objBundleRecord; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objBundleRecord)); + ConvertBundleUsedRecord(env, objBundleRecord, bundleRecord); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objBundleRecords, index, objBundleRecord)); + index++; + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "bundleRecords", objBundleRecords)); +} + +static void ParseGetPermissionUsedRecords( + const napi_env env, const napi_callback_info info, RecordManagerAsyncContext& asyncContext) +{ + size_t argc = ARGS_TWO; + napi_value argv[ARGS_TWO] = { 0 }; + napi_value thisVar = nullptr; + void* data = nullptr; + napi_valuetype valuetype = napi_undefined; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + napi_typeof(env, argv[PARAM0], &valuetype); + if (valuetype != napi_object) { + return; + } + napi_value property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "tokenId", &property)); + asyncContext.request.tokenId = ParseUint32(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "isRemote", &property)) ; + asyncContext.request.isRemote = ParseBool(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "deviceId", &property)); + asyncContext.request.deviceId = ParseString(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "bundleName", &property)); + asyncContext.request.bundleName = ParseString(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "beginTime", &property)); + asyncContext.request.beginTimeMillis = ParseInt64(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "endTime", &property)); + asyncContext.request.endTimeMillis = ParseInt64(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "permissionNames", &property)); + asyncContext.request.permissionList = ParseStringArray(env, property); + + property = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_named_property(env, argv[PARAM0], "flag", &property)); + asyncContext.request.flag = (PermissionUsageFlagEnum)ParseInt32(env, property); + + asyncContext.env = env; + if (argc == ARGS_TWO) { + NAPI_CALL_RETURN_VOID(env, napi_typeof(env, argv[ARGS_TWO - 1], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, argv[ARGS_TWO - 1], 1, &asyncContext.callbackRef)); + } + } +} + +static void AddPermissionUsedRecordExecute(napi_env env, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddPermissionUsedRecord execute."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + asyncContext->retCode = PrivacyKit::AddPermissionUsedRecord(asyncContext->tokenId, + asyncContext->permissionName, asyncContext->successCount, asyncContext->failCount); +} + +static void AddPermissionUsedRecordComplete(napi_env env, napi_status status, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddPermissionUsedRecord complete."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + std::unique_ptr callbackPtr {asyncContext}; + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; + + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, + asyncContext->retCode, &results[PARAM1])); + if (asyncContext->deferred) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncContext->deferred, + results[PARAM1])); + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_value undefine = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefine)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncContext->callbackRef, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefine, callback, ASYNC_CALL_BACK_VALUES_NUM, + results, &callResult)); + } +} + +napi_value AddPermissionUsedRecord(napi_env env, napi_callback_info cbinfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddPermissionUsedRecord begin."); + + auto *asyncContext = new (std::nothrow) RecordManagerAsyncContext(env); + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + std::unique_ptr callbackPtr {asyncContext}; + ParseAddPermissionRecord(env, cbinfo, *asyncContext); + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &(asyncContext->deferred), &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "AddPermissionUsedRecord", NAPI_AUTO_LENGTH, &resource)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resource, + AddPermissionUsedRecordExecute, + AddPermissionUsedRecordComplete, + reinterpret_cast(asyncContext), + &(asyncContext->asyncWork))); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->asyncWork)); + callbackPtr.release(); + return result; +} + +static void StartUsingPermissionExecute(napi_env env, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StartUsingPermission execute."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + asyncContext->retCode = PrivacyKit::StartUsingPermission(asyncContext->tokenId, + asyncContext->permissionName); +} + +static void StartUsingPermissionComplete(napi_env env, napi_status status, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StartUsingPermission complete."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + std::unique_ptr callbackPtr {asyncContext}; + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; + + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncContext->retCode, + &results[PARAM1])); + if (asyncContext->deferred) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncContext->deferred, + results[PARAM1])); + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_value undefine = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefine)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncContext->callbackRef, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefine, callback, ASYNC_CALL_BACK_VALUES_NUM, + results, &callResult)); + } +} + +napi_value StartUsingPermission(napi_env env, napi_callback_info cbinfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StartUsingPermission begin."); + + auto *asyncContext = new (std::nothrow) RecordManagerAsyncContext(env); + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + std::unique_ptr callbackPtr {asyncContext}; + ParseStartAndStopUsingPermission(env, cbinfo, *asyncContext); + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &(asyncContext->deferred), &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "StartUsingPermission", NAPI_AUTO_LENGTH, &resource)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resource, + StartUsingPermissionExecute, + StartUsingPermissionComplete, + reinterpret_cast(asyncContext), + &(asyncContext->asyncWork))); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->asyncWork)); + callbackPtr.release(); + return result; +} + +static void StopUsingPermissionExecute(napi_env env, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StopUsingPermission execute."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + asyncContext->retCode = PrivacyKit::StopUsingPermission(asyncContext->tokenId, + asyncContext->permissionName); +} + +static void StopUsingPermissionComplete(napi_env env, napi_status status, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StopUsingPermission complete."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + std::unique_ptr callbackPtr {asyncContext}; + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; + + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncContext->retCode, + &results[PARAM1])); + if (asyncContext->deferred) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncContext->deferred, + results[PARAM1])); + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_value undefine = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefine)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncContext->callbackRef, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefine, callback, ASYNC_CALL_BACK_VALUES_NUM, + results, &callResult)); + } +} + +napi_value StopUsingPermission(napi_env env, napi_callback_info cbinfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "StopUsingPermission begin."); + + auto *asyncContext = new (std::nothrow) RecordManagerAsyncContext(env); + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + std::unique_ptr callbackPtr {asyncContext}; + ParseStartAndStopUsingPermission(env, cbinfo, *asyncContext); + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &(asyncContext->deferred), &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "StopUsingPermission", NAPI_AUTO_LENGTH, &resource)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resource, + StopUsingPermissionExecute, + StopUsingPermissionComplete, + reinterpret_cast(asyncContext), + &(asyncContext->asyncWork))); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->asyncWork)); + callbackPtr.release(); + return result; +} + +static void GetPermissionUsedRecordsExecute(napi_env env, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetPermissionUsedRecords execute."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + asyncContext->retCode = PrivacyKit::GetPermissionUsedRecords(asyncContext->request, asyncContext->result); +} + +static void GetPermissionUsedRecordsComplete(napi_env env, napi_status status, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetPermissionUsedRecords complete."); + RecordManagerAsyncContext* asyncContext = reinterpret_cast(data); + if (asyncContext == nullptr) { + return; + } + + std::unique_ptr callbackPtr {asyncContext}; + napi_value results[ASYNC_CALL_BACK_VALUES_NUM] = {nullptr}; + + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncContext->retCode, &results[0])); + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &results[PARAM1])); + ProcessRecordResult(env, results[PARAM1], asyncContext->result); + if (asyncContext->deferred) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncContext->deferred, + results[PARAM1])); + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_value undefine = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefine)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &callResult)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncContext->callbackRef, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefine, callback, ASYNC_CALL_BACK_VALUES_NUM, + results, &callResult)); + } +} + +napi_value GetPermissionUsedRecords(napi_env env, napi_callback_info cbinfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetPermissionUsedRecords begin."); + auto *asyncContext = new (std::nothrow) RecordManagerAsyncContext(env); + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "new struct fail."); + return nullptr; + } + + std::unique_ptr callbackPtr {asyncContext}; + ParseGetPermissionUsedRecords(env, cbinfo, *asyncContext); + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &(asyncContext->deferred), &result)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &result)); + } + + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "GetPermissionUsedRecords", NAPI_AUTO_LENGTH, &resource)); + + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resource, + GetPermissionUsedRecordsExecute, + GetPermissionUsedRecordsComplete, + reinterpret_cast(asyncContext), + &(asyncContext->asyncWork))); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->asyncWork)); + callbackPtr.release(); + return result; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/ohos.build b/security_access_token-yl_0822/ohos.build new file mode 100644 index 000000000..9bb34ca00 --- /dev/null +++ b/security_access_token-yl_0822/ohos.build @@ -0,0 +1,61 @@ +{ + "subsystem": "security", + "parts": { + "access_token": { + "variants": [ + "phone", + "wearable" + ], + "inner_kits": [ + { + "name": "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "header": { + "header_files": [ + "accesstoken_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/accesstoken/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "header": { + "header_files": [ + "nativetoken_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/nativetoken/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + "header": { + "header_files": [ + "token_setproc.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/token_setproc/include" + } + }, + { + "name": "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + "header": { + "header_files": [ + "privacy_kit.h" + ], + "header_base": "//base/security/access_token/interfaces/innerkits/privacy/include" + } + } + ], + "module_list": [ + "//base/security/access_token:accesstoken_build_module", + "//base/security/access_token:tokensync_build_module", + "//base/security/access_token:privacy_build_module" + ], + "test_list": [ + "//base/security/access_token:accesstoken_build_module_test", + "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest", + "//base/security/access_token/interfaces/innerkits/nativetoken/test:unittest", + "//base/security/access_token/interfaces/innerkits/token_setproc/test:unittest", + "//base/security/access_token/interfaces/innerkits/privacy/test:unittest" + ] + } + } +} diff --git a/security_access_token-yl_0822/services/accesstokenmanager/BUILD.gn b/security_access_token-yl_0822/services/accesstokenmanager/BUILD.gn new file mode 100644 index 000000000..116041ae5 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/BUILD.gn @@ -0,0 +1,113 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") + +ohos_prebuilt_etc("access_token.rc") { + source = "access_token.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "access_token" +} + +if (is_standard_system) { + ohos_shared_library("accesstoken_manager_service") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "//third_party/sqlite/include/", + "main/cpp/include/callback", + "main/cpp/include/service", + "main/cpp/include/token", + "main/cpp/include/permission", + "main/cpp/include/database", + "main/cpp/include/device", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/interfaces/innerkits/tokensync/src", + "//base/security/access_token/services/common/database/include", + "//base/security/access_token/services/tokensyncmanager/include/common", + "//third_party/json/include", + ] + + sources = [ + "main/cpp/src/callback/callback_manager.cpp", + "main/cpp/src/callback/perm_state_callback_death_recipient.cpp", + "main/cpp/src/callback/permission_state_change_callback_proxy.cpp", + "main/cpp/src/database/data_storage.cpp", + "main/cpp/src/database/data_translator.cpp", + "main/cpp/src/database/sqlite_storage.cpp", + "main/cpp/src/permission/permission_definition_cache.cpp", + "main/cpp/src/permission/permission_manager.cpp", + "main/cpp/src/permission/permission_policy_set.cpp", + "main/cpp/src/permission/permission_validator.cpp", + "main/cpp/src/service/accesstoken_manager_service.cpp", + "main/cpp/src/service/accesstoken_manager_stub.cpp", + "main/cpp/src/token/accesstoken_id_manager.cpp", + "main/cpp/src/token/accesstoken_info_manager.cpp", + "main/cpp/src/token/hap_token_info_inner.cpp", + "main/cpp/src/token/native_token_info_inner.cpp", + "main/cpp/src/token/native_token_receptor.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + if (dlp_permission_enable == true) { + cflags_cc += [ "-DSUPPORT_SANDBOX_APP" ] + sources += [ + "main/cpp/src/permission/dlp_permission_set_manager.cpp", + "main/cpp/src/permission/dlp_permission_set_parser.cpp", + ] + } + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + "//base/security/access_token/services/accesstokenmanager:access_token.rc", + "//base/security/access_token/services/common/database:accesstoken_database_cxx", + ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + + sources += [ + "main/cpp/src/device/atm_device_state_callback.cpp", + "main/cpp/src/token/accesstoken_remote_token_manager.cpp", + "main/cpp/src/token/token_modify_notifier.cpp", + ] + + include_dirs += [ + "//base/security/access_token/interfaces/innerkits/tokensync/include", + "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", + ] + + deps += [ "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk" ] + external_deps += [ "device_manager:devicemanagersdk" ] + } + } +} diff --git a/security_access_token-yl_0822/services/accesstokenmanager/access_token.cfg b/security_access_token-yl_0822/services/accesstokenmanager/access_token.cfg new file mode 100644 index 000000000..3b139195f --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/access_token.cfg @@ -0,0 +1,20 @@ +{ + "jobs" : [{ + "name" : "pre-init", + "cmds" : [ + "mkdir /data/service/el0/access_token 0750 root access_token", + "load_access_token_id " + ] + } + ], + "services" : [{ + "name" : "accesstoken_service", + "path" : ["/system/bin/sa_main", "/system/profile/accesstoken_service.xml"], + "importance" : -20, + "uid" : "access_token", + "gid" : ["access_token"], + "permission" : ["ohos.permission.DISTRIBUTED_DATASYNC"], + "secon" : "u:r:accesstoken_service:s0" + } + ] +} diff --git a/security_access_token-yl_0822/services/accesstokenmanager/access_token.rc b/security_access_token-yl_0822/services/accesstokenmanager/access_token.rc new file mode 100644 index 000000000..15ff9d773 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/access_token.rc @@ -0,0 +1,22 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +on late-fs + start accesstoken_service + +service accesstoken_service /system/bin/sa_main /system/profile/accesstoken_service.xml + class accesstoken_service + priority -20 + user access_token + group access_token + seclabel u:r:accesstoken_service:s0 diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/callback_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/callback_manager.h new file mode 100644 index 000000000..58530fade --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/callback_manager.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESS_TOKEN_PERMISSION_CALLBACK_MANAGER_H +#define ACCESS_TOKEN_PERMISSION_CALLBACK_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "accesstoken_log.h" +#include "i_permission_state_callback.h" +#include "permission_state_change_info.h" +#include "permission_state_change_callback_proxy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum PermStateChangeType { + REVOKED = 0, + GRANTED = 1, +}; +struct CallbackRecord { + CallbackRecord() : scopePtr_(nullptr), callbackObject_(nullptr) + {} + CallbackRecord(std::shared_ptr callbackScopePtr, sptr callback) + : scopePtr_(callbackScopePtr), callbackObject_(callback) + {} + + std::shared_ptr scopePtr_; + sptr callbackObject_; +}; + +class CallbackManager { +public: + virtual ~CallbackManager(); + CallbackManager(); + static CallbackManager& GetInstance(); + + int32_t AddCallback( + const std::shared_ptr& callbackScopePtr, const sptr& callback); + int32_t RemoveCallback(const sptr& callback); + bool CalledAccordingToTokenIdLlist(const std::vector& tokenIDList, AccessTokenID tokenID); + bool CalledAccordingToPermLlist(const std::vector& permList, const std::string& permName); + void ExecuteCallbackAsync(AccessTokenID tokenID, const std::string& permName, int32_t changeType); + +private: + std::mutex mutex_; + std::vector callbackInfoList_; + sptr callbackDeathRecipient_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKEN_PERMISSION_CALLBACK_MANAGER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/perm_state_callback_death_recipient.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/perm_state_callback_death_recipient.h new file mode 100644 index 000000000..4a4af90b7 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/perm_state_callback_death_recipient.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_STATE_CALLBACK_DEATH_RECIPIENT_H +#define PERM_STATE_CALLBACK_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient { +public: + PermStateCallbackDeathRecipient() = default; + virtual ~PermStateCallbackDeathRecipient() = default; + + virtual void OnRemoteDied(const wptr& remote); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERM_STATE_CALLBACK_DEATH_RECIPIENT_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/permission_state_change_callback_proxy.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/permission_state_change_callback_proxy.h new file mode 100644 index 000000000..0625a24fd --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/callback/permission_state_change_callback_proxy.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H +#define PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H + +#include "i_permission_state_callback.h" + +#include "iremote_proxy.h" +#include "nocopyable.h" +#include "permission_state_change_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionStateChangeCallbackProxy : public IRemoteProxy { +public: + explicit PermissionStateChangeCallbackProxy(const sptr& impl); + ~PermissionStateChangeCallbackProxy() override; + virtual void PermStateChangeCallback(PermStateChangeInfo& result) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_STATE_CHANGE_CALLBACK_PROXY_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_storage.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_storage.h new file mode 100644 index 000000000..0d69fb9dd --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_storage.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_STORAGE_H +#define DATA_STORAGE_H + +#include +#include + +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataStorage { +public: + enum DataType { + ACCESSTOKEN_HAP_INFO, + ACCESSTOKEN_NATIVE_INFO, + ACCESSTOKEN_PERMISSION_DEF, + ACCESSTOKEN_PERMISSION_STATE, + }; + + static DataStorage& GetRealDataStorage(); + + virtual ~DataStorage() = default; + + virtual int Add(const DataType type, const std::vector& values) = 0; + + virtual int Remove(const DataType type, const GenericValues& conditions) = 0; + + virtual int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) = 0; + + virtual int Find(const DataType type, std::vector& results) = 0; + + virtual int RefreshAll(const DataType type, const std::vector& values) = 0; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // DATA_STORAGE_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_translator.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_translator.h new file mode 100644 index 000000000..a731e9b2f --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/data_translator.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_TRANSLATOR_H +#define DATA_TRANSLATOR_H + +#include + +#include "hap_token_info_inner.h" +#include "native_token_info_inner.h" +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataTranslator final { +public: + static int TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues); + static int TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef); + static int TranslationIntoGenericValues(const PermissionStateFull& inPermissionState, + const unsigned int grantIndex, GenericValues& outGenericValues); + static int TranslationIntoPermissionStateFull(const GenericValues& inGenericValues, + PermissionStateFull& outPermissionState); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DATA_TRANSLATOR_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h new file mode 100644 index 000000000..2fea72d2c --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/database/sqlite_storage.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SQLITE_STORAGE_H +#define SQLITE_STORAGE_H + +#include "data_storage.h" +#include "sqlite_helper.h" +#include "field_const.h" + +#include "nocopyable.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SqliteStorage : public DataStorage, public SqliteHelper { +public: + enum ExecuteResult { FAILURE = -1, SUCCESS }; + + struct SqliteTable { + public: + std::string tableName_; + std::vector tableColumnNames_; + }; + + static SqliteStorage& GetInstance(); + + ~SqliteStorage() override; + + int Add(const DataType type, const std::vector& values) override; + + int Remove(const DataType type, const GenericValues& conditions) override; + + int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) override; + + int Find(const DataType type, std::vector& results) override; + + int RefreshAll(const DataType type, const std::vector& values) override; + + void OnCreate() override; + void OnUpdate() override; + +private: + SqliteStorage(); + DISALLOW_COPY_AND_MOVE(SqliteStorage); + + std::map dataTypeToSqlTable_; + OHOS::Utils::RWLock rwLock_; + + int CreateHapTokenInfoTable() const; + int CreateNativeTokenInfoTable() const; + int CreatePermissionDefinitionTable() const; + int CreatePermissionStateTable() const; + + std::string CreateInsertPrepareSqlCmd(const DataType type) const; + std::string CreateDeletePrepareSqlCmd( + const DataType type, const std::vector& columnNames = std::vector()) const; + std::string CreateUpdatePrepareSqlCmd(const DataType type, const std::vector& modifyColumns, + const std::vector& conditionColumns) const; + std::string CreateSelectPrepareSqlCmd(const DataType type) const; + +private: + inline static const std::string HAP_TOKEN_INFO_TABLE = "hap_token_info_table"; + inline static const std::string NATIVE_TOKEN_INFO_TABLE = "native_token_info_table"; + inline static const std::string PERMISSION_DEF_TABLE = "permission_definition_table"; + inline static const std::string PERMISSION_STATE_TABLE = "permission_state_table"; + inline static const std::string DATABASE_NAME = "access_token.db"; + inline static const std::string DATABASE_PATH = "/data/service/el1/public/access_token/"; + static const int DATABASE_VERSION = 1; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // SQLITE_STORAGE_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/device/atm_device_state_callback.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/device/atm_device_state_callback.h new file mode 100644 index 000000000..dbc45fa31 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/device/atm_device_state_callback.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ATM_DEVICE_STATE_CALLBACK_H +#define ATM_DEVICE_STATE_CALLBACK_H + +#include "device_manager_callback.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AtmDmInitCallback final : public DistributedHardware::DmInitCallback { + void OnRemoteDied() override + {} +}; + +class AtmDeviceStateCallback final : public DistributedHardware::DeviceStateCallback { +public: + AtmDeviceStateCallback(); + ~AtmDeviceStateCallback(); + + void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceReady(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ATM_DEVICE_STATE_CALLBACK_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_manager.h new file mode 100644 index 000000000..c0db14d53 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_manager.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_DLP_PERMISSION_SET_MANAGER_H +#define ACCESSTOKEN_DLP_PERMISSION_SET_MANAGER_H + +#include +#include + +#include "nocopyable.h" +#include "permission_dlp_mode.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DlpPermissionSetManager final { +public: + static DlpPermissionSetManager& GetInstance(); + virtual ~DlpPermissionSetManager(); + + int32_t UpdatePermStateWithDlpInfo(int32_t dlpType, std::vector& permStateList); + bool IsPermStateNeedUpdate(int32_t dlpType, int32_t dlpMode); + void ProcessDlpPermInfos(const std::vector& info); + int32_t GetPermDlpMode(const std::string& permissionName); + +private: + DlpPermissionSetManager(); + DISALLOW_COPY_AND_MOVE(DlpPermissionSetManager); + void ProcessDlpPermsInfos(std::vector& dlpPerms); + + /** + * key: the permission name. + * value: the mode of permission. + */ + std::map dlpPermissionModeMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_DLP_PERMISSION_SET_MANAGER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_parser.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_parser.h new file mode 100644 index 000000000..67b9e12be --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/dlp_permission_set_parser.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_DLP_PERMISSION_SET_PARSER_H +#define ACCESSTOKEN_DLP_PERMISSION_SET_PARSER_H + +#include +#include + +#include "permission_dlp_mode.h" +#include "nlohmann/json.hpp" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string CLONE_PERMISSION_CONFIG_FILE = "/system/etc/dlp_permission/clone_app_permission.json"; +constexpr int32_t MAX_CLONE_PERMISSION_CONFIG_FILE_SIZE = 5 * 1024 * 1024; +constexpr size_t MAX_BUFFER_SIZE = 1024; +class DlpPermissionSetParser final { +public: + static DlpPermissionSetParser& GetInstance(); + virtual ~DlpPermissionSetParser() = default; + int32_t Init(); + +private: + DlpPermissionSetParser() : ready_(false) {} + DISALLOW_COPY_AND_MOVE(DlpPermissionSetParser); + int ReadCfgFile(std::string& dlpPermsRawData); + void FromJson(const nlohmann::json& jsonObject, std::vector& dlpPerms); + int32_t ParserDlpPermsRawData(const std::string& dlpPermsRawData, + std::vector& dlpPerms); + void from_json(const nlohmann::json& j, PermissionDlpMode& p); + void ProcessDlpPermsInfos(std::vector& dlpPerms); + + bool ready_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_DLP_PERMISSION_SET_PARSER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h new file mode 100644 index 000000000..d3f923e74 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_definition_cache.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_DEFINITION_CACHE_H +#define PERMISSION_DEFINITION_CACHE_H + +#include +#include + +#include "data_translator.h" +#include "permission_def.h" + +#include "rwlock.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionDefinitionCache final { +public: + static PermissionDefinitionCache& GetInstance(); + + virtual ~PermissionDefinitionCache(); + + bool Insert(const PermissionDef& info, AccessTokenID tokenId); + + bool Update(const PermissionDef& info); + + void DeleteByBundleName(const std::string& bundleName); + + int FindByPermissionName(const std::string& permissionName, PermissionDef& info); + + bool IsSystemGrantedPermission(const std::string& permissionName); + + bool IsUserGrantedPermission(const std::string& permissionName); + + bool HasDefinition(const std::string& permissionName); + + bool IsPermissionDefEmpty(); + + void StorePermissionDef(std::vector& valueList); + + void GetDefPermissionsByTokenId(std::vector& permList, AccessTokenID tokenId); + + int32_t RestorePermDefInfo(std::vector& permDefRes); + +private: + PermissionDefinitionCache(); + + bool IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const; + + DISALLOW_COPY_AND_MOVE(PermissionDefinitionCache); + + /** + * key: the permission name. + * value: the object of PermissionDefData. + */ + std::map permissionDefinitionMap_; + + OHOS::Utils::RWLock cacheLock_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_DEFINITION_CACHE_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h new file mode 100644 index 000000000..30f6d542a --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_MANAGER_H +#define PERMISSION_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "hap_token_info_inner.h" +#include "iremote_broker.h" +#include "permission_def.h" +#include "permission_list_state.h" +#include "permission_state_change_info.h" +#include "permission_state_full.h" + +#include "rwlock.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionManager final { +public: + static PermissionManager& GetInstance(); + virtual ~PermissionManager(); + + void AddDefPermissions(const std::vector& permList, AccessTokenID tokenId, + bool updateFlag); + void RemoveDefPermissions(AccessTokenID tokenID); + int VerifyNativeAccessToken(AccessTokenID tokenID, const std::string& permissionName); + int VerifyHapAccessToken(AccessTokenID tokenID, const std::string& permissionName); + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName); + int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName); + int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult); + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList); + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant); + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName); + void GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + void RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); + void ClearUserGrantedPermissionState(AccessTokenID tokenID); + void GetSelfPermissionState( + std::vector permsList, PermissionListState &permState); + int32_t AddPermStateChangeCallback( + const PermStateChangeScope& scope, const sptr& callback); + int32_t RemovePermStateChangeCallback(const sptr& callback); + +private: + PermissionManager(); + void UpdateTokenPermissionState( + AccessTokenID tokenID, const std::string& permissionName, bool isGranted, int flag); + std::string TransferPermissionDefToString(const PermissionDef& inPermissionDef); + + DISALLOW_COPY_AND_MOVE(PermissionManager); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_MANAGER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h new file mode 100644 index 000000000..d18e301a1 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_POLICY_SET_H +#define PERMISSION_POLICY_SET_H + +#include +#include +#include + +#include "access_token.h" +#include "generic_values.h" +#include "permission_def.h" +#include "permission_state_full.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionPolicySet final { +public: + PermissionPolicySet() : tokenId_(0) {} + virtual ~PermissionPolicySet(); + + static std::shared_ptr BuildPermissionPolicySet(AccessTokenID tokenId, + const std::vector& permStateList); + static std::shared_ptr RestorePermissionPolicy(AccessTokenID tokenId, + const std::vector& permStateRes); + void StorePermissionPolicySet(std::vector& permStateValueList); + void Update(const std::vector& permStateList); + + int VerifyPermissStatus(const std::string& permissionName); + void GetDefPermissions(std::vector& permList); + void GetPermissionStateFulls(std::vector& permList); + int QueryPermissionFlag(const std::string& permissionName); + bool UpdatePermissionStatus(const std::string& permissionName, bool isGranted, uint32_t flag); + void ToString(std::string& info); + bool IsPermissionReqValid(int32_t tokenApl, const std::string& permissionName, + const std::vector& nativeAcls); + void PermStateToString(int32_t tokenApl, const std::vector& nativeAcls, std::string& info); + void GetPermissionStateList(std::vector& stateList); + void ResetUserGrantPermissionStatus(void); + +private: + static void MergePermissionStateFull(std::vector& permStateList, + const PermissionStateFull& state); + void UpdatePermStateFull(const PermissionStateFull& permOld, PermissionStateFull& permNew); + void StorePermissionDef(std::vector& valueList) const; + void StorePermissionState(std::vector& valueList) const; + void PermDefToString(const PermissionDef& def, std::string& info) const; + void PermStateFullToString(const PermissionStateFull& state, std::string& info) const; + + OHOS::Utils::RWLock permPolicySetLock_; + std::vector permStateList_; + AccessTokenID tokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_POLICY_SET_H + diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h new file mode 100644 index 000000000..bdf5e2b04 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/permission/permission_validator.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_VALIDATOR_H +#define PERMISSION_VALIDATOR_H +#include "permission_def.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionValidator final { +public: + PermissionValidator() {} + ~PermissionValidator() {} + + static bool IsPermissionNameValid(const std::string& permissionName); + static bool IsPermissionFlagValid(int flag); + static bool IsPermissionDefValid(const PermissionDef& permDef); + static bool IsPermissionStateValid(const PermissionStateFull& permState); + static void FilterInvalidPermissionDef( + const std::vector& permList, std::vector& result); + static void FilterInvalidPermissionState( + const std::vector& permList, std::vector& result); + static bool IsGrantModeValid(int grantMode); + static bool IsGrantStatusValid(int grantStaus); +private: + static void DeduplicateResDevID(const PermissionStateFull& permState, PermissionStateFull& result); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_VALIDATOR_H + diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h new file mode 100644 index 000000000..2b46210f1 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_SERVICE_H +#define ACCESSTOKEN_MANAGER_SERVICE_H + +#include +#include +#include + +#include "accesstoken_manager_stub.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "singleton.h" +#include "system_ability.h" +#include "hap_token_info.h" +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class AccessTokenManagerService final : public SystemAbility, public AccessTokenManagerStub { + DECLARE_DELAYED_SINGLETON(AccessTokenManagerService); + DECLEAR_SYSTEM_ABILITY(AccessTokenManagerService); + +public: + void OnStart() override; + void OnStop() override; + + AccessTokenIDEx AllocHapToken(const HapInfoParcel& info, const HapPolicyParcel& policy) override; + int VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) override; + int VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) override; + int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override; + int GetDefPermissions(AccessTokenID tokenID, std::vector& permList) override; + int GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) override; + PermissionOper GetSelfPermissionsState( + std::vector& reqPermList) override; + int GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) override; + int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) override; + int ClearUserGrantedPermissionState(AccessTokenID tokenID) override; + int DeleteToken(AccessTokenID tokenID) override; + int GetTokenType(AccessTokenID tokenID) override; + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) override; + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex) override; + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) override; + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& InfoParcel) override; + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) override; + int UpdateHapToken(AccessTokenID tokenID, + const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyParcel) override; + int32_t RegisterPermStateChangeCallback( + const PermStateChangeScopeParcel& scope, const sptr& callback) override; + int32_t UnRegisterPermStateChangeCallback(const sptr& callback) override; + +#ifdef TOKEN_SYNC_ENABLE + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) override; + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoForSyncParcel) override; + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteDeviceTokens(const std::string& deviceID) override; + void CreateDeviceListenner(); + void DestroyDeviceListenner(); +#endif + + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) override; + +private: + bool Initialize(); + + ServiceRunningState state_; + std::mutex mutex_; + bool isListened_ = false; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_SERVICE_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h new file mode 100644 index 000000000..cbc45c2be --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_MANAGER_STUB_H +#define ACCESSTOKEN_MANAGER_STUB_H + +#include "i_accesstoken_manager.h" + +#include + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenManagerStub : public IRemoteStub { +public: + AccessTokenManagerStub(); + virtual ~AccessTokenManagerStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override; + +private: + void VerifyAccessTokenInner(MessageParcel& data, MessageParcel& reply); + void VerifyNativeTokenInner(MessageParcel& data, MessageParcel& reply); + void GetDefPermissionInner(MessageParcel& data, MessageParcel& reply); + void GetDefPermissionsInner(MessageParcel& data, MessageParcel& reply); + void GetReqPermissionsInner(MessageParcel& data, MessageParcel& reply); + void GetSelfPermissionsStateInner(MessageParcel& data, MessageParcel& reply); + void GetPermissionFlagInner(MessageParcel& data, MessageParcel& reply); + void GrantPermissionInner(MessageParcel& data, MessageParcel& reply); + void RevokePermissionInner(MessageParcel& data, MessageParcel& reply); + void ClearUserGrantedPermissionStateInner(MessageParcel& data, MessageParcel& reply); + void AllocHapTokenInner(MessageParcel& data, MessageParcel& reply); + void DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void AllocNativeTokenInner(MessageParcel& data, MessageParcel& reply); + void UpdateHapTokenInner(MessageParcel& data, MessageParcel& reply); + void GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply); + void GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply); + void CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply); + void GetTokenTypeInner(MessageParcel& data, MessageParcel& reply); + void RegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply); + void UnRegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply); + +#ifdef TOKEN_SYNC_ENABLE + void GetHapTokenInfoFromRemoteInner(MessageParcel& data, MessageParcel& reply); + void GetAllNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void SetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply); + void GetRemoteNativeTokenIDInner(MessageParcel& data, MessageParcel& reply); + void GetRemoteHapTokenIDInner(MessageParcel& data, MessageParcel& reply); +#endif + + void DumpTokenInfoInner(MessageParcel& data, MessageParcel& reply); + + bool IsAuthorizedCalling() const; + bool IsAccessTokenCalling() const; + static const int32_t SYSTEM_UID = 1000; + static const int32_t ROOT_UID = 0; + static const int32_t ACCESSTOKEN_UID = 3020; + + using RequestFuncType = void (AccessTokenManagerStub::*)(MessageParcel &data, MessageParcel &reply); + std::map requestFuncMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_MANAGER_STUB_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h new file mode 100644 index 000000000..d19803abc --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_id_manager.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_TOKEN_ID_MANAGER_H +#define ACCESSTOKEN_TOKEN_ID_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "nocopyable.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static constexpr unsigned int TOKEN_RANDOM_MASK = (1 << 20) - 1; +static const int MAX_CREATE_TOKEN_ID_RETRY = 1000; + +class AccessTokenIDManager final { +public: + static AccessTokenIDManager& GetInstance(); + virtual ~AccessTokenIDManager() = default; + + int AddTokenId(AccessTokenID id, ATokenTypeEnum type); + AccessTokenID CreateAndRegisterTokenId(ATokenTypeEnum type, int dlpType); + int RegisterTokenId(AccessTokenID id, ATokenTypeEnum type); + void ReleaseTokenId(AccessTokenID id); + ATokenTypeEnum GetTokenIdType(AccessTokenID id); + int GetTokenIdDlpFlag(AccessTokenID id); + static ATokenTypeEnum GetTokenIdTypeEnum(AccessTokenID id); + +private: + AccessTokenIDManager() = default; + DISALLOW_COPY_AND_MOVE(AccessTokenIDManager); + AccessTokenID CreateTokenId(ATokenTypeEnum type, int dlpType) const; + + OHOS::Utils::RWLock tokenIdLock_; + std::set tokenIdSet_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_ID_MANAGER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h new file mode 100644 index 000000000..d6e866d56 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_TOKEN_INFO_MANAGER_H +#define ACCESSTOKEN_TOKEN_INFO_MANAGER_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "native_token_info.h" +#include "native_token_info_inner.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static const std::string ACCESS_TOKEN_PACKAGE_NAME = "ohos.security.distributed_token_sync"; +static const int UDID_MAX_LENGTH = 128; // udid/uuid max length + +class AccessTokenInfoManager final { +public: + static AccessTokenInfoManager& GetInstance(); + ~AccessTokenInfoManager(); + void Init(); + std::shared_ptr GetHapTokenInfoInner(AccessTokenID id); + int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& InfoParcel); + std::shared_ptr GetNativeTokenInfoInner(AccessTokenID id); + int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& InfoParcel); + std::shared_ptr GetNativePermissionPolicySet(AccessTokenID id); + std::shared_ptr GetHapPermissionPolicySet(AccessTokenID id); + int RemoveHapTokenInfo(AccessTokenID id); + int RemoveNativeTokenInfo(AccessTokenID id); + int CreateHapTokenInfo(const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx); + int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); + AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); + AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); + void ProcessNativeTokenInfos(const std::vector>& tokenInfos); + int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); + void RefreshTokenInfoIfNeeded(); + +#ifdef TOKEN_SYNC_ENABLE + /* tokensync needed */ + int GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSync& hapSync); + void GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync); + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); + int DeleteRemoteDeviceTokens(const std::string& deviceID); + std::string GetUdidByNodeId(const std::string &nodeId); +#endif + +private: + AccessTokenInfoManager(); + DISALLOW_COPY_AND_MOVE(AccessTokenInfoManager); + + void InitHapTokenInfos(); + void InitNativeTokenInfos(); + int AddHapTokenInfo(const std::shared_ptr& info); + int AddNativeTokenInfo(const std::shared_ptr& info); + std::string GetHapUniqueStr(const std::shared_ptr& info) const; + std::string GetHapUniqueStr(const int& userID, const std::string& bundleName, const int& instIndex) const; + bool TryUpdateExistNativeToken(const std::shared_ptr& infoPtr); + int AllocNativeToken(const std::shared_ptr& infoPtr); + void StoreAllTokenInfo(); + int CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync); + int UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync); + + OHOS::ThreadPool tokenDataWorker_; + bool hasInited_; + + OHOS::Utils::RWLock hapTokenInfoLock_; + OHOS::Utils::RWLock nativeTokenInfoLock_; + OHOS::Utils::RWLock managerLock_; + + std::map> hapTokenInfoMap_; + std::map hapTokenIdMap_; + std::map> nativeTokenInfoMap_; + std::map nativeTokenIdMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_INFO_MANAGER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h new file mode 100644 index 000000000..8cb735f6f --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H +#define ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "native_token_info.h" +#include "native_token_info_inner.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenRemoteDevice final { +public: + std::string DeviceID_; // networkID + std::map MappingTokenIDPairMap_; +}; + +class AccessTokenRemoteTokenManager final { +public: + static AccessTokenRemoteTokenManager& GetInstance(); + ~AccessTokenRemoteTokenManager(); + AccessTokenID MapRemoteDeviceTokenToLocal(const std::string& deviceID, AccessTokenID remoteID); + int GetDeviceAllRemoteTokenID(const std::string& deviceID, std::vector& mapIDs); + AccessTokenID GetDeviceMappingTokenID(const std::string& deviceID, AccessTokenID remoteID); + int RemoveDeviceMappingTokenID(const std::string& deviceID, AccessTokenID remoteID); + +private: + AccessTokenRemoteTokenManager(); + DISALLOW_COPY_AND_MOVE(AccessTokenRemoteTokenManager); + + OHOS::Utils::RWLock remoteDeviceLock_; + std::map remoteDeviceMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H + diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h new file mode 100644 index 000000000..ace08daad --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H +#define ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H + +#include +#include +#include + +#include "access_token.h" +#include "generic_values.h" +#include "hap_token_info.h" +#include "permission_def.h" +#include "permission_policy_set.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class HapTokenInfoInner final { +public: + HapTokenInfoInner(); + HapTokenInfoInner(AccessTokenID id, const HapInfoParams& info, const HapPolicyParams& policy); + HapTokenInfoInner(AccessTokenID id, const HapTokenInfo &info, + const std::vector& permStateList); + virtual ~HapTokenInfoInner(); + + void Update(const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); + void TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const; + void StoreHapInfo(std::vector& hapInfoValues, + std::vector& permStateValues) const; + int RestoreHapTokenInfo(AccessTokenID tokenId, const GenericValues& tokenValue, + const std::vector& permStateRes); + + std::shared_ptr GetHapInfoPermissionPolicySet() const; + HapTokenInfo GetHapInfoBasic() const; + int GetUserID() const; + int GetDlpType() const; + std::string GetBundleName() const; + int GetInstIndex() const; + AccessTokenID GetTokenID() const; + void SetTokenBaseInfo(const HapTokenInfo& baseInfo); + void SetPermissionPolicySet(std::shared_ptr& policySet); + void ToString(std::string& info) const; + bool IsRemote() const; + void SetRemote(bool isRemote); + +private: + void StoreHapBasicInfo(std::vector& valueList) const; + void TranslationIntoGenericValues(GenericValues& outGenericValues) const; + int RestoreHapTokenBasicInfo(const GenericValues& inGenericValues); + + HapTokenInfo tokenInfoBasic_; + + // true means sync from remote. + bool isRemote_; + + std::shared_ptr permPolicySet_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_HAP_TOKEN_INFO_INNER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h new file mode 100644 index 000000000..6894140b0 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H +#define ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H + +#include +#include +#include "access_token.h" +#include "generic_values.h" +#include "native_token_info.h" +#include "permission_policy_set.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +static const std::string JSON_PROCESS_NAME = "processName"; +static const std::string JSON_APL = "APL"; +static const std::string JSON_VERSION = "version"; +static const std::string JSON_TOKEN_ID = "tokenId"; +static const std::string JSON_TOKEN_ATTR = "tokenAttr"; +static const std::string JSON_DCAPS = "dcaps"; +static const std::string JSON_PERMS = "permissions"; +static const std::string JSON_ACLS = "nativeAcls"; +static const int MAX_DCAPS_NUM = 32; +static const int MAX_REQ_PERM_NUM = 32; + +class NativeTokenInfoInner final { +public: + NativeTokenInfoInner(); + NativeTokenInfoInner(NativeTokenInfo& info, + const std::vector& permStateList); + virtual ~NativeTokenInfoInner(); + + int Init(AccessTokenID id, const std::string& processName, int apl, + const std::vector& dcap, + const std::vector& nativeAcls, + const std::vector& permStateList); + void StoreNativeInfo(std::vector& valueList, + std::vector& permStateValues) const; + void TranslateToNativeTokenInfo(NativeTokenInfo& InfoParcel) const; + void SetDcaps(const std::string& dcapStr); + void SetNativeAcls(const std::string& AclsStr); + void ToString(std::string& info) const; + int RestoreNativeTokenInfo(AccessTokenID tokenId, const GenericValues& inGenericValues, + const std::vector& permStateRes); + void Update(AccessTokenID tokenId, const std::string& processName, + int apl, const std::vector& dcap, + const std::vector& nativeAcls); + + std::vector GetDcap() const; + std::vector GetNativeAcls() const; + AccessTokenID GetTokenID() const; + std::string GetProcessName() const; + NativeTokenInfo GetNativeTokenInfo() const; + std::shared_ptr GetNativeInfoPermissionPolicySet() const; + bool IsRemote() const; + void SetRemote(bool isRemote); + +private: + int TranslationIntoGenericValues(GenericValues& outGenericValues) const; + std::string DcapToString(const std::vector& dcap) const; + std::string NativeAclsToString(const std::vector& nativeAcls) const; + + // true means sync from remote. + bool isRemote_; + NativeTokenInfo tokenInfoBasic_; + std::shared_ptr permPolicySet_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_NATIVE_TOKEN_INFO_INNER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_receptor.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_receptor.h new file mode 100644 index 000000000..cc72c61ff --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/native_token_receptor.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_NATIVE_TOKEN_RECEPTOR_H +#define ACCESSTOKEN_NATIVE_TOKEN_RECEPTOR_H + +#include +#include + +#include "native_token_info_inner.h" + +#include "access_token.h" +#include "nlohmann/json.hpp" +#include "nocopyable.h" +#include "permission_policy_set.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string NATIVE_TOKEN_CONFIG_FILE = "/data/service/el0/access_token/nativetoken.json"; +constexpr int MAX_NATIVE_CONFIG_FILE_SIZE = 5 * 1024 * 1024; // 5M +constexpr size_t BUFFER_SIZE = 1024; +class NativeTokenReceptor final { +public: + static NativeTokenReceptor& GetInstance(); + virtual ~NativeTokenReceptor() = default; + int Init(); + +private: + NativeTokenReceptor() : ready_(false) {} + DISALLOW_COPY_AND_MOVE(NativeTokenReceptor); + int ReadCfgFile(std::string &nativeRawData); + void FromJson(const nlohmann::json &jsonObject, + std::vector>& tokenInfos); + int32_t ParserNativeRawData(const std::string& nativeRawData, + std::vector>& tokenInfos); + void from_json(const nlohmann::json& j, NativeTokenInfo& p); + bool ready_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_NATIVE_TOKEN_RECEPTOR_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h new file mode 100644 index 000000000..1ad3aad4b --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_MODIFY_NOTIFIER_H +#define TOKEN_MODIFY_NOTIFIER_H + +#include +#include + +#include "access_token.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenModifyNotifier final { +public: + static TokenModifyNotifier& GetInstance(); + ~TokenModifyNotifier(); + void AddHapTokenObservation(AccessTokenID tokenID); + void NotifyTokenDelete(AccessTokenID tokenID); + void NotifyTokenModify(AccessTokenID tokenID); + void NotifyTokenChangedIfNeed(); + void NotifyTokenSyncTask(); + +private: + TokenModifyNotifier(); + DISALLOW_COPY_AND_MOVE(TokenModifyNotifier); + + bool hasInited_; + OHOS::Utils::RWLock initLock_; + OHOS::Utils::RWLock Notifylock_; + OHOS::ThreadPool notifyTokenWorker_; + std::set observationSet_; + std::vector deleteTokenList_; + std::vector modifiedTokenList_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_MODIFY_NOTIFIER_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp new file mode 100644 index 000000000..89b44b390 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/callback_manager.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "callback_manager.h" + +#include +#include +#include + +#include "access_token.h" +#include "perm_state_callback_death_recipient.h" + + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "CallbackManager"}; +const time_t MAX_TIMEOUT_SEC = 30; +} + +CallbackManager& CallbackManager::GetInstance() +{ + static CallbackManager instance; + return instance; +} + +CallbackManager::CallbackManager() : callbackDeathRecipient_(sptr( + new (std::nothrow) PermStateCallbackDeathRecipient())) +{ +} + +CallbackManager::~CallbackManager() +{ +} + +int32_t CallbackManager::AddCallback( + const std::shared_ptr& callbackScopePtr, const sptr& callback) +{ + if ((callbackScopePtr == nullptr) || (callback == nullptr)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input is nullptr"); + return RET_FAILED; + } + + callback->AddDeathRecipient(callbackDeathRecipient_); + + CallbackRecord recordInstance; + recordInstance.callbackObject_ = callback; + recordInstance.scopePtr_ = callbackScopePtr; + + std::lock_guard lock(mutex_); + callbackInfoList_.emplace_back(recordInstance); + + ACCESSTOKEN_LOG_INFO(LABEL, "recordInstance is added"); + return RET_SUCCESS; +} + +int32_t CallbackManager::RemoveCallback(const sptr& callback) +{ + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "callback is nullptr"); + return RET_FAILED; + } + + std::lock_guard lock(mutex_); + + for (auto it = callbackInfoList_.begin(); it != callbackInfoList_.end(); ++it) { + if (callback == (*it).callbackObject_) { + ACCESSTOKEN_LOG_INFO(LABEL, "find callback"); + if (callbackDeathRecipient_ != nullptr) { + callback->RemoveDeathRecipient(callbackDeathRecipient_); + } + (*it).callbackObject_ = nullptr; + callbackInfoList_.erase(it); + break; + } + } + ACCESSTOKEN_LOG_INFO(LABEL, "callbackInfoList_ %{public}u", (uint32_t)callbackInfoList_.size()); + return RET_SUCCESS; +} + +bool CallbackManager::CalledAccordingToTokenIdLlist( + const std::vector& tokenIDList, AccessTokenID tokenID) +{ + if (tokenIDList.empty()) { + return true; + } + for (const auto& id : tokenIDList) { + if (id == tokenID) { + return true; + } + } + return false; +} + +bool CallbackManager::CalledAccordingToPermLlist(const std::vector& permList, const std::string& permName) +{ + if (permList.empty()) { + return true; + } + for (const auto& perm : permList) { + if (perm == permName) { + return true; + } + } + return false; +} + +void CallbackManager::ExecuteCallbackAsync(AccessTokenID tokenID, const std::string& permName, int32_t changeType) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "entry"); + + auto callbackStart = [&]() { + ACCESSTOKEN_LOG_INFO(LABEL, "callbackStart"); + std::lock_guard lock(mutex_); + for (auto it = callbackInfoList_.begin(); it != callbackInfoList_.end(); ++it) { + std::shared_ptr scopePtr_ = (*it).scopePtr_; + if (scopePtr_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "scopePtr_ is nullptr"); + continue; + } + if (!CalledAccordingToTokenIdLlist(scopePtr_->tokenIDs, tokenID) || + !CalledAccordingToPermLlist(scopePtr_->permList, permName)) { + ACCESSTOKEN_LOG_INFO(LABEL, + "tokenID is %{public}u, permName is %{public}s", tokenID, permName.c_str()); + continue; + } + auto callback = iface_cast((*it).callbackObject_); + if (callback != nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "callback excute"); + PermStateChangeInfo resInfo; + resInfo.PermStateChangeType = changeType; + resInfo.permissionName = permName; + resInfo.tokenID = tokenID; + callback->PermStateChangeCallback(resInfo); + } + } + }; + + std::packaged_task callbackTask(callbackStart); + std::future fut = callbackTask.get_future(); + std::make_unique(std::move(callbackTask))->detach(); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "Waiting for the callback execution complete..."); + std::future_status status = fut.wait_for(std::chrono::seconds(MAX_TIMEOUT_SEC)); + if (status == std::future_status::timeout) { + ACCESSTOKEN_LOG_WARN(LABEL, "callbackTask callback execution timeout"); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "The callback execution is complete"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/perm_state_callback_death_recipient.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/perm_state_callback_death_recipient.cpp new file mode 100644 index 000000000..817ac2ad1 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/perm_state_callback_death_recipient.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_state_callback_death_recipient.h" + +#include "access_token.h" +#include "callback_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermStateCallbackDeathRecipient" +}; +} + +void PermStateCallbackDeathRecipient::OnRemoteDied(const wptr& remote) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "enter"); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote object is nullptr"); + return; + } + + sptr object = remote.promote(); + if (object == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "object is nullptr"); + return; + } + CallbackManager::GetInstance().RemoveCallback(object); + ACCESSTOKEN_LOG_INFO(LABEL, "end"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/permission_state_change_callback_proxy.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/permission_state_change_callback_proxy.cpp new file mode 100644 index 000000000..6c3ce737e --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/callback/permission_state_change_callback_proxy.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_state_change_callback_proxy.h" + +#include "access_token.h" +#include "accesstoken_log.h" +#include "permission_state_change_info_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionStateChangeCallbackProxy" +}; +} + +PermissionStateChangeCallbackProxy::PermissionStateChangeCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +PermissionStateChangeCallbackProxy::~PermissionStateChangeCallbackProxy() +{} + +void PermissionStateChangeCallbackProxy::PermStateChangeCallback(PermStateChangeInfo& info) +{ + MessageParcel data; + data.WriteInterfaceToken(IPermissionStateCallback::GetDescriptor()); + + PermissionStateChangeInfoParcel resultParcel; + resultParcel.changeInfo = info; + if (!data.WriteParcelable(&resultParcel)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable(result)"); + return; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return; + } + int32_t requestResult = remote->SendRequest( + static_cast(IPermissionStateCallback::PERMISSION_STATE_CHANGE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "SendRequest success"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp new file mode 100644 index 000000000..2d9f3e83e --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_storage.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_storage.h" + +#include "sqlite_storage.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +DataStorage& DataStorage::GetRealDataStorage() +{ + return SqliteStorage::GetInstance(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp new file mode 100644 index 000000000..5dc08b762 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_translator.h" + +#include + +#include "accesstoken_log.h" +#include "data_validator.h" +#include "field_const.h" +#include "permission_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DataTranslator"}; +} + +int DataTranslator::TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues) +{ + outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionDef.permissionName); + outGenericValues.Put(FIELD_BUNDLE_NAME, inPermissionDef.bundleName); + outGenericValues.Put(FIELD_GRANT_MODE, inPermissionDef.grantMode); + outGenericValues.Put(FIELD_AVAILABLE_LEVEL, inPermissionDef.availableLevel); + outGenericValues.Put(FIELD_PROVISION_ENABLE, inPermissionDef.provisionEnable ? 1 : 0); + outGenericValues.Put(FIELD_DISTRIBUTED_SCENE_ENABLE, inPermissionDef.distributedSceneEnable ? 1 : 0); + outGenericValues.Put(FIELD_LABEL, inPermissionDef.label); + outGenericValues.Put(FIELD_LABEL_ID, inPermissionDef.labelId); + outGenericValues.Put(FIELD_DESCRIPTION, inPermissionDef.description); + outGenericValues.Put(FIELD_DESCRIPTION_ID, inPermissionDef.descriptionId); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef) +{ + outPermissionDef.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME); + outPermissionDef.bundleName = inGenericValues.GetString(FIELD_BUNDLE_NAME); + outPermissionDef.grantMode = inGenericValues.GetInt(FIELD_GRANT_MODE); + int aplNum = inGenericValues.GetInt(FIELD_AVAILABLE_LEVEL); + if (!DataValidator::IsAplNumValid(aplNum)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Apl is wrong."); + return RET_FAILED; + } + outPermissionDef.availableLevel = (ATokenAplEnum)aplNum; + outPermissionDef.provisionEnable = (inGenericValues.GetInt(FIELD_PROVISION_ENABLE) == 1); + outPermissionDef.distributedSceneEnable = (inGenericValues.GetInt(FIELD_DISTRIBUTED_SCENE_ENABLE) == 1); + outPermissionDef.label = inGenericValues.GetString(FIELD_LABEL); + outPermissionDef.labelId = inGenericValues.GetInt(FIELD_LABEL_ID); + outPermissionDef.description = inGenericValues.GetString(FIELD_DESCRIPTION); + outPermissionDef.descriptionId = inGenericValues.GetInt(FIELD_DESCRIPTION_ID); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoGenericValues(const PermissionStateFull& inPermissionState, + const unsigned int grantIndex, GenericValues& outGenericValues) +{ + if (grantIndex >= inPermissionState.resDeviceID.size() || grantIndex >= inPermissionState.grantStatus.size() || + grantIndex >= inPermissionState.grantFlags.size()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "perm status grant size is wrong"); + return RET_FAILED; + } + outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionState.permissionName); + outGenericValues.Put(FIELD_DEVICE_ID, inPermissionState.resDeviceID[grantIndex]); + outGenericValues.Put(FIELD_GRANT_IS_GENERAL, inPermissionState.isGeneral ? 1 : 0); + outGenericValues.Put(FIELD_GRANT_STATE, inPermissionState.grantStatus[grantIndex]); + outGenericValues.Put(FIELD_GRANT_FLAG, inPermissionState.grantFlags[grantIndex]); + return RET_SUCCESS; +} + +int DataTranslator::TranslationIntoPermissionStateFull(const GenericValues& inGenericValues, + PermissionStateFull& outPermissionState) +{ + outPermissionState.isGeneral = ((inGenericValues.GetInt(FIELD_GRANT_IS_GENERAL) == 1) ? true : false); + outPermissionState.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME); + if (!DataValidator::IsPermissionNameValid(outPermissionState.permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permission name is wrong"); + return RET_FAILED; + } + + std::string devID = inGenericValues.GetString(FIELD_DEVICE_ID); + if (!DataValidator::IsDeviceIdValid(devID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "devID is wrong"); + return RET_FAILED; + } + outPermissionState.resDeviceID.push_back(devID); + + int grantStatus = (PermissionState)inGenericValues.GetInt(FIELD_GRANT_STATE); + if (!PermissionValidator::IsGrantStatusValid(grantStatus)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "grantStatus is wrong"); + return RET_FAILED; + } + outPermissionState.grantStatus.push_back(grantStatus); + + int grantFlag = (PermissionState)inGenericValues.GetInt(FIELD_GRANT_FLAG); + if (!PermissionValidator::IsPermissionFlagValid(grantFlag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "grantFlag is wrong"); + return RET_FAILED; + } + outPermissionState.grantFlags.push_back(grantFlag); + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp new file mode 100644 index 000000000..5763a0c4a --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sqlite_storage.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SqliteStorage"}; +} + +SqliteStorage& SqliteStorage::GetInstance() +{ + static SqliteStorage instance; + return instance; +} + +SqliteStorage::~SqliteStorage() +{ + Close(); +} + +void SqliteStorage::OnCreate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called.", __func__); + CreateHapTokenInfoTable(); + CreateNativeTokenInfoTable(); + CreatePermissionDefinitionTable(); + CreatePermissionStateTable(); +} + +void SqliteStorage::OnUpdate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called.", __func__); +} + +SqliteStorage::SqliteStorage() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATABASE_VERSION) +{ + SqliteTable hapTokenInfoTable; + hapTokenInfoTable.tableName_ = HAP_TOKEN_INFO_TABLE; + hapTokenInfoTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_USER_ID, + FIELD_BUNDLE_NAME, FIELD_INST_INDEX, FIELD_DLP_TYPE, + FIELD_APP_ID, FIELD_DEVICE_ID, + FIELD_APL, FIELD_TOKEN_VERSION, + FIELD_TOKEN_ATTR, FIELD_API_VERSION + }; + + SqliteTable NativeTokenInfoTable; + NativeTokenInfoTable.tableName_ = NATIVE_TOKEN_INFO_TABLE; + NativeTokenInfoTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PROCESS_NAME, + FIELD_TOKEN_VERSION, FIELD_TOKEN_ATTR, + FIELD_DCAP, FIELD_NATIVE_ACLS, FIELD_APL + }; + + SqliteTable permissionDefTable; + permissionDefTable.tableName_ = PERMISSION_DEF_TABLE; + permissionDefTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PERMISSION_NAME, + FIELD_BUNDLE_NAME, FIELD_GRANT_MODE, + FIELD_AVAILABLE_LEVEL, FIELD_PROVISION_ENABLE, + FIELD_DISTRIBUTED_SCENE_ENABLE, FIELD_LABEL, + FIELD_LABEL_ID, FIELD_DESCRIPTION, + FIELD_DESCRIPTION_ID + }; + + SqliteTable permissionStateTable; + permissionStateTable.tableName_ = PERMISSION_STATE_TABLE; + permissionStateTable.tableColumnNames_ = { + FIELD_TOKEN_ID, FIELD_PERMISSION_NAME, + FIELD_DEVICE_ID, FIELD_GRANT_IS_GENERAL, + FIELD_GRANT_STATE, FIELD_GRANT_FLAG + }; + + dataTypeToSqlTable_ = { + {ACCESSTOKEN_HAP_INFO, hapTokenInfoTable}, + {ACCESSTOKEN_NATIVE_INFO, NativeTokenInfoTable}, + {ACCESSTOKEN_PERMISSION_DEF, permissionDefTable}, + {ACCESSTOKEN_PERMISSION_STATE, permissionStateTable}, + }; + + Open(); +} + +int SqliteStorage::Add(const DataType type, const std::vector& values) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string prepareSql = CreateInsertPrepareSqlCmd(type); + auto statement = Prepare(prepareSql); + BeginTransaction(); + bool isExecuteSuccessfully = true; + for (const auto& value : values) { + std::vector columnNames = value.GetAllKeys(); + for (const auto& columnName : columnNames) { + statement.Bind(columnName, value.Get(columnName)); + } + int ret = statement.Step(); + if (ret != Statement::State::DONE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", SpitError().c_str()); + isExecuteSuccessfully = false; + } + statement.Reset(); + } + if (!isExecuteSuccessfully) { + ACCESSTOKEN_LOG_ERROR(LABEL, "rollback transaction."); + RollbackTransaction(); + return FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "commit transaction."); + CommitTransaction(); + return SUCCESS; +} + +int SqliteStorage::Remove(const DataType type, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector columnNames = conditions.GetAllKeys(); + std::string prepareSql = CreateDeletePrepareSqlCmd(type, columnNames); + auto statement = Prepare(prepareSql); + for (const auto& columnName : columnNames) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int SqliteStorage::Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector modifyColumns = modifyValues.GetAllKeys(); + std::vector conditionColumns = conditions.GetAllKeys(); + std::string prepareSql = CreateUpdatePrepareSqlCmd(type, modifyColumns, conditionColumns); + auto statement = Prepare(prepareSql); + for (const auto& columnName : modifyColumns) { + statement.Bind(columnName, modifyValues.Get(columnName)); + } + for (const auto& columnName : conditionColumns) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int SqliteStorage::Find(const DataType type, std::vector& results) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string prepareSql = CreateSelectPrepareSqlCmd(type); + auto statement = Prepare(prepareSql); + while (statement.Step() == Statement::State::ROW) { + int columnCount = statement.GetColumnCount(); + GenericValues value; + for (int i = 0; i < columnCount; i++) { + value.Put(statement.GetColumnName(i), statement.GetValue(i, false)); + } + results.emplace_back(value); + } + return SUCCESS; +} + +int SqliteStorage::RefreshAll(const DataType type, const std::vector& values) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string deleteSql = CreateDeletePrepareSqlCmd(type); + std::string insertSql = CreateInsertPrepareSqlCmd(type); + auto deleteStatement = Prepare(deleteSql); + auto insertStatement = Prepare(insertSql); + BeginTransaction(); + bool canCommit = deleteStatement.Step() == Statement::State::DONE; + for (const auto& value : values) { + std::vector columnNames = value.GetAllKeys(); + for (const auto& columnName : columnNames) { + insertStatement.Bind(columnName, value.Get(columnName)); + } + int ret = insertStatement.Step(); + if (ret != Statement::State::DONE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "insert failed, errorMsg: %{public}s", SpitError().c_str()); + canCommit = false; + } + insertStatement.Reset(); + } + if (!canCommit) { + ACCESSTOKEN_LOG_ERROR(LABEL, "rollback transaction."); + RollbackTransaction(); + return FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "commit transaction."); + CommitTransaction(); + return SUCCESS; +} + +std::string SqliteStorage::CreateInsertPrepareSqlCmd(const DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "insert into " + it->second.tableName_ + " values("; + int i = 1; + for (const auto& columnName : it->second.tableColumnNames_) { + sql.append(":" + columnName); + if (i < (int) it->second.tableColumnNames_.size()) { + sql.append(","); + } + i += 1; + } + sql.append(")"); + return sql; +} + +std::string SqliteStorage::CreateDeletePrepareSqlCmd( + const DataType type, const std::vector& columnNames) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where 1 = 1"; + for (const auto& columnName : columnNames) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + return sql; +} + +std::string SqliteStorage::CreateUpdatePrepareSqlCmd(const DataType type, const std::vector& modifyColumns, + const std::vector& conditionColumns) const +{ + if (modifyColumns.empty()) { + return std::string(); + } + + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + + std::string sql = "update " + it->second.tableName_ + " set "; + int i = 1; + for (const auto& columnName : modifyColumns) { + sql.append(columnName + "=:" + columnName); + if (i < (int) modifyColumns.size()) { + sql.append(","); + } + i += 1; + } + + if (!conditionColumns.empty()) { + sql.append(" where 1 = 1"); + for (const auto& columnName : conditionColumns) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + } + return sql; +} + +std::string SqliteStorage::CreateSelectPrepareSqlCmd(const DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "select * from " + it->second.tableName_; + return sql; +} + +int SqliteStorage::CreateHapTokenInfoTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_HAP_INFO); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_USER_ID + " integer not null,") + .append(FIELD_BUNDLE_NAME + " text not null,") + .append(FIELD_INST_INDEX + " integer not null,") + .append(FIELD_DLP_TYPE + " integer not null,") + .append(FIELD_APP_ID + " text not null,") + .append(FIELD_DEVICE_ID + " text not null,") + .append(FIELD_APL + " integer not null,") + .append(FIELD_TOKEN_VERSION + " integer not null,") + .append(FIELD_TOKEN_ATTR + " integer not null,") + .append(FIELD_API_VERSION + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreateNativeTokenInfoTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_NATIVE_INFO); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PROCESS_NAME + " text not null,") + .append(FIELD_TOKEN_VERSION + " integer not null,") + .append(FIELD_TOKEN_ATTR + " integer not null,") + .append(FIELD_DCAP + " text not null,") + .append(FIELD_NATIVE_ACLS + " text not null,") + .append(FIELD_APL + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreatePermissionDefinitionTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_PERMISSION_DEF); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PERMISSION_NAME + " text not null,") + .append(FIELD_BUNDLE_NAME + " text not null,") + .append(FIELD_GRANT_MODE + " integer not null,") + .append(FIELD_AVAILABLE_LEVEL + " integer not null,") + .append(FIELD_PROVISION_ENABLE + " integer not null,") + .append(FIELD_DISTRIBUTED_SCENE_ENABLE + " integer not null,") + .append(FIELD_LABEL + " text not null,") + .append(FIELD_LABEL_ID + " integer not null,") + .append(FIELD_DESCRIPTION + " text not null,") + .append(FIELD_DESCRIPTION_ID + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("," + FIELD_PERMISSION_NAME) + .append("))"); + return ExecuteSql(sql); +} + +int SqliteStorage::CreatePermissionStateTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::ACCESSTOKEN_PERMISSION_STATE); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_PERMISSION_NAME + " text not null,") + .append(FIELD_DEVICE_ID + " text not null,") + .append(FIELD_GRANT_IS_GENERAL + " integer not null,") + .append(FIELD_GRANT_STATE + " integer not null,") + .append(FIELD_GRANT_FLAG + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("," + FIELD_PERMISSION_NAME) + .append("," + FIELD_DEVICE_ID) + .append("))"); + return ExecuteSql(sql); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/device/atm_device_state_callback.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/device/atm_device_state_callback.cpp new file mode 100644 index 000000000..3f7db3a8f --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/device/atm_device_state_callback.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "atm_device_state_callback.h" + +#include +#include + +#include "accesstoken_log.h" +#include "constant.h" +#include "device_manager.h" +#include "dm_device_info.h" +#include "token_sync_manager_client.h" +#include "accesstoken_manager_service.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +using OHOS::DistributedHardware::DeviceStateCallback; +using OHOS::DistributedHardware::DmDeviceInfo; +using OHOS::DistributedHardware::DmInitCallback; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AtmDeviceStateCallback"}; +} + +AtmDeviceStateCallback::AtmDeviceStateCallback() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "AtmDeviceStateCallback()"); +} + +AtmDeviceStateCallback::~AtmDeviceStateCallback() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~AtmDeviceStateCallback()"); +} + +void AtmDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "device online"); + + // when remote device online and token sync remote object is null, start a thread to load token sync + if (TokenSyncManagerClient::GetInstance().GetRemoteObject() == nullptr) { + std::function runner = [&]() { + TokenSyncManagerClient::GetInstance().LoadTokenSync(); + + ACCESSTOKEN_LOG_INFO(LABEL, "load tokensync."); + + return; + }; + + std::thread initThread(runner); + initThread.detach(); + } +} + +void AtmDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "device offline"); +} + +void AtmDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "device ready"); +} + +void AtmDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "device changed"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_manager.cpp new file mode 100644 index 000000000..053cee3eb --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_manager.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dlp_permission_set_manager.h" + +#include +#include +#include +#include +#include + +#include "access_token.h" +#include "accesstoken_log.h" +#include "data_validator.h" +#include "securec.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DlpPermissionSetManager"}; +} + +DlpPermissionSetManager& DlpPermissionSetManager::GetInstance() +{ + static DlpPermissionSetManager instance; + return instance; +} + +DlpPermissionSetManager::DlpPermissionSetManager() +{} + +DlpPermissionSetManager::~DlpPermissionSetManager() +{} + +void DlpPermissionSetManager::ProcessDlpPermInfos(const std::vector& dlpPermInfos) +{ + for (auto iter = dlpPermInfos.begin(); iter != dlpPermInfos.end(); iter++) { + auto it = dlpPermissionModeMap_.find(iter->permissionName); + if (it != dlpPermissionModeMap_.end()) { + ACCESSTOKEN_LOG_WARN(LABEL, + "info for permission: %{public}s dlpMode %{public}d has been insert, please check!", + iter->permissionName.c_str(), iter->dlpMode); + continue; + } + dlpPermissionModeMap_[iter->permissionName] = iter->dlpMode; + continue; + } +} + +int32_t DlpPermissionSetManager::GetPermDlpMode(const std::string& permissionName) +{ + auto it = dlpPermissionModeMap_.find(permissionName); + if (it == dlpPermissionModeMap_.end()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "can not find permission: %{public}s in dlp permission cfg", + permissionName.c_str()); + return DLP_PERM_ALL; + } + return dlpPermissionModeMap_[permissionName]; +} + +int32_t DlpPermissionSetManager::UpdatePermStateWithDlpInfo(int32_t dlpType, + std::vector& permStateList) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "dlpType: %{public}d", dlpType); + for (auto iter = permStateList.begin(); iter != permStateList.end(); iter++) { + if (iter->grantStatus[0] == PERMISSION_DENIED) { + continue; + } + int32_t dlpMode = GetPermDlpMode(iter->permissionName); + bool res = IsPermStateNeedUpdate(dlpType, dlpMode); + if (res) { + iter->grantStatus[0] = PERMISSION_DENIED; + } + } + return RET_SUCCESS; +} + +bool DlpPermissionSetManager::IsPermStateNeedUpdate(int32_t dlpType, int32_t dlpMode) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "dlpType: %{public}d dlpMode %{public}d", dlpType, dlpMode); + /* permission is available to all dlp hap */ + if (dlpMode == DLP_PERM_ALL) { + return false; + } + + /* permission is available to full control */ + if (dlpMode == DLP_PERM_FULL_CONTROL && dlpType == DLP_FULL_CONTROL) { + return false; + } + /* permission is available to none */ + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_parser.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_parser.cpp new file mode 100644 index 000000000..bb2509cee --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/dlp_permission_set_parser.cpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dlp_permission_set_parser.h" + +#include +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "data_validator.h" +#include "dlp_permission_set_manager.h" +#include "securec.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DlpPermissionSetParser"}; +} + +// nlohmann json need the function named from_json to parse +void from_json(const nlohmann::json& j, PermissionDlpMode& p) +{ + if (j.find("name") == j.end()) { + return; + } + p.permissionName = j.at("name").get(); + if (!DataValidator::IsProcessNameValid(p.permissionName)) { + return; + } + + if (j.find("dlpGrantRange") == j.end()) { + return; + } + std::string dlpModeStr = j.at("dlpGrantRange").get(); + if (dlpModeStr == "all") { + p.dlpMode = DLP_PERM_ALL; + return; + } + if (dlpModeStr == "full_control") { + p.dlpMode = DLP_PERM_FULL_CONTROL; + return; + } + p.dlpMode = DLP_PERM_NONE; + return; +} + +int32_t DlpPermissionSetParser::ParserDlpPermsRawData(const std::string& dlpPermsRawData, + std::vector& dlpPerms) +{ + nlohmann::json jsonRes = nlohmann::json::parse(dlpPermsRawData, nullptr, false); + if (jsonRes.is_discarded()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "jsonRes is invalid."); + return RET_FAILED; + } + + if (jsonRes.find("dlpPermissions") != jsonRes.end()) { + nlohmann::json dlpPermTokenJson = jsonRes.at("dlpPermissions").get(); + dlpPerms = dlpPermTokenJson.get>(); + } + + return RET_SUCCESS; +} + +int32_t DlpPermissionSetParser::ReadCfgFile(std::string& dlpPermsRawData) +{ + int32_t fd = open(CLONE_PERMISSION_CONFIG_FILE.c_str(), O_RDONLY); + if (fd < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "open failed errno %{public}d.", errno); + return RET_FAILED; + } + struct stat statBuffer; + + if (fstat(fd, &statBuffer) != 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fstat failed errno %{public}d.", errno); + close(fd); + return RET_FAILED; + } + + if (statBuffer.st_size == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is 0."); + close(fd); + return RET_FAILED; + } + if (statBuffer.st_size > MAX_CLONE_PERMISSION_CONFIG_FILE_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is too large."); + close(fd); + return RET_FAILED; + } + dlpPermsRawData.reserve(statBuffer.st_size); + + char buff[MAX_BUFFER_SIZE] = { 0 }; + ssize_t readLen = 0; + while ((readLen = read(fd, buff, MAX_BUFFER_SIZE)) > 0) { + dlpPermsRawData.append(buff, readLen); + } + close(fd); + + if (readLen == 0) { + return RET_SUCCESS; + } + return RET_FAILED; +} + +int32_t DlpPermissionSetParser::Init() +{ + if (ready_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "dlp permission has been set."); + return RET_SUCCESS; + } + + std::string dlpPermsRawData; + int32_t ret = ReadCfgFile(dlpPermsRawData); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "readCfgFile failed."); + return RET_FAILED; + } + std::vector dlpPerms; + ret = ParserDlpPermsRawData(dlpPermsRawData, dlpPerms); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ParserDlpPermsRawData failed."); + return RET_FAILED; + } + DlpPermissionSetManager::GetInstance().ProcessDlpPermInfos(dlpPerms); + + ready_ = true; + ACCESSTOKEN_LOG_INFO(LABEL, "init ok."); + return RET_SUCCESS; +} + +DlpPermissionSetParser& DlpPermissionSetParser::GetInstance() +{ + static DlpPermissionSetParser instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp new file mode 100644 index 000000000..932c6515b --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_definition_cache.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_definition_cache.h" + +#include "access_token.h" +#include "accesstoken_log.h" +#include "field_const.h" +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionDefinitionCache" +}; +} + +PermissionDefinitionCache& PermissionDefinitionCache::GetInstance() +{ + static PermissionDefinitionCache instance; + return instance; +} + +PermissionDefinitionCache::PermissionDefinitionCache() +{} + +PermissionDefinitionCache::~PermissionDefinitionCache() +{} + +bool PermissionDefinitionCache::Insert(const PermissionDef& info, AccessTokenID tokenId) +{ + Utils::UniqueWriteGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.find(info.permissionName); + if (it != permissionDefinitionMap_.end()) { + ACCESSTOKEN_LOG_WARN(LABEL, "info for permission: %{public}s has been insert, please check!", + info.permissionName.c_str()); + return false; + } + permissionDefinitionMap_[info.permissionName].permDef = info; + permissionDefinitionMap_[info.permissionName].tokenId = tokenId; + return true; +} + +bool PermissionDefinitionCache::Update(const PermissionDef& info) +{ + Utils::UniqueWriteGuard cacheGuard(this->cacheLock_); + permissionDefinitionMap_[info.permissionName].permDef = info; + return true; +} + +void PermissionDefinitionCache::DeleteByBundleName(const std::string& bundleName) +{ + Utils::UniqueWriteGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.begin(); + while (it != permissionDefinitionMap_.end()) { + if (bundleName == it->second.permDef.bundleName) { + permissionDefinitionMap_.erase(it++); + } else { + ++it; + } + } +} + +int PermissionDefinitionCache::FindByPermissionName(const std::string& permissionName, PermissionDef& info) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.find(permissionName); + if (it == permissionDefinitionMap_.end()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "can not find definition info for permission: %{public}s", + permissionName.c_str()); + return RET_FAILED; + } + info = it->second.permDef; + return RET_SUCCESS; +} + +bool PermissionDefinitionCache::IsSystemGrantedPermission(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return IsGrantedModeEqualInner(permissionName, SYSTEM_GRANT); +} + +bool PermissionDefinitionCache::IsUserGrantedPermission(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return IsGrantedModeEqualInner(permissionName, USER_GRANT); +} + +bool PermissionDefinitionCache::IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const +{ + auto it = permissionDefinitionMap_.find(permissionName); + if (it == permissionDefinitionMap_.end()) { + return false; + } + return it->second.permDef.grantMode == grantMode; +} + +bool PermissionDefinitionCache::HasDefinition(const std::string& permissionName) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return permissionDefinitionMap_.count(permissionName) == 1; +} + +bool PermissionDefinitionCache::IsPermissionDefEmpty() +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + return permissionDefinitionMap_.empty(); +} + +void PermissionDefinitionCache::StorePermissionDef(std::vector& valueList) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.begin(); + while (it != permissionDefinitionMap_.end()) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, (int)it->second.tokenId); + DataTranslator::TranslationIntoGenericValues(it->second.permDef, genericValues); + valueList.emplace_back(genericValues); + ++it; + } +} + +void PermissionDefinitionCache::GetDefPermissionsByTokenId(std::vector& permList, + AccessTokenID tokenId) +{ + Utils::UniqueReadGuard cacheGuard(this->cacheLock_); + auto it = permissionDefinitionMap_.begin(); + while (it != permissionDefinitionMap_.end()) { + if (tokenId == it->second.tokenId) { + permList.emplace_back(it->second.permDef); + } + ++it; + } +} + +int32_t PermissionDefinitionCache::RestorePermDefInfo(std::vector& permDefRes) +{ + std::vector permDataList; + for (const GenericValues& defValue : permDefRes) { + PermissionDef def; + AccessTokenID tokenId = (AccessTokenID)defValue.GetInt(FIELD_TOKEN_ID); + int32_t ret = DataTranslator::TranslationIntoPermissionDef(defValue, def); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x permDef is wrong.", tokenId); + return ret; + } + Insert(def, tokenId); + } + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp new file mode 100644 index 000000000..4819bf776 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp @@ -0,0 +1,448 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_manager.h" +#include "access_token.h" +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "callback_manager.h" +#ifdef SUPPORT_SANDBOX_APP +#include "dlp_permission_set_manager.h" +#endif +#include "permission_definition_cache.h" +#include "permission_validator.h" +#ifdef TOKEN_SYNC_ENABLE +#include "token_modify_notifier.h" +#endif + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionManager"}; +} + +PermissionManager& PermissionManager::GetInstance() +{ + static PermissionManager instance; + return instance; +} + +PermissionManager::PermissionManager() +{ +} + +PermissionManager::~PermissionManager() +{ +} + +void PermissionManager::AddDefPermissions(const std::vector& permList, AccessTokenID tokenId, + bool updateFlag) +{ + std::vector permFilterList; + PermissionValidator::FilterInvalidPermissionDef(permList, permFilterList); + + for (const auto& perm : permFilterList) { + if (!PermissionValidator::IsPermissionDefValid(perm)) { + ACCESSTOKEN_LOG_INFO(LABEL, "invalid permission definition info: %{public}s", + TransferPermissionDefToString(perm).c_str()); + continue; + } + + if (updateFlag) { + PermissionDefinitionCache::GetInstance().Update(perm); + continue; + } + + if (!PermissionDefinitionCache::GetInstance().HasDefinition(perm.permissionName)) { + PermissionDefinitionCache::GetInstance().Insert(perm, tokenId); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, "permission %{public}s has define", + TransferPermissionDefToString(perm).c_str()); + } + } +} + +void PermissionManager::RemoveDefPermissions(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u", __func__, tokenID); + std::shared_ptr tokenInfo = + AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (tokenInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params(tokenID: %{public}u)!", tokenID); + return; + } + std::string bundleName = tokenInfo->GetBundleName(); + PermissionDefinitionCache::GetInstance().DeleteByBundleName(bundleName); +} + +int PermissionManager::VerifyHapAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + std::shared_ptr tokenInfoPtr = + AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (tokenInfoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "can not find tokenInfo!"); + return PERMISSION_DENIED; + } + std::shared_ptr permPolicySet = tokenInfoPtr->GetHapInfoPermissionPolicySet(); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return PERMISSION_DENIED; + } + + return permPolicySet->VerifyPermissStatus(permissionName); +} + +int PermissionManager::VerifyNativeAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + std::shared_ptr tokenInfoPtr = + AccessTokenInfoManager::GetInstance().GetNativeTokenInfoInner(tokenID); + if (tokenInfoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "can not find tokenInfo!"); + return PERMISSION_DENIED; + } + + NativeTokenInfo info; + tokenInfoPtr->TranslateToNativeTokenInfo(info); + if (PermissionDefinitionCache::GetInstance().IsPermissionDefEmpty()) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission definition set has not been installed!"); + if (info.apl >= APL_SYSTEM_BASIC) { + return PERMISSION_GRANTED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "native process apl is %{public}d!", info.apl); + return PERMISSION_DENIED; + } + if (!tokenInfoPtr->IsRemote() && !PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); + return PERMISSION_DENIED; + } + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetNativePermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return PERMISSION_DENIED; + } + + return permPolicySet->VerifyPermissStatus(permissionName); +} + +int PermissionManager::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u, permissionName: %{public}s", __func__, + tokenID, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return PERMISSION_DENIED; + } + + ATokenTypeEnum tokenType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID); + if (tokenType == TOKEN_NATIVE) { + return VerifyNativeAccessToken(tokenID, permissionName); + } + if (tokenType == TOKEN_HAP) { + return VerifyHapAccessToken(tokenID, permissionName); + } + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenType!"); + return PERMISSION_DENIED; +} + +int PermissionManager::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: %{public}u, permissionName: %{public}s", __func__, + tokenID, permissionName.c_str()); + + PermissionDef permissionInfo; + NativeTokenInfo nativeTokenInfo; + int res = PermissionManager::GetDefPermission(permissionName, permissionInfo); + if (res != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetDefPermission in %{public}s failed", __func__); + return PERMISSION_DENIED; + } + res = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfo); + if (res != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetNativeTokenInfo in %{public}s failed", __func__); + return PERMISSION_DENIED; + } + if (permissionInfo.availableLevel > nativeTokenInfo.apl) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +int PermissionManager::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permissionName: %{public}s", __func__, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return RET_FAILED; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); + return RET_FAILED; + } + return PermissionDefinitionCache::GetInstance().FindByPermissionName(permissionName, permissionDefResult); +} + +int PermissionManager::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u", __func__, tokenID); + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return RET_FAILED; + } + + permPolicySet->GetDefPermissions(permList); + return RET_SUCCESS; +} + +int PermissionManager::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u, isSystemGrant: %{public}d", + __func__, tokenID, isSystemGrant); + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return RET_FAILED; + } + + GrantMode mode = isSystemGrant ? SYSTEM_GRANT : USER_GRANT; + std::vector tmpList; + permPolicySet->GetPermissionStateFulls(tmpList); + for (const auto& perm : tmpList) { + PermissionDef permDef; + GetDefPermission(perm.permissionName, permDef); + if (permDef.grantMode == mode) { + reqPermList.emplace_back(perm); + } + } + return RET_SUCCESS; +} + +void PermissionManager::GetSelfPermissionState(std::vector permsList, + PermissionListState &permState) +{ + bool foundGoal = false; + int32_t goalGrantStatus; + uint32_t goalGrantFlags; + for (const auto& perm : permsList) { + if (perm.permissionName == permState.permissionName) { + ACCESSTOKEN_LOG_INFO(LABEL, + "find goal permission: %{public}s!", permState.permissionName.c_str()); + foundGoal = true; + goalGrantStatus = perm.grantStatus[0]; + goalGrantFlags = static_cast(perm.grantFlags[0]); + break; + } + } + if (foundGoal == false) { + ACCESSTOKEN_LOG_WARN(LABEL, + "can not find permission: %{public}s define!", permState.permissionName.c_str()); + permState.state = INVALID_OPER; + return; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permState.permissionName)) { + ACCESSTOKEN_LOG_WARN(LABEL, + "no definition for permission: %{public}s!", permState.permissionName.c_str()); + permState.state = INVALID_OPER; + return; + } + + if (goalGrantStatus == PERMISSION_DENIED) { + if ((goalGrantFlags == PERMISSION_DEFAULT_FLAG) || + ((goalGrantFlags & PERMISSION_USER_SET) != 0)) { + permState.state = DYNAMIC_OPER; + return; + } + if ((goalGrantFlags & PERMISSION_USER_FIXED) != 0) { + permState.state = SETTING_OPER; + return; + } + } + + permState.state = PASS_OPER; + return; +} + +int PermissionManager::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u, permissionName: %{public}s", + __func__, tokenID, permissionName.c_str()); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return PERMISSION_DEFAULT_FLAG; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); + return PERMISSION_DEFAULT_FLAG; + } + std::shared_ptr permPolicySet = + AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return PERMISSION_DEFAULT_FLAG; + } + return permPolicySet->QueryPermissionFlag(permissionName); +} + +void PermissionManager::UpdateTokenPermissionState( + AccessTokenID tokenID, const std::string& permissionName, bool isGranted, int flag) +{ + std::shared_ptr infoPtr = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + if (infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote token can not update"); + return; + } + + std::shared_ptr permPolicySet = infoPtr->GetHapInfoPermissionPolicySet(); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } +#ifdef SUPPORT_SANDBOX_APP + int32_t dlpType = infoPtr->GetDlpType(); + if (isGranted && dlpType != DLP_COMMON) { + int32_t dlpMode = DlpPermissionSetManager::GetInstance().GetPermDlpMode(permissionName); + if (DlpPermissionSetManager::GetInstance().IsPermStateNeedUpdate(dlpType, dlpMode)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}u is not allowed to be granted permissionName %{public}s", + tokenID, permissionName.c_str()); + return; + } + } +#endif + bool isUpdated = permPolicySet->UpdatePermissionStatus(permissionName, isGranted, static_cast(flag)); + if (isUpdated) { + ACCESSTOKEN_LOG_INFO(LABEL, "isUpdated"); + int32_t changeType = isGranted ? GRANTED : REVOKED; + CallbackManager::GetInstance().ExecuteCallbackAsync(tokenID, permissionName, changeType); + } + +#ifdef TOKEN_SYNC_ENABLE + TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID); +#endif +} + +void PermissionManager::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: %{public}u, permissionName: %{public}s, flag: %{public}d", + __func__, tokenID, permissionName.c_str(), flag); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); + return; + } + if (!PermissionValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + UpdateTokenPermissionState(tokenID, permissionName, true, flag); +} + +void PermissionManager::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s called, tokenID: %{public}u, permissionName: %{public}s, flag: %{public}d", + __func__, tokenID, permissionName.c_str(), flag); + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); + return; + } + if (!PermissionValidator::IsPermissionFlagValid(flag)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + UpdateTokenPermissionState(tokenID, permissionName, false, flag); +} + +int32_t PermissionManager::AddPermStateChangeCallback( + const PermStateChangeScope& scope, const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + auto callbackScopePtr = std::make_shared(scope); + if (callbackScopePtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "callbackScopePtr is nullptr"); + } + + return CallbackManager::GetInstance().AddCallback(callbackScopePtr, callback); +} + +int32_t PermissionManager::RemovePermStateChangeCallback(const sptr& callback) +{ + return CallbackManager::GetInstance().RemoveCallback(callback); +} + +void PermissionManager::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u", __func__, tokenID); + std::shared_ptr infoPtr = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + if (infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote token can not clear."); + return; + } + + std::shared_ptr permPolicySet = infoPtr->GetHapInfoPermissionPolicySet(); + if (permPolicySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); + return; + } + + permPolicySet->ResetUserGrantPermissionStatus(); +} + +std::string PermissionManager::TransferPermissionDefToString(const PermissionDef& inPermissionDef) +{ + std::string infos; + infos.append(R"({"permissionName": ")" + inPermissionDef.permissionName + R"(")"); + infos.append(R"(, "bundleName": ")" + inPermissionDef.bundleName + R"(")"); + infos.append(R"(, "grantMode": )" + std::to_string(inPermissionDef.grantMode)); + infos.append(R"(, "availableLevel": )" + std::to_string(inPermissionDef.availableLevel)); + infos.append(R"(, "provisionEnable": )" + std::to_string(inPermissionDef.provisionEnable)); + infos.append(R"(, "distributedSceneEnable": )" + std::to_string(inPermissionDef.distributedSceneEnable)); + infos.append(R"(, "label": ")" + inPermissionDef.label + R"(")"); + infos.append(R"(, "labelId": )" + std::to_string(inPermissionDef.labelId)); + infos.append(R"(, "description": ")" + inPermissionDef.description + R"(")"); + infos.append(R"(, "descriptionId": )" + std::to_string(inPermissionDef.descriptionId)); + infos.append("}"); + return infos; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp new file mode 100644 index 000000000..c0b766dde --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp @@ -0,0 +1,373 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_policy_set.h" + +#include "accesstoken_log.h" +#include "data_storage.h" +#include "data_translator.h" +#include "field_const.h" +#include "permission_definition_cache.h" +#include "permission_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermissionPolicySet"}; +} + +PermissionPolicySet::~PermissionPolicySet() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, + "%{public}s called, tokenID: 0x%{public}x destruction", __func__, tokenId_); +} + +std::shared_ptr PermissionPolicySet::BuildPermissionPolicySet( + AccessTokenID tokenId, const std::vector& permStateList) +{ + std::shared_ptr policySet = std::make_shared(); + if (policySet != nullptr) { + PermissionValidator::FilterInvalidPermissionState(permStateList, policySet->permStateList_); + policySet->tokenId_ = tokenId; + } + return policySet; +} + +void PermissionPolicySet::UpdatePermStateFull(const PermissionStateFull& permOld, PermissionStateFull& permNew) +{ + if (permNew.isGeneral == permOld.isGeneral) { + permNew.resDeviceID = permOld.resDeviceID; + permNew.grantStatus = permOld.grantStatus; + permNew.grantFlags = permOld.grantFlags; + } +} + +void PermissionPolicySet::Update(const std::vector& permStateList) +{ + std::vector permStateFilterList; + PermissionValidator::FilterInvalidPermissionState(permStateList, permStateFilterList); + + Utils::UniqueWriteGuard infoGuard(this->permPolicySetLock_); + for (PermissionStateFull& permStateNew : permStateFilterList) { + for (const PermissionStateFull& permStateOld : permStateList_) { + if (permStateNew.permissionName == permStateOld.permissionName) { + UpdatePermStateFull(permStateOld, permStateNew); + break; + } + } + } + permStateList_ = permStateFilterList; +} + +std::shared_ptr PermissionPolicySet::RestorePermissionPolicy(AccessTokenID tokenId, + const std::vector& permStateRes) +{ + std::shared_ptr policySet = std::make_shared(); + if (policySet == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x new failed.", tokenId); + return nullptr; + } + policySet->tokenId_ = tokenId; + + for (const GenericValues& stateValue : permStateRes) { + if ((AccessTokenID)stateValue.GetInt(FIELD_TOKEN_ID) == tokenId) { + PermissionStateFull state; + int ret = DataTranslator::TranslationIntoPermissionStateFull(stateValue, state); + if (ret == RET_SUCCESS) { + MergePermissionStateFull(policySet->permStateList_, state); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x permState is wrong.", tokenId); + } + } + } + return policySet; +} + +void PermissionPolicySet::MergePermissionStateFull(std::vector& permStateList, + const PermissionStateFull& state) +{ + for (auto iter = permStateList.begin(); iter != permStateList.end(); iter++) { + if (state.permissionName == iter->permissionName) { + iter->resDeviceID.emplace_back(state.resDeviceID[0]); + iter->grantStatus.emplace_back(state.grantStatus[0]); + iter->grantFlags.emplace_back(state.grantFlags[0]); + return; + } + } + permStateList.emplace_back(state); +} + +void PermissionPolicySet::StorePermissionState(std::vector& valueList) const +{ + for (const auto& permissionState : permStateList_) { + if (permissionState.isGeneral) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, (int)tokenId_); + DataTranslator::TranslationIntoGenericValues(permissionState, 0, genericValues); + valueList.emplace_back(genericValues); + continue; + } + + unsigned int stateSize = permissionState.resDeviceID.size(); + for (unsigned int i = 0; i < stateSize; i++) { + GenericValues genericValues; + genericValues.Put(FIELD_TOKEN_ID, (int)tokenId_); + DataTranslator::TranslationIntoGenericValues(permissionState, i, genericValues); + valueList.emplace_back(genericValues); + } + } +} + +void PermissionPolicySet::StorePermissionPolicySet(std::vector& permStateValueList) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + StorePermissionState(permStateValueList); +} + +int PermissionPolicySet::VerifyPermissStatus(const std::string& permissionName) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + for (const auto& perm : permStateList_) { + if (perm.permissionName == permissionName) { + if (perm.isGeneral) { + return perm.grantStatus[0]; + } else { + return PERMISSION_DENIED; + } + } + } + return PERMISSION_DENIED; +} + +void PermissionPolicySet::GetDefPermissions(std::vector& permList) +{ + PermissionDefinitionCache::GetInstance().GetDefPermissionsByTokenId(permList, tokenId_); +} + +void PermissionPolicySet::GetPermissionStateFulls(std::vector& permList) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + permList.assign(permStateList_.begin(), permStateList_.end()); +} + +int PermissionPolicySet::QueryPermissionFlag(const std::string& permissionName) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + for (const auto& perm : permStateList_) { + if (perm.permissionName == permissionName) { + if (perm.isGeneral) { + uint32_t oldFlag = static_cast(perm.grantFlags[0]); + uint32_t unmaskedFlag = (oldFlag) & (~PERMISSION_GRANTED_BY_POLICY); + return static_cast(unmaskedFlag); + } else { + return PERMISSION_DEFAULT_FLAG; + } + } + } + return PERMISSION_DEFAULT_FLAG; +} + +bool PermissionPolicySet::UpdatePermissionStatus(const std::string& permissionName, bool isGranted, uint32_t flag) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "permissionName %{public}s.", permissionName.c_str()); + + bool ret = false; + Utils::UniqueWriteGuard infoGuard(this->permPolicySetLock_); + for (auto& perm : permStateList_) { + if (perm.permissionName == permissionName) { + if (perm.isGeneral) { + int32_t oldStatus = perm.grantStatus[0]; + perm.grantStatus[0] = isGranted ? PERMISSION_GRANTED : PERMISSION_DENIED; + uint32_t currFlag = static_cast(perm.grantFlags[0]); + uint32_t newFlag = flag | (currFlag & PERMISSION_GRANTED_BY_POLICY); + perm.grantFlags[0] = static_cast(newFlag); + ret = (oldStatus == perm.grantStatus[0]) ? false : true; + } else { + ACCESSTOKEN_LOG_WARN(LABEL, "perm isGeneral is false."); + } + break; + } + } + + return ret; +} + +void PermissionPolicySet::ResetUserGrantPermissionStatus(void) +{ + Utils::UniqueWriteGuard infoGuard(this->permPolicySetLock_); + for (auto& perm : permStateList_) { + if (perm.isGeneral) { + uint32_t oldFlag = static_cast(perm.grantFlags[0]); + if ((oldFlag & PERMISSION_SYSTEM_FIXED) != 0) { + continue; + } + if ((oldFlag & PERMISSION_GRANTED_BY_POLICY) != 0) { + perm.grantStatus[0] = PERMISSION_GRANTED; + perm.grantFlags[0] = PERMISSION_GRANTED_BY_POLICY; + continue; + } + perm.grantStatus[0] = PERMISSION_DENIED; + perm.grantFlags[0] = PERMISSION_DEFAULT_FLAG; + } else { + continue; + } + } +} + +void PermissionPolicySet::GetPermissionStateList(std::vector& stateList) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + for (const auto& state : permStateList_) { + stateList.emplace_back(state); + } +} + +void PermissionPolicySet::PermDefToString(const PermissionDef& def, std::string& info) const +{ + info.append(R"( {)"); + info.append("\n"); + info.append(R"( "permissionName": ")" + def.permissionName + R"(")" + ",\n"); + info.append(R"( "bundleName": ")" + def.bundleName + R"(")" + ",\n"); + info.append(R"( "grantMode": )" + std::to_string(def.grantMode) + ",\n"); + info.append(R"( "availableLevel": )" + std::to_string(def.availableLevel) + ",\n"); + info.append(R"( "provisionEnable": )" + std::to_string(def.provisionEnable) + ",\n"); + info.append(R"( "distributedSceneEnable": )" + std::to_string(def.distributedSceneEnable) + ",\n"); + info.append(R"( "label": ")" + def.label + R"(")" + ",\n"); + info.append(R"( "labelId": )" + std::to_string(def.labelId) + ",\n"); + info.append(R"( "description": ")" + def.description + R"(")" + ",\n"); + info.append(R"( "descriptionId": )" + std::to_string(def.descriptionId) + ",\n"); + info.append(R"( })"); +} + +void PermissionPolicySet::PermStateFullToString(const PermissionStateFull& state, std::string& info) const +{ + info.append(R"( {)"); + info.append("\n"); + info.append(R"( "permissionName": ")" + state.permissionName + R"(")" + ",\n"); + info.append(R"( "isGeneral": )" + std::to_string(state.isGeneral) + ",\n"); + info.append(R"( "resDeviceIDList": [ )"); + for (auto iter = state.resDeviceID.begin(); iter != state.resDeviceID.end(); iter++) { + info.append("\n"); + info.append(R"( { "resDeviceID": ")" + *iter + R"(")" + " }"); + if (iter != (state.resDeviceID.end() - 1)) { + info.append(","); + } + } + info.append("\n ],\n"); + + info.append(R"( "grantStatusList": [)"); + for (auto iter = state.grantStatus.begin(); iter != state.grantStatus.end(); iter++) { + info.append("\n"); + info.append(R"( { "grantStatus": )" + std::to_string(*iter) + " }"); + if (iter != (state.grantStatus.end() - 1)) { + info.append(","); + } + } + info.append("\n ],\n"); + + info.append(R"( "grantFlagsList": [)"); + for (auto iter = state.grantFlags.begin(); iter != state.grantFlags.end(); iter++) { + info.append("\n"); + info.append(R"( { "grantFlag": )" + std::to_string(*iter) + " }"); + if (iter != (state.grantFlags.end() - 1)) { + info.append(","); + } + } + info.append("\n ],\n"); + + info.append(R"( })"); +} + +void PermissionPolicySet::ToString(std::string& info) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + info.append(R"( "permDefList": [)"); + info.append("\n"); + std::vector permList; + PermissionDefinitionCache::GetInstance().GetDefPermissionsByTokenId(permList, tokenId_); + for (auto iter = permList.begin(); iter != permList.end(); iter++) { + PermDefToString(*iter, info); + if (iter != (permList.end() - 1)) { + info.append(",\n"); + } + } + info.append("\n ],\n"); + + info.append(R"( "permStateList": [)"); + info.append("\n"); + for (auto iter = permStateList_.begin(); iter != permStateList_.end(); iter++) { + PermStateFullToString(*iter, info); + if (iter != (permStateList_.end() - 1)) { + info.append(",\n"); + } + } + info.append("\n ]\n"); +} + +bool PermissionPolicySet::IsPermissionReqValid(int32_t tokenApl, const std::string& permissionName, + const std::vector& nativeAcls) +{ + PermissionDef permissionDef; + int ret = PermissionDefinitionCache::GetInstance().FindByPermissionName( + permissionName, permissionDef); + if (ret != RET_SUCCESS) { + return false; + } + if (tokenApl >= permissionDef.availableLevel) { + return true; + } + + auto iter = std::find(nativeAcls.begin(), nativeAcls.end(), permissionName); + if (iter != nativeAcls.end()) { + return true; + } + return false; +} + +void PermissionPolicySet::PermStateToString(int32_t tokenApl, + const std::vector& nativeAcls, std::string& info) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + + std::vector invalidPermList = {}; + info.append(R"( "permStateList": [)"); + info.append("\n"); + for (auto iter = permStateList_.begin(); iter != permStateList_.end(); iter++) { + if (!IsPermissionReqValid(tokenApl, iter->permissionName, nativeAcls)) { + invalidPermList.emplace_back(iter->permissionName); + continue; + } + PermStateFullToString(*iter, info); + if (iter != (permStateList_.end() - 1)) { + info.append(",\n"); + } + } + info.append("\n ]\n"); + + if (invalidPermList.empty()) { + return; + } + + info.append(R"( "invalidPermList": [)"); + info.append("\n"); + for (auto iter = invalidPermList.begin(); iter != invalidPermList.end(); iter++) { + info.append(R"( "permissionName": ")" + *iter + R"(")" + ",\n"); + } + info.append("\n ]\n"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp new file mode 100644 index 000000000..83c5af20f --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "permission_validator.h" + +#include + +#include "access_token.h" +#include "data_validator.h" +#include "permission_definition_cache.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool PermissionValidator::IsGrantModeValid(int grantMode) +{ + return grantMode == GrantMode::SYSTEM_GRANT || grantMode == GrantMode::USER_GRANT; +} + +bool PermissionValidator::IsGrantStatusValid(int grantStaus) +{ + return grantStaus == PermissionState::PERMISSION_GRANTED || grantStaus == PermissionState::PERMISSION_DENIED; +} + +bool PermissionValidator::IsPermissionFlagValid(int flag) +{ + return DataValidator::IsPermissionFlagValid(flag); +} + +bool PermissionValidator::IsPermissionNameValid(const std::string& permissionName) +{ + return DataValidator::IsPermissionNameValid(permissionName); +} + +bool PermissionValidator::IsPermissionDefValid(const PermissionDef& permDef) +{ + if (!DataValidator::IsLabelValid(permDef.label)) { + return false; + } + if (!DataValidator::IsDescValid(permDef.description)) { + return false; + } + if (!DataValidator::IsBundleNameValid(permDef.bundleName)) { + return false; + } + if (!DataValidator::IsPermissionNameValid(permDef.permissionName)) { + return false; + } + if (!IsGrantModeValid(permDef.grantMode)) { + return false; + } + return DataValidator::IsAplNumValid(permDef.availableLevel); +} + +bool PermissionValidator::IsPermissionStateValid(const PermissionStateFull& permState) +{ + if (!DataValidator::IsPermissionNameValid(permState.permissionName)) { + return false; + } + + size_t resDevIdSize = permState.resDeviceID.size(); + size_t grantStatSize = permState.grantStatus.size(); + size_t grantFlagSize = permState.grantFlags.size(); + if ((grantStatSize != resDevIdSize) || (grantFlagSize != resDevIdSize)) { + return false; + } + + for (uint32_t i = 0; i < resDevIdSize; i++) { + if (!IsGrantStatusValid(permState.grantStatus[i]) || + !IsPermissionFlagValid(permState.grantFlags[i])) { + return false; + } + } + return true; +} + + +void PermissionValidator::FilterInvalidPermissionDef( + const std::vector& permList, std::vector& result) +{ + std::set permDefSet; + for (auto it = permList.begin(); it != permList.end(); ++it) { + std::string permName = it->permissionName; + if (!IsPermissionDefValid(*it) || permDefSet.count(permName) != 0) { + continue; + } + permDefSet.insert(permName); + result.emplace_back(*it); + } +} + +void PermissionValidator::DeduplicateResDevID(const PermissionStateFull& permState, PermissionStateFull& result) +{ + std::set resDevId; + auto stateIter = permState.grantStatus.begin(); + auto flagIter = permState.grantFlags.begin(); + for (auto it = permState.resDeviceID.begin(); it != permState.resDeviceID.end(); ++it, ++stateIter, ++flagIter) { + if (resDevId.count(*it) != 0) { + continue; + } + resDevId.insert(*it); + result.resDeviceID.emplace_back(*it); + result.grantStatus.emplace_back(*stateIter); + result.grantFlags.emplace_back(*flagIter); + } + result.permissionName = permState.permissionName; + result.isGeneral = permState.isGeneral; +} + +void PermissionValidator::FilterInvalidPermissionState( + const std::vector& permList, std::vector& result) +{ + std::set permStateSet; + for (auto it = permList.begin(); it != permList.end(); ++it) { + std::string permName = it->permissionName; + PermissionStateFull res; + if (!IsPermissionStateValid(*it) || permStateSet.count(permName) != 0) { + continue; + } + DeduplicateResDevID(*it, res); + permStateSet.insert(permName); + result.emplace_back(res); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp new file mode 100644 index 000000000..974b71c1c --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -0,0 +1,466 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_service.h" + +#include + +#include "access_token.h" +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#ifdef TOKEN_SYNC_ENABLE +#include "atm_device_state_callback.h" +#include "device_manager.h" +#endif +#include "constant_common.h" +#ifdef SUPPORT_SANDBOX_APP +#include "dlp_permission_set_parser.h" +#endif +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "ipc_skeleton.h" +#include "native_token_info_inner.h" +#include "native_token_receptor.h" +#include "permission_list_state.h" +#include "permission_manager.h" +#include "privacy_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerService" +}; +} + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +AccessTokenManagerService::AccessTokenManagerService() + : SystemAbility(SA_ID_ACCESSTOKEN_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService()"); +} + +AccessTokenManagerService::~AccessTokenManagerService() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "~AccessTokenManagerService()"); +} + +void AccessTokenManagerService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService has already started!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "AccessTokenManagerService is starting"); + if (!Initialize()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, AccessTokenManagerService start successfully!"); +} + +void AccessTokenManagerService::OnStop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "stop service"); + state_ = ServiceRunningState::STATE_NOT_START; +#ifdef TOKEN_SYNC_ENABLE + DestroyDeviceListenner(); +#endif +} + +int AccessTokenManagerService::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + int32_t res = PermissionManager::GetInstance().VerifyAccessToken(tokenID, permissionName); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenID: %{public}d, permissionName: %{public}s, res %{public}d", + tokenID, permissionName.c_str(), res); + return res; +} + +int AccessTokenManagerService::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, permissionName: %{public}s", + tokenID, permissionName.c_str()); + return PermissionManager::GetInstance().VerifyNativeToken(tokenID, permissionName); +} + +int AccessTokenManagerService::GetDefPermission( + const std::string& permissionName, PermissionDefParcel& permissionDefResult) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, permissionName: %{public}s", permissionName.c_str()); + return PermissionManager::GetInstance().GetDefPermission(permissionName, permissionDefResult.permissionDef); +} + +int AccessTokenManagerService::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + std::vector permVec; + int ret = PermissionManager::GetInstance().GetDefPermissions(tokenID, permVec); + for (const auto& perm : permVec) { + PermissionDefParcel permPrcel; + permPrcel.permissionDef = perm; + permList.emplace_back(permPrcel); + } + return ret; +} + +int AccessTokenManagerService::GetReqPermissions( + AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, isSystemGrant: %{public}d", tokenID, isSystemGrant); + + std::vector permList; + int ret = PermissionManager::GetInstance().GetReqPermissions(tokenID, permList, isSystemGrant); + + for (const auto& perm : permList) { + PermissionStateFullParcel permPrcel; + permPrcel.permStatFull = perm; + reqPermList.emplace_back(permPrcel); + } + return ret; +} + +PermissionOper AccessTokenManagerService::GetSelfPermissionsState( + std::vector& reqPermList) +{ + AccessTokenID callingTokenID = IPCSkeleton::GetCallingTokenID(); + ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}d", callingTokenID); + + bool needRes = false; + std::vector permsList; + int retUserGrant = PermissionManager::GetInstance().GetReqPermissions(callingTokenID, permsList, false); + int retSysGrant = PermissionManager::GetInstance().GetReqPermissions(callingTokenID, permsList, true); + if ((retSysGrant != RET_SUCCESS) || (retUserGrant != RET_SUCCESS)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "GetReqPermissions failed, retUserGrant:%{public}d, retSysGrant:%{public}d", + retUserGrant, retSysGrant); + return INVALID_OPER; + } + + uint32_t size = reqPermList.size(); + for (uint32_t i = 0; i < size; i++) { + PermissionManager::GetInstance().GetSelfPermissionState( + permsList, reqPermList[i].permsState); + if (reqPermList[i].permsState.state == DYNAMIC_OPER) { + needRes = true; + } + ACCESSTOKEN_LOG_INFO(LABEL, "perm: 0x%{public}s, state: 0x%{public}d", + reqPermList[i].permsState.permissionName.c_str(), reqPermList[i].permsState.state); + } + if (needRes) { + return DYNAMIC_OPER; + } + return PASS_OPER; +} + +int AccessTokenManagerService::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, permissionName: %{public}s", + tokenID, permissionName.c_str()); + return PermissionManager::GetInstance().GetPermissionFlag(tokenID, permissionName); +} + +int AccessTokenManagerService::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", + tokenID, permissionName.c_str(), flag); + PermissionManager::GetInstance().GrantPermission(tokenID, permissionName, flag); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenManagerService::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", + tokenID, permissionName.c_str(), flag); + PermissionManager::GetInstance().RevokePermission(tokenID, permissionName, flag); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenManagerService::ClearUserGrantedPermissionState(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + PermissionManager::GetInstance().ClearUserGrantedPermissionState(tokenID); + AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); + PrivacyKit::RemovePermissionUsedRecords(tokenID, ""); + return RET_SUCCESS; +} + +int32_t AccessTokenManagerService::RegisterPermStateChangeCallback( + const PermStateChangeScopeParcel& scope, const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Entry"); + return PermissionManager::GetInstance().AddPermStateChangeCallback(scope.scope, callback); +} + +int32_t AccessTokenManagerService::UnRegisterPermStateChangeCallback(const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Entry"); + return PermissionManager::GetInstance().RemovePermStateChangeCallback(callback); +} + +AccessTokenIDEx AccessTokenManagerService::AllocHapToken(const HapInfoParcel& info, const HapPolicyParcel& policy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called!"); + AccessTokenIDEx tokenIdEx; + tokenIdEx.tokenIDEx = 0LL; + + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( + info.hapInfoParameter, policy.hapPolicyParameter, tokenIdEx); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, "hap token info create failed"); + } + return tokenIdEx; +} + +int AccessTokenManagerService::DeleteToken(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenID, ""); + // only support hap token deletion + return AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); +} + +int AccessTokenManagerService::GetTokenType(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + return AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID); +} + +int AccessTokenManagerService::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x, dcap: %{public}s", + tokenID, dcap.c_str()); + return AccessTokenInfoManager::GetInstance().CheckNativeDCap(tokenID, dcap); +} + +AccessTokenID AccessTokenManagerService::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, userID: %{public}d, bundleName: %{public}s, instIndex: %{public}d", + userID, bundleName.c_str(), instIndex); + return AccessTokenInfoManager::GetInstance().GetHapTokenID(userID, bundleName, instIndex); +} + +AccessTokenID AccessTokenManagerService::AllocLocalTokenID( + const std::string& remoteDeviceID, AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, remoteDeviceID: %{public}s, remoteTokenID: %{public}d", + ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); + return AccessTokenInfoManager::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); +} + +int AccessTokenManagerService::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + + return AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenID, appIDDesc, apiVersion, + policyParcel.hapPolicyParameter); +} + +int AccessTokenManagerService::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + + return AccessTokenInfoManager::GetInstance().GetHapTokenInfo(tokenID, InfoParcel.hapTokenInfoParams); +} + +int AccessTokenManagerService::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& InfoParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + + return AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(tokenID, InfoParcel.nativeTokenInfoParams); +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenManagerService::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); + + return AccessTokenInfoManager::GetInstance().GetHapTokenInfoFromRemote(tokenID, + hapSyncParcel.hapTokenInfoForSyncParams); +} + +int AccessTokenManagerService::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + + std::vector nativeVec; + AccessTokenInfoManager::GetInstance().GetAllNativeTokenInfo(nativeVec); + for (const auto& native : nativeVec) { + NativeTokenInfoForSyncParcel nativeParcel; + nativeParcel.nativeTokenInfoForSyncParams = native; + nativeTokenInfosRes.emplace_back(nativeParcel); + } + + return RET_SUCCESS; +} + +int AccessTokenManagerService::SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); + + return AccessTokenInfoManager::GetInstance().SetRemoteHapTokenInfo(deviceID, + hapSyncParcel.hapTokenInfoForSyncParams); +} + +int AccessTokenManagerService::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoForSyncParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); + + std::vector nativeList; + + for (const auto& nativeParcel : nativeTokenInfoForSyncParcel) { + nativeList.emplace_back(nativeParcel.nativeTokenInfoForSyncParams); + } + + return AccessTokenInfoManager::GetInstance().SetRemoteNativeTokenInfo(deviceID, nativeList); +} + +int AccessTokenManagerService::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s, token id %{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + + return AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceID, tokenID); +} + +AccessTokenID AccessTokenManagerService::GetRemoteNativeTokenID(const std::string& deviceID, + AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s, token id %{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + + return AccessTokenInfoManager::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); +} + +int AccessTokenManagerService::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called, deviceID: %{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); + + return AccessTokenInfoManager::GetInstance().DeleteRemoteDeviceTokens(deviceID); +} +#endif + +void AccessTokenManagerService::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + + AccessTokenInfoManager::GetInstance().DumpTokenInfo(tokenID, dumpInfo); +} +#ifdef TOKEN_SYNC_ENABLE +void AccessTokenManagerService::CreateDeviceListenner() +{ + static const int32_t RETRY_SLEEP_TIME_MS = 1000; + std::function runner = [&]() { + auto retrySleepTime = std::chrono::milliseconds(RETRY_SLEEP_TIME_MS); + while (1) { + std::unique_lock lock(mutex_); + + std::string packageName = ACCESS_TOKEN_PACKAGE_NAME; + std::shared_ptr ptrDmInitCallback = std::make_shared(); + + int32_t ret = + DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(packageName, ptrDmInitCallback); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret); + std::this_thread::sleep_for(retrySleepTime); + continue; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "device manager init success."); + + std::string extra = ""; + std::shared_ptr ptrAtmDeviceStateCallback = + std::make_shared(); + ret = DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(packageName, extra, + ptrAtmDeviceStateCallback); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: RegisterDevStateCallback error, result: %{public}d", ret); + std::this_thread::sleep_for(retrySleepTime); + continue; + } + + isListened_ = true; + + ACCESSTOKEN_LOG_INFO(LABEL, "device state listenner register success."); + + return; + } + }; + + std::thread initThread(runner); + initThread.detach(); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "start a thread to listen device state."); +} + +void AccessTokenManagerService::DestroyDeviceListenner() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, init: %{public}d", isListened_); + + std::unique_lock lock(mutex_); + + if (!isListened_) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "not listened, skip"); + return; + } + + std::string packageName = ACCESS_TOKEN_PACKAGE_NAME; + + int32_t ret = DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(packageName); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnRegisterDevStateCallback failed, code: %{public}d", ret); + } + + ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(packageName); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret); + } + + isListened_ = false; + + ACCESSTOKEN_LOG_INFO(LABEL, "device state listenner unregister success."); +} +#endif + +bool AccessTokenManagerService::Initialize() +{ + AccessTokenInfoManager::GetInstance().Init(); + NativeTokenReceptor::GetInstance().Init(); +#ifdef TOKEN_SYNC_ENABLE + CreateDeviceListenner(); // for start tokensync when remote devivce online +#endif +#ifdef SUPPORT_SANDBOX_APP + DlpPermissionSetParser::GetInstance().Init(); +#endif + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp new file mode 100644 index 000000000..766939fa6 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_manager_stub.h" + +#include +#include "accesstoken_log.h" +#include "ipc_skeleton.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenManagerStub"}; +constexpr int32_t FOUNDATION_UID = 5523; +} + +int32_t AccessTokenManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, code: %{public}u", __func__, code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != IAccessTokenManager::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return -1; + } + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + (this->*requestFunc)(data, reply); + } else { + // when valid code without any function to handle + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); // when code invalid + } + + return NO_ERROR; +} + +void AccessTokenManagerStub::DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + int result = this->DeleteToken(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::VerifyAccessTokenInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int result = this->VerifyAccessToken(tokenID, permissionName); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::VerifyNativeTokenInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int result = this->VerifyNativeToken(tokenID, permissionName); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetDefPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + std::string permissionName = data.ReadString(); + PermissionDefParcel permissionDefParcel; + int result = this->GetDefPermission(permissionName, permissionDefParcel); + reply.WriteParcelable(&permissionDefParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetDefPermissionsInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + std::vector permList; + + int result = this->GetDefPermissions(tokenID, permList); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permList.size()); + reply.WriteInt32((int32_t)permList.size()); + for (const auto& permDef : permList) { + reply.WriteParcelable(&permDef); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetReqPermissionsInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + int isSystemGrant = data.ReadInt32(); + std::vector permList; + + int result = this->GetReqPermissions(tokenID, permList, isSystemGrant); + ACCESSTOKEN_LOG_INFO(LABEL, "permList size: %{public}d", (int) permList.size()); + reply.WriteInt32((int32_t)permList.size()); + for (const auto& permDef : permList) { + reply.WriteParcelable(&permDef); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetSelfPermissionsStateInner(MessageParcel& data, MessageParcel& reply) +{ + std::vector permList; + uint32_t size = data.ReadUint32(); + ACCESSTOKEN_LOG_INFO(LABEL, "permList size read from client data is %{public}d.", size); + if (size > MAX_PERMISSION_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permList size %{public}d is invalid", size); + reply.WriteInt32(INVALID_OPER); + return; + } + for (uint32_t i = 0; i < size; i++) { + sptr permissionParcel = data.ReadParcelable(); + if (permissionParcel != nullptr) { + permList.emplace_back(*permissionParcel); + } + } + + PermissionOper result = this->GetSelfPermissionsState(permList); + + reply.WriteInt32(result); + + reply.WriteUint32(permList.size()); + for (const auto& perm : permList) { + reply.WriteParcelable(&perm); + } +} + +void AccessTokenManagerStub::GetPermissionFlagInner(MessageParcel& data, MessageParcel& reply) +{ + unsigned int callingTokenID = IPCSkeleton::GetCallingTokenID(); + ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}u", callingTokenID); + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + if (!IsAuthorizedCalling() && + VerifyAccessToken(callingTokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED && + VerifyAccessToken(callingTokenID, "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED && + VerifyAccessToken(callingTokenID, "ohos.permission.GET_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(PERMISSION_DEFAULT_FLAG); + return; + } + int result = this->GetPermissionFlag(tokenID, permissionName); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GrantPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + unsigned int callingTokenID = IPCSkeleton::GetCallingTokenID(); + ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}d", callingTokenID); + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int flag = data.ReadInt32(); + if (!IsAuthorizedCalling() && + VerifyAccessToken(callingTokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(RET_FAILED); + return; + } + int result = this->GrantPermission(tokenID, permissionName, flag); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::RevokePermissionInner(MessageParcel& data, MessageParcel& reply) +{ + unsigned int callingTokenID = IPCSkeleton::GetCallingTokenID(); + ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}d", callingTokenID); + AccessTokenID tokenID = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int flag = data.ReadInt32(); + if (!IsAuthorizedCalling() && + VerifyAccessToken(callingTokenID, "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(RET_FAILED); + return; + } + int result = this->RevokePermission(tokenID, permissionName, flag); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::ClearUserGrantedPermissionStateInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + int result = this->ClearUserGrantedPermissionState(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::AllocHapTokenInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenIDEx res = {0}; + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + + sptr hapInfoParcel = data.ReadParcelable(); + sptr hapPolicyParcel = data.ReadParcelable(); + if (hapInfoParcel == nullptr || hapPolicyParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read hapPolicyParcel or hapInfoParcel fail"); + reply.WriteInt32(RET_FAILED); + return; + } + res = this->AllocHapToken(*hapInfoParcel, *hapPolicyParcel); + reply.WriteUint64(res.tokenIDEx); +} + +void AccessTokenManagerStub::GetTokenTypeInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenID = data.ReadUint32(); + int result = this->GetTokenType(tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string dCap = data.ReadString(); + int result = this->CheckNativeDCap(tokenID, dCap); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(INVALID_TOKENID); + return; + } + int userID = data.ReadInt32(); + std::string bundleName = data.ReadString(); + int instIndex = data.ReadInt32(); + AccessTokenID result = this->GetHapTokenID(userID, bundleName, instIndex); + reply.WriteUint32(result); +} + +void AccessTokenManagerStub::AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if ((!IsAuthorizedCalling()) && (this->GetTokenType(tokenCaller) != TOKEN_NATIVE)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(INVALID_TOKENID); + return; + } + std::string remoteDeviceID = data.ReadString(); + AccessTokenID remoteTokenID = data.ReadUint32(); + AccessTokenID result = this->AllocLocalTokenID(remoteDeviceID, remoteTokenID); + reply.WriteUint32(result); +} + +void AccessTokenManagerStub::UpdateHapTokenInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string appIDDesc = data.ReadString(); + int32_t apiVersion = data.ReadInt32(); + sptr policyParcel = data.ReadParcelable(); + if (policyParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "policyParcel read faild"); + reply.WriteInt32(RET_FAILED); + return; + } + int32_t result = this->UpdateHapToken(tokenID, appIDDesc, apiVersion, *policyParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if ((this->GetTokenType(tokenCaller) != TOKEN_NATIVE)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + HapTokenInfoParcel hapTokenInfoParcel; + AccessTokenID tokenID = data.ReadUint32(); + int result = this->GetHapTokenInfo(tokenID, hapTokenInfoParcel); + reply.WriteParcelable(&hapTokenInfoParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + NativeTokenInfoParcel nativeTokenInfoParcel; + int result = this->GetNativeTokenInfo(tokenID, nativeTokenInfoParcel); + reply.WriteParcelable(&nativeTokenInfoParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::RegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply) +{ + sptr scopeParcel = data.ReadParcelable(); + if (scopeParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read scopeParcel fail"); + reply.WriteInt32(RET_FAILED); + return; + } + sptr callback = data.ReadRemoteObject(); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read callback fail"); + reply.WriteInt32(RET_FAILED); + return; + } + int32_t result = this->RegisterPermStateChangeCallback(*scopeParcel, callback); + reply.WriteInt32(result); +} +void AccessTokenManagerStub::UnRegisterPermStateChangeCallbackInner(MessageParcel& data, MessageParcel& reply) +{ + sptr callback = data.ReadRemoteObject(); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read callback fail"); + reply.WriteInt32(RET_FAILED); + return; + } + int32_t result = this->UnRegisterPermStateChangeCallback(callback); + reply.WriteInt32(result); +} + +#ifdef TOKEN_SYNC_ENABLE +void AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + HapTokenInfoForSyncParcel hapTokenParcel; + + int result = this->GetHapTokenInfoFromRemote(tokenID, hapTokenParcel); + reply.WriteParcelable(&hapTokenParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetAllNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::vector nativeTokenInfosRes; + int result = this->GetAllNativeTokenInfo(nativeTokenInfosRes); + reply.WriteUint32(nativeTokenInfosRes.size()); + for (const auto& native : nativeTokenInfosRes) { + reply.WriteParcelable(&native); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::SetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + sptr hapTokenParcel = data.ReadParcelable(); + if (hapTokenParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hapTokenParcel read faild"); + reply.WriteInt32(RET_FAILED); + return; + } + int result = this->SetRemoteHapTokenInfo(deviceID, *hapTokenParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + + std::vector nativeParcelList; + uint32_t size = data.ReadUint32(); + if (size > MAX_NATIVE_TOKEN_INFO_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "size %{public}u is invalid", size); + reply.WriteInt32(RET_FAILED); + return; + } + for (uint32_t i = 0; i < size; i++) { + sptr nativeParcel = data.ReadParcelable(); + if (nativeParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nativeParcel read faild"); + reply.WriteInt32(RET_FAILED); + return; + } + nativeParcelList.emplace_back(*nativeParcel); + } + + int result = this->SetRemoteNativeTokenInfo(deviceID, nativeParcelList); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + + int result = this->DeleteRemoteToken(deviceID, tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetRemoteNativeTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(INVALID_TOKENID); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + + AccessTokenID result = this->GetRemoteNativeTokenID(deviceID, tokenID); + reply.WriteUint32(result); +} + +void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling() && !IsAccessTokenCalling()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + + int result = this->DeleteRemoteDeviceTokens(deviceID); + reply.WriteInt32(result); +} +#endif + +void AccessTokenManagerStub::DumpTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + std::string dumpInfo = ""; + this->DumpTokenInfo(tokenID, dumpInfo); + reply.WriteString(dumpInfo); +} + +bool AccessTokenManagerStub::IsAuthorizedCalling() const +{ + int callingUid = IPCSkeleton::GetCallingUid(); + ACCESSTOKEN_LOG_INFO(LABEL, "Calling uid: %{public}d", callingUid); + return callingUid == SYSTEM_UID || callingUid == ROOT_UID || callingUid == FOUNDATION_UID; +} + +bool AccessTokenManagerStub::IsAccessTokenCalling() const +{ + int callingUid = IPCSkeleton::GetCallingUid(); + return callingUid == ACCESSTOKEN_UID; +} + +AccessTokenManagerStub::AccessTokenManagerStub() +{ + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::VERIFY_ACCESSTOKEN)] = + &AccessTokenManagerStub::VerifyAccessTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::VERIFY_NATIVETOKEN)] = + &AccessTokenManagerStub::VerifyNativeTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSION)] = + &AccessTokenManagerStub::GetDefPermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSIONS)] = + &AccessTokenManagerStub::GetDefPermissionsInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_REQ_PERMISSIONS)] = + &AccessTokenManagerStub::GetReqPermissionsInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_FLAG)] = + &AccessTokenManagerStub::GetPermissionFlagInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GRANT_PERMISSION)] = + &AccessTokenManagerStub::GrantPermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::REVOKE_PERMISSION)] = + &AccessTokenManagerStub::RevokePermissionInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::CLEAR_USER_GRANT_PERMISSION)] = + &AccessTokenManagerStub::ClearUserGrantedPermissionStateInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::ALLOC_TOKEN_HAP)] = + &AccessTokenManagerStub::AllocHapTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::TOKEN_DELETE)] = + &AccessTokenManagerStub::DeleteTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_TOKEN_TYPE)] = + &AccessTokenManagerStub::GetTokenTypeInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::CHECK_NATIVE_DCAP)] = + &AccessTokenManagerStub::CheckNativeDCapInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_ID)] = + &AccessTokenManagerStub::GetHapTokenIDInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::ALLOC_LOCAL_TOKEN_ID)] = + &AccessTokenManagerStub::AllocLocalTokenIDInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_TOKENINFO)] = + &AccessTokenManagerStub::GetNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKENINFO)] = + &AccessTokenManagerStub::GetHapTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN)] = + &AccessTokenManagerStub::UpdateHapTokenInner; + +#ifdef TOKEN_SYNC_ENABLE + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_FROM_REMOTE)] = + &AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_ALL_NATIVE_TOKEN_FROM_REMOTE)] = + &AccessTokenManagerStub::GetAllNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_HAP_TOKEN_INFO)] = + &AccessTokenManagerStub::SetRemoteHapTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_NATIVE_TOKEN_INFO)] = + &AccessTokenManagerStub::SetRemoteNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_TOKEN_INFO)] = + &AccessTokenManagerStub::DeleteRemoteTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_DEVICE_TOKEN)] = + &AccessTokenManagerStub::DeleteRemoteDeviceTokensInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_REMOTE_TOKEN)] = + &AccessTokenManagerStub::GetRemoteNativeTokenIDInner; +#endif + + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DUMP_TOKENINFO)] = + &AccessTokenManagerStub::DumpTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_OPER_STATE)] = + &AccessTokenManagerStub::GetSelfPermissionsStateInner; + + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::REGISTER_PERM_STATE_CHANGE_CALLBACK)] = + &AccessTokenManagerStub::RegisterPermStateChangeCallbackInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::UNREGISTER_PERM_STATE_CHANGE_CALLBACK)] = + &AccessTokenManagerStub::UnRegisterPermStateChangeCallbackInner; +} + +AccessTokenManagerStub::~AccessTokenManagerStub() +{ + requestFuncMap_.clear(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp new file mode 100644 index 000000000..9abbe3fed --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_validator.h" +#include "random.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenIDManager"}; +} + +ATokenTypeEnum AccessTokenIDManager::GetTokenIdTypeEnum(AccessTokenID id) +{ + AccessTokenIDInner *idInner = reinterpret_cast(&id); + return (ATokenTypeEnum)idInner->type; +} + +int AccessTokenIDManager::GetTokenIdDlpFlag(AccessTokenID id) +{ + AccessTokenIDInner *idInner = reinterpret_cast(&id); + return idInner->dlpFlag; +} + +ATokenTypeEnum AccessTokenIDManager::GetTokenIdType(AccessTokenID id) +{ + { + Utils::UniqueReadGuard idGuard(this->tokenIdLock_); + if (tokenIdSet_.count(id) == 0) { + return TOKEN_INVALID; + } + } + return GetTokenIdTypeEnum(id); +} + +int AccessTokenIDManager::RegisterTokenId(AccessTokenID id, ATokenTypeEnum type) +{ + AccessTokenIDInner *idInner = reinterpret_cast(&id); + if (idInner->version != DEFAULT_TOKEN_VERSION || idInner->type != type) { + return RET_FAILED; + } + + Utils::UniqueWriteGuard idGuard(this->tokenIdLock_); + + for (std::set::iterator it = tokenIdSet_.begin(); it != tokenIdSet_.end(); ++it) { + AccessTokenID tokenId = *it; + AccessTokenIDInner *idInnerExist = reinterpret_cast(&tokenId); + if (idInnerExist->tokenUniqueID == idInner->tokenUniqueID) { + return RET_FAILED; + } + } + tokenIdSet_.insert(id); + return RET_SUCCESS; +} + +AccessTokenID AccessTokenIDManager::CreateTokenId(ATokenTypeEnum type, int dlpType) const +{ + unsigned int rand = GetRandomUint32(); + if (rand == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "get random failed"); + return 0; + } + + AccessTokenIDInner innerId = {0}; + innerId.version = DEFAULT_TOKEN_VERSION; + innerId.type = type; + innerId.res = 0; + innerId.dlpFlag = (dlpType == 0) ? 0 : 1; + innerId.tokenUniqueID = rand & TOKEN_RANDOM_MASK; + AccessTokenID tokenId = *(AccessTokenID *)&innerId; + return tokenId; +} + +AccessTokenID AccessTokenIDManager::CreateAndRegisterTokenId(ATokenTypeEnum type, int dlpType) +{ + AccessTokenID tokenId = 0; + // random maybe repeat, retry twice. + for (int i = 0; i < MAX_CREATE_TOKEN_ID_RETRY; i++) { + tokenId = CreateTokenId(type, dlpType); + if (tokenId == INVALID_TOKENID) { + ACCESSTOKEN_LOG_ERROR(LABEL, "create tokenId failed"); + return INVALID_TOKENID; + } + + int ret = RegisterTokenId(tokenId, type); + if (ret == RET_SUCCESS) { + break; + } else if (i < MAX_CREATE_TOKEN_ID_RETRY - 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "reigster tokenId failed, maybe repeat, retry"); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "reigster tokenId finally failed"); + tokenId = INVALID_TOKENID; + } + } + return tokenId; +} + +void AccessTokenIDManager::ReleaseTokenId(AccessTokenID id) +{ + Utils::UniqueWriteGuard idGuard(this->tokenIdLock_); + if (tokenIdSet_.count(id) == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "id %{public}x is not exist", id); + return; + } + tokenIdSet_.erase(id); +} + +AccessTokenIDManager& AccessTokenIDManager::GetInstance() +{ + static AccessTokenIDManager instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp new file mode 100644 index 000000000..e6ef009f3 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -0,0 +1,993 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_info_manager.h" + +#include +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "accesstoken_remote_token_manager.h" +#include "constant_common.h" +#include "data_storage.h" +#include "data_translator.h" +#include "data_validator.h" +#ifdef SUPPORT_SANDBOX_APP +#include "dlp_permission_set_manager.h" +#endif +#include "field_const.h" +#include "generic_values.h" +#include "hap_token_info_inner.h" +#include "permission_definition_cache.h" +#include "permission_manager.h" +#include "softbus_bus_center.h" + +#ifdef TOKEN_SYNC_ENABLE +#include "token_modify_notifier.h" +#include "token_sync_kit.h" +#endif + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManager"}; +} + +AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) {} + +AccessTokenInfoManager::~AccessTokenInfoManager() +{ + if (!hasInited_) { + return; + } + this->tokenDataWorker_.Stop(); + this->hasInited_ = false; +} + +void AccessTokenInfoManager::Init() +{ + OHOS::Utils::UniqueWriteGuard lk(this->managerLock_); + if (hasInited_) { + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "init begin!"); + InitHapTokenInfos(); + InitNativeTokenInfos(); + this->tokenDataWorker_.Start(1); + hasInited_ = true; + ACCESSTOKEN_LOG_INFO(LABEL, "Init success"); +} + +void AccessTokenInfoManager::InitHapTokenInfos() +{ + std::vector hapTokenRes; + std::vector permDefRes; + std::vector permStateRes; + + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_HAP_INFO, hapTokenRes); + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefRes); + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); + + for (const GenericValues& tokenValue : hapTokenRes) { + AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(FIELD_TOKEN_ID); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add id failed.", tokenId); + continue; + } + std::shared_ptr hap = std::make_shared(); + if (hap == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u alloc failed.", tokenId); + continue; + } + ret = hap->RestoreHapTokenInfo(tokenId, tokenValue, permStateRes); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u restore failed.", tokenId); + continue; + } + + ret = AddHapTokenInfo(hap); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, + " restore hap token %{public}u bundle name %{public}s user %{public}d inst %{public}d ok!", + tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex()); + } + PermissionDefinitionCache::GetInstance().RestorePermDefInfo(permDefRes); +} + +void AccessTokenInfoManager::InitNativeTokenInfos() +{ + std::vector nativeTokenResults; + std::vector permStateRes; + + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenResults); + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); + for (const GenericValues& nativeTokenValue : nativeTokenResults) { + AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(FIELD_TOKEN_ID); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_NATIVE); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId); + continue; + } + std::shared_ptr native = std::make_shared(); + if (native == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u alloc failed.", tokenId); + continue; + } + + ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue, permStateRes); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u restore failed.", tokenId); + continue; + } + + ret = AddNativeTokenInfo(native); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, + "restore native token %{public}u process name %{public}s ok!", + tokenId, native->GetProcessName().c_str()); + } +} + +std::string AccessTokenInfoManager::GetHapUniqueStr(const int& userID, + const std::string& bundleName, const int& instIndex) const +{ + return bundleName + "&" + std::to_string(userID) + "&" + std::to_string(instIndex); +} + +std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr& info) const +{ + if (info == nullptr) { + return std::string(""); + } + return GetHapUniqueStr(info->GetUserID(), info->GetBundleName(), info->GetInstIndex()); +} + +int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr& info) +{ + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null."); + return RET_FAILED; + } + AccessTokenID id = info->GetTokenID(); + + { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) > 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u info has exist.", id); + return RET_FAILED; + } + + if (!info->IsRemote()) { + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) > 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u Unique info has exist.", id); + return RET_FAILED; + } + hapTokenIdMap_[HapUniqueKey] = id; + } + hapTokenInfoMap_[id] = info; + } + return RET_SUCCESS; +} + +int AccessTokenInfoManager::AddNativeTokenInfo(const std::shared_ptr& info) +{ + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null."); + return RET_FAILED; + } + + AccessTokenID id = info->GetTokenID(); + std::string processName = info->GetProcessName(); + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u has exist.", id); + return RET_FAILED; + } + if (!info->IsRemote()) { + if (nativeTokenIdMap_.count(processName) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u process name %{public}s has exist.", id, processName.c_str()); + return RET_FAILED; + } + nativeTokenIdMap_[processName] = id; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "token info is added %{public}u.", id); + nativeTokenInfoMap_[id] = info; + + return RET_SUCCESS; +} + +std::shared_ptr AccessTokenInfoManager::GetHapTokenInfoInner(AccessTokenID id) +{ + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) != 0) { + return hapTokenInfoMap_[id]; + } + ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}u is invalid.", id); + return nullptr; +} + +int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& InfoParcel) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", tokenID); + return RET_FAILED; + } + infoPtr->TranslateToHapTokenInfo(InfoParcel); + return RET_SUCCESS; +} + +std::shared_ptr AccessTokenInfoManager::GetHapPermissionPolicySet(AccessTokenID id) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(id); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", id); + return nullptr; + } + return infoPtr->GetHapInfoPermissionPolicySet(); +} + +std::shared_ptr AccessTokenInfoManager::GetNativeTokenInfoInner(AccessTokenID id) +{ + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", id); + return nullptr; + } + return nativeTokenInfoMap_[id]; +} + +int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& InfoParcel) +{ + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", tokenID); + return RET_FAILED; + } + + infoPtr->TranslateToNativeTokenInfo(InfoParcel); + return RET_SUCCESS; +} + +std::shared_ptr AccessTokenInfoManager::GetNativePermissionPolicySet(AccessTokenID id) +{ + std::shared_ptr infoPtr = GetNativeTokenInfoInner(id); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", id); + return nullptr; + } + return infoPtr->GetNativeInfoPermissionPolicySet(); +} + +int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id) +{ + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); + if (type != TOKEN_HAP) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is not hap.", id); + return RET_FAILED; + } + + // make sure that RemoveDefPermissions is called outside of the lock to avoid deadlocks. + PermissionManager::GetInstance().RemoveDefPermissions(id); + { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u no exist.", id); + return RET_FAILED; + } + + const std::shared_ptr info = hapTokenInfoMap_[id]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u is null.", id); + return RET_FAILED; + } + if (info->IsRemote()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote hap token %{public}u can not delete.", id); + return RET_FAILED; + } + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) != 0) { + hapTokenIdMap_.erase(HapUniqueKey); + } + hapTokenInfoMap_.erase(id); + } + + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); + ACCESSTOKEN_LOG_INFO(LABEL, "remove hap token %{public}u ok!", id); + RefreshTokenInfoIfNeeded(); +#ifdef TOKEN_SYNC_ENABLE + TokenModifyNotifier::GetInstance().NotifyTokenDelete(id); +#endif + + return RET_SUCCESS; +} + +int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id) +{ + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); + if (type != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is not hap.", id); + return RET_FAILED; + } + + bool isRemote = false; + { + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(id) == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "native token %{public}u is null.", id); + return RET_FAILED; + } + + std::shared_ptr info = nativeTokenInfoMap_[id]; + if (info->IsRemote()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote native token %{public}u can not delete.", id); + return RET_FAILED; + } + std::string processName = nativeTokenInfoMap_[id]->GetProcessName(); + if (nativeTokenIdMap_.count(processName) != 0) { + nativeTokenIdMap_.erase(processName); + } + nativeTokenInfoMap_.erase(id); + } + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); + ACCESSTOKEN_LOG_INFO(LABEL, "remove native token %{public}u ok!", id); + if (!isRemote) { + RefreshTokenInfoIfNeeded(); + } + return RET_SUCCESS; +} + +#ifdef SUPPORT_SANDBOX_APP +static void GetPolicyCopied(const HapPolicyParams& policy, HapPolicyParams& policyNew) +{ + policyNew.apl = policy.apl; + policyNew.domain = policy.domain; + + for (const auto& state : policy.permStateList) { + policyNew.permStateList.emplace_back(state); + } + for (const auto& def : policy.permList) { + policyNew.permList.emplace_back(def); + } +} +#endif + +int AccessTokenInfoManager::CreateHapTokenInfo( + const HapInfoParams& info, const HapPolicyParams& policy, AccessTokenIDEx& tokenIdEx) +{ + if (!DataValidator::IsUserIdValid(info.userID) || !DataValidator::IsBundleNameValid(info.bundleName) + || !DataValidator::IsAppIDDescValid(info.appIDDesc) || !DataValidator::IsDomainValid(policy.domain) || + (!DataValidator::IsDlpTypeValid(info.dlpType))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); + return RET_FAILED; + } + + AccessTokenID tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP, info.dlpType); + if (tokenId == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "token Id create failed"); + return RET_FAILED; + } +#ifdef SUPPORT_SANDBOX_APP + std::shared_ptr tokenInfo; + if (info.dlpType != DLP_COMMON) { + HapPolicyParams policyNew; + GetPolicyCopied(policy, policyNew); + int32_t res = DlpPermissionSetManager::GetInstance().UpdatePermStateWithDlpInfo( + info.dlpType, policyNew.permStateList); + if (res != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s update dlp permission failed", info.bundleName.c_str()); + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + return RET_FAILED; + } + tokenInfo = std::make_shared(tokenId, info, policyNew); + } else { + tokenInfo = std::make_shared(tokenId, info, policy); + } +#else + std::shared_ptr tokenInfo = std::make_shared(tokenId, info, policy); +#endif + + if (tokenInfo == nullptr) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + ACCESSTOKEN_LOG_INFO(LABEL, "alloc token info failed"); + return RET_FAILED; + } + + int ret = AddHapTokenInfo(tokenInfo); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s add token info failed", info.bundleName.c_str()); + AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); + return RET_FAILED; + } + PermissionManager::GetInstance().AddDefPermissions(policy.permList, tokenId, false); + + ACCESSTOKEN_LOG_INFO(LABEL, "create hap token %{public}u bundleName %{public}s user %{public}d inst %{public}d ok", + tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex()); + + tokenIdEx.tokenIdExStruct.tokenID = tokenId; + tokenIdEx.tokenIdExStruct.tokenAttr = 0; + RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) +{ + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", tokenID); + return RET_FAILED; + } + + std::vector dcaps = infoPtr->GetDcap(); + for (auto iter = dcaps.begin(); iter != dcaps.end(); iter++) { + if (*iter == dcap) { + return RET_SUCCESS; + } + } + return RET_FAILED; +} + +AccessTokenID AccessTokenInfoManager::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) +{ + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + std::string HapUniqueKey = GetHapUniqueStr(userID, bundleName, instIndex); + if (hapTokenIdMap_.count(HapUniqueKey) > 0) { + return hapTokenIdMap_[HapUniqueKey]; + } + return 0; +} + +bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptr& infoPtr) +{ + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "info is null"); + return false; + } + + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + AccessTokenID id = infoPtr->GetTokenID(); + std::string processName = infoPtr->GetProcessName(); + bool idExist = (nativeTokenInfoMap_.count(id) > 0); + bool processExist = (nativeTokenIdMap_.count(processName) > 0); + // id is exist, but it is not this process, so neither update nor add. + if (idExist && !processExist) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token Id is exist, but process name is not exist, can not update."); + return true; + } + + // this process is exist, but id is not same, perhaps libat lose his data, we need delete old, add new later. + if (!idExist && processExist) { + AccessTokenID idRemove = nativeTokenIdMap_[processName]; + nativeTokenIdMap_.erase(processName); + if (nativeTokenInfoMap_.count(idRemove) > 0) { + nativeTokenInfoMap_.erase(idRemove); + } + AccessTokenIDManager::GetInstance().ReleaseTokenId(idRemove); + return false; + } + + if (!idExist && !processExist) { + return false; + } + + nativeTokenInfoMap_[id] = infoPtr; + return true; +} + +void AccessTokenInfoManager::ProcessNativeTokenInfos( + const std::vector>& tokenInfos) +{ + for (const auto& infoPtr: tokenInfos) { + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "token info from libat is null"); + continue; + } + bool isUpdated = TryUpdateExistNativeToken(infoPtr); + if (!isUpdated) { + ACCESSTOKEN_LOG_INFO(LABEL, + "token %{public}u process name %{public}s is new, add to manager!", + infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); + AccessTokenID id = infoPtr->GetTokenID(); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_NATIVE); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token Id register fail"); + continue; + } + ret = AddNativeTokenInfo(infoPtr); + if (ret != RET_SUCCESS) { + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); + ACCESSTOKEN_LOG_ERROR(LABEL, + "token %{public}u process name %{public}s add to manager failed!", + infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); + } + } + } + RefreshTokenInfoIfNeeded(); +} + +int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, + const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) +{ + if (!DataValidator::IsAppIDDescValid(appIDDesc)) { + ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u parm format error!", tokenID); + return RET_FAILED; + } + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u is null, can not update!", tokenID); + return RET_FAILED; + } + + if (infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote hap token %{public}u can not update!", tokenID); + return RET_FAILED; + } + + { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + infoPtr->Update(appIDDesc, apiVersion, policy); + ACCESSTOKEN_LOG_INFO(LABEL, + "token %{public}u bundle name %{public}s user %{public}d inst %{public}d update ok!", + tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex()); + } + + PermissionManager::GetInstance().AddDefPermissions(policy.permList, tokenID, true); +#ifdef TOKEN_SYNC_ENABLE + TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID); +#endif + RefreshTokenInfoIfNeeded(); + return RET_SUCCESS; +} + +#ifdef TOKEN_SYNC_ENABLE +int AccessTokenInfoManager::GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr || infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u is invalid.", tokenID); + return RET_FAILED; + } + hapSync.baseInfo = infoPtr->GetHapInfoBasic(); + std::shared_ptr permSetPtr = infoPtr->GetHapInfoPermissionPolicySet(); + if (permSetPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u permSet is invalid.", tokenID); + return RET_FAILED; + } + permSetPtr->GetPermissionStateList(hapSync.permStateList); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSync& hapSync) +{ + int ret = GetHapTokenSync(tokenID, hapSync); + TokenModifyNotifier::GetInstance().AddHapTokenObservation(tokenID); + return ret; +} + +void AccessTokenInfoManager::GetAllNativeTokenInfo( + std::vector& nativeTokenInfosRes) +{ + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + for (const auto& nativeTokenInner : nativeTokenInfoMap_) { + std::shared_ptr nativeTokenInnerPtr = nativeTokenInner.second; + if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote() + || nativeTokenInnerPtr->GetDcap().empty()) { + continue; + } + NativeTokenInfoForSync token; + nativeTokenInnerPtr->TranslateToNativeTokenInfo(token.baseInfo); + + std::shared_ptr permSetPtr = + nativeTokenInnerPtr->GetNativeInfoPermissionPolicySet(); + if (permSetPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}u permSet is invalid.", token.baseInfo.tokenID); + return; + } + permSetPtr->GetPermissionStateList(token.permStateList); + + nativeTokenInfosRes.emplace_back(token); + } + return; +} + +int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(mapID); + if (infoPtr == nullptr || !infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u is null or not remote, can not update!", mapID); + return RET_FAILED; + } + + std::shared_ptr newPermPolicySet = + PermissionPolicySet::BuildPermissionPolicySet(mapID, hapSync.permStateList); + + { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + infoPtr->SetTokenBaseInfo(hapSync.baseInfo); + infoPtr->SetPermissionPolicySet(newPermPolicySet); + } + return RET_SUCCESS; +} + +int AccessTokenInfoManager::CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync) +{ + std::shared_ptr hap = std::make_shared(mapID, + hapSync.baseInfo, hapSync.permStateList); + if (hap == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "alloc local token failed."); + return RET_FAILED; + } + hap->SetRemote(true); + + int ret = AddHapTokenInfo(hap); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "add local token failed."); + return RET_FAILED; + } + + return RET_SUCCESS; +} + +int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) + || !DataValidator::IsUserIdValid(hapSync.baseInfo.userID) + || !DataValidator::IsBundleNameValid(hapSync.baseInfo.bundleName) + || !DataValidator::IsAplNumValid(hapSync.baseInfo.apl) + || !DataValidator::IsTokenIDValid(hapSync.baseInfo.tokenID) + || !DataValidator::IsAppIDDescValid(hapSync.baseInfo.appID) + || !DataValidator::IsDeviceIdValid(hapSync.baseInfo.deviceID) + || !DataValidator::IsDlpTypeValid(hapSync.baseInfo.dlpType) + || hapSync.baseInfo.ver != DEFAULT_TOKEN_VERSION + || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(hapSync.baseInfo.tokenID) != TOKEN_HAP) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + + AccessTokenID remoteID = hapSync.baseInfo.tokenID; + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); + if (mapID != 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u update exist remote hap token %{public}u.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + // update remote token mapping id + hapSync.baseInfo.tokenID = mapID; + hapSync.baseInfo.deviceID = deviceID; + return UpdateRemoteHapTokenInfo(mapID, hapSync); + } + + mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u map failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + return RET_FAILED; + } + + // update remote token mapping id + hapSync.baseInfo.tokenID = mapID; + hapSync.baseInfo.deviceID = deviceID; + + if (CreateRemoteHapTokenInfo(mapID, hapSync) == RET_FAILED) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + return RET_FAILED; + } + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u success.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + + for (NativeTokenInfoForSync& nativeToken : nativeTokenInfoList) { + if (!DataValidator::IsAplNumValid(nativeToken.baseInfo.apl) || + nativeToken.baseInfo.ver != DEFAULT_TOKEN_VERSION || + !DataValidator::IsProcessNameValid(nativeToken.baseInfo.processName) || + nativeToken.baseInfo.dcap.empty() || + AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(nativeToken.baseInfo.tokenID) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}u is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), nativeToken.baseInfo.tokenID); + continue; + } + + AccessTokenID remoteID = nativeToken.baseInfo.tokenID; + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); + if (mapID != 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}u has maped, no need update it.", + ConstantCommon::EncryptDevId(deviceID).c_str(), nativeToken.baseInfo.tokenID); + continue; + } + + mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); + if (mapID == 0) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}u map failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + continue; + } + nativeToken.baseInfo.tokenID = mapID; + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map to local token %{public}u.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + + std::shared_ptr nativePtr = + std::make_shared(nativeToken.baseInfo, nativeToken.permStateList); + if (nativePtr == nullptr) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u alloc local token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + continue; + } + nativePtr->SetRemote(true); + int ret = AddNativeTokenInfo(nativePtr); + if (ret != RET_SUCCESS) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u add local token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}u map token %{public}u add success.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + } + + return RET_SUCCESS; +} + +int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId %{public}u is not mapped", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + return RET_FAILED; + } + + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(mapID); + if (type == TOKEN_HAP) { + Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + if (hapTokenInfoMap_.count(mapID) == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}u no exist.", mapID); + return RET_FAILED; + } + hapTokenInfoMap_.erase(mapID); + } else if (type == TOKEN_NATIVE) { + Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); + if (nativeTokenInfoMap_.count(mapID) == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "native token %{public}u is null.", mapID); + return RET_FAILED; + } + nativeTokenInfoMap_.erase(mapID); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "mapping tokenId %{public}u type is unknown", mapID); + } + + return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID); +} + +AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) + || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); + return 0; + } + return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); +} + +int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + std::vector remoteTokens; + int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens); + if (ret == RET_FAILED) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s have no remote token", + ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + for (AccessTokenID remoteID : remoteTokens) { + DeleteRemoteToken(deviceID, remoteID); + } + return RET_SUCCESS; +} + +std::string AccessTokenInfoManager::GetUdidByNodeId(const std::string &nodeId) +{ + uint8_t info[UDID_MAX_LENGTH + 1] = {0}; + + int32_t ret = ::GetNodeKeyInfo(ACCESS_TOKEN_PACKAGE_NAME.c_str(), nodeId.c_str(), + NodeDeviceInfoKey::NODE_KEY_UDID, info, UDID_MAX_LENGTH); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret); + return ""; + } + std::string udid(reinterpret_cast(info)); + return udid; +} + +AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID, + AccessTokenID remoteTokenID) +{ + if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", + ConstantCommon::EncryptDevId(remoteDeviceID).c_str()); + return 0; + } + std::string remoteUdid = GetUdidByNodeId(remoteDeviceID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s remoteUdid", ConstantCommon::EncryptDevId(remoteUdid).c_str()); + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, + remoteTokenID); + if (mapID != 0) { + return mapID; + } + int ret = TokenSyncKit::GetRemoteHapTokenInfo(remoteUdid, remoteTokenID); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}u sync failed", + ConstantCommon::EncryptDevId(remoteUdid).c_str(), remoteTokenID); + return 0; + } + + return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteUdid, remoteTokenID); +} +#else +AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID, + AccessTokenID remoteTokenID) +{ + ACCESSTOKEN_LOG_ERROR(LABEL, "tokensync is disable, check dependent components"); + return 0; +} +#endif + +AccessTokenInfoManager& AccessTokenInfoManager::GetInstance() +{ + static AccessTokenInfoManager instance; + return instance; +} + +void AccessTokenInfoManager::StoreAllTokenInfo() +{ + std::vector hapInfoValues; + std::vector permDefValues; + std::vector permStateValues; + std::vector nativeTokenValues; + { + Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); + for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->StoreHapInfo(hapInfoValues, permStateValues); + } + } + } + + { + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->StoreNativeInfo(nativeTokenValues, permStateValues); + } + } + } + + PermissionDefinitionCache::GetInstance().StorePermissionDef(permDefValues); + + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_HAP_INFO, hapInfoValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefValues); + DataStorage::GetRealDataStorage().RefreshAll(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateValues); +} + +void AccessTokenInfoManager::RefreshTokenInfoIfNeeded() +{ + if (tokenDataWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "has refresh task!"); + return; + } + + tokenDataWorker_.AddTask([]() { + AccessTokenInfoManager::GetInstance().StoreAllTokenInfo(); + + // Sleep for one second to avoid frequent refresh of the database. + std::this_thread::sleep_for(std::chrono::seconds(1)); + }); +} + +void AccessTokenInfoManager::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "get hapTokenInfo"); + if (tokenID != 0) { + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID); + if (type == TOKEN_HAP) { + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr != nullptr) { + infoPtr->ToString(dumpInfo); + } + } else if (type == TOKEN_NATIVE) { + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr != nullptr) { + infoPtr->ToString(dumpInfo); + } + } else { + dumpInfo.append("invalid tokenId"); + } + return; + } + + Utils::UniqueReadGuard hapInfoGuard(this->hapTokenInfoLock_); + for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->ToString(dumpInfo); + dumpInfo.append("\n"); + } + } + + ACCESSTOKEN_LOG_INFO(LABEL, "get nativeTokenInfo"); + Utils::UniqueReadGuard nativeInfoGuard(this->nativeTokenInfoLock_); + for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) { + if (iter->second != nullptr) { + iter->second->ToString(dumpInfo); + dumpInfo.append("\n"); + } + } + ACCESSTOKEN_LOG_INFO(LABEL, "get tokeninfo: %{public}s", dumpInfo.c_str()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp new file mode 100644 index 000000000..d2240dfe5 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_remote_token_manager.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_validator.h" +#include "constant_common.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, + SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenRemoteTokenManager"}; +} +AccessTokenRemoteTokenManager::AccessTokenRemoteTokenManager() +{} + +AccessTokenRemoteTokenManager::~AccessTokenRemoteTokenManager() +{ +} + +AccessTokenRemoteTokenManager& AccessTokenRemoteTokenManager::GetInstance() +{ + static AccessTokenRemoteTokenManager instance; + return instance; +} + +AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + return 0; + } + ATokenTypeEnum tokeType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(remoteID); + if (tokeType != TOKEN_HAP && tokeType != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}x type is invalid.", remoteID); + return 0; + } + int dlpType = AccessTokenIDManager::GetInstance().GetTokenIdDlpFlag(remoteID); + + AccessTokenID mapID = 0; + Utils::UniqueWriteGuard infoGuard(this->remoteDeviceLock_); + std::map* mapPtr = nullptr; + if (remoteDeviceMap_.count(deviceID) > 0) { + AccessTokenRemoteDevice& device = remoteDeviceMap_[deviceID]; + if (device.MappingTokenIDPairMap_.count(remoteID) > 0) { + mapID = device.MappingTokenIDPairMap_[remoteID]; + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x has already mapped, maptokenID is %{public}x.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID, mapID); + return mapID; + } + mapPtr = &device.MappingTokenIDPairMap_; + } else { + AccessTokenRemoteDevice device; + device.DeviceID_ = deviceID; + remoteDeviceMap_[deviceID] = device; + mapPtr = &remoteDeviceMap_[deviceID].MappingTokenIDPairMap_; + } + + mapID = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(tokeType, dlpType); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x map local Token failed.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + return 0; + } + mapPtr->insert(std::pair(remoteID, mapID)); + return mapID; +} + +int AccessTokenRemoteTokenManager::GetDeviceAllRemoteTokenID(const std::string& deviceID, + std::vector& remoteIDs) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s is valid.", ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + + for (const auto& mapEntry : remoteDeviceMap_[deviceID].MappingTokenIDPairMap_) { + remoteIDs.emplace_back(mapEntry.first); + } + return RET_SUCCESS; +} + +AccessTokenID AccessTokenRemoteTokenManager::GetDeviceMappingTokenID(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + return 0; + } + + Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1 || + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); + return 0; + } + + return remoteDeviceMap_[deviceID].MappingTokenIDPairMap_[remoteID]; +} + +int AccessTokenRemoteTokenManager::RemoveDeviceMappingTokenID(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s or token %{public}x is invalid.", + ConstantCommon::EncryptDevId(deviceID).c_str(), remoteID); + return RET_FAILED; + } + + Utils::UniqueWriteGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1 || + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", + ConstantCommon::EncryptDevId(deviceID).c_str()); + return RET_FAILED; + } + + AccessTokenID mapID = remoteDeviceMap_[deviceID].MappingTokenIDPairMap_[remoteID]; + AccessTokenIDManager::GetInstance().ReleaseTokenId(mapID); + + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.erase(remoteID); + + if (remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.empty()) { + remoteDeviceMap_.erase(deviceID); + } + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp new file mode 100644 index 000000000..195743792 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hap_token_info_inner.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_translator.h" +#include "data_validator.h" +#include "field_const.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "HapTokenInfoInner"}; +static const std::string DEFAULT_DEVICEID = "0"; +} + +HapTokenInfoInner::HapTokenInfoInner() : isRemote_(false) +{ + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenID = 0; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.userID = 0; + tokenInfoBasic_.apiVersion = 0; + tokenInfoBasic_.instIndex = 0; + tokenInfoBasic_.dlpType = 0; + tokenInfoBasic_.apl = APL_NORMAL; +} + +HapTokenInfoInner::HapTokenInfoInner(AccessTokenID id, + const HapInfoParams &info, const HapPolicyParams &policy) : isRemote_(false) +{ + tokenInfoBasic_.tokenID = id; + tokenInfoBasic_.userID = info.userID; + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.bundleName = info.bundleName; + tokenInfoBasic_.apiVersion = info.apiVersion; + tokenInfoBasic_.instIndex = info.instIndex; + tokenInfoBasic_.dlpType = info.dlpType; + tokenInfoBasic_.appID = info.appIDDesc; + tokenInfoBasic_.deviceID = DEFAULT_DEVICEID; + tokenInfoBasic_.apl = policy.apl; + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, policy.permStateList); +} + +HapTokenInfoInner::HapTokenInfoInner(AccessTokenID id, + const HapTokenInfo &info, const std::vector& permStateList) : isRemote_(false) +{ + tokenInfoBasic_ = info; + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, permStateList); +} + +HapTokenInfoInner::~HapTokenInfoInner() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, + "tokenID: 0x%{public}x destruction", tokenInfoBasic_.tokenID); +} + +void HapTokenInfoInner::Update(const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) +{ + tokenInfoBasic_.appID = appIDDesc; + tokenInfoBasic_.apiVersion = apiVersion; + tokenInfoBasic_.apl = policy.apl; + if (permPolicySet_ == nullptr) { + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(tokenInfoBasic_.tokenID, + policy.permStateList); + return; + } + + permPolicySet_->Update(policy.permStateList); + return; +} + +void HapTokenInfoInner::TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const +{ + InfoParcel = tokenInfoBasic_; +} + +void HapTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const +{ + outGenericValues.Put(FIELD_TOKEN_ID, (int)tokenInfoBasic_.tokenID); + outGenericValues.Put(FIELD_USER_ID, tokenInfoBasic_.userID); + outGenericValues.Put(FIELD_BUNDLE_NAME, tokenInfoBasic_.bundleName); + outGenericValues.Put(FIELD_API_VERSION, tokenInfoBasic_.apiVersion); + outGenericValues.Put(FIELD_INST_INDEX, tokenInfoBasic_.instIndex); + outGenericValues.Put(FIELD_DLP_TYPE, tokenInfoBasic_.dlpType); + outGenericValues.Put(FIELD_APP_ID, tokenInfoBasic_.appID); + outGenericValues.Put(FIELD_DEVICE_ID, tokenInfoBasic_.deviceID); + outGenericValues.Put(FIELD_APL, tokenInfoBasic_.apl); + outGenericValues.Put(FIELD_TOKEN_VERSION, tokenInfoBasic_.ver); + outGenericValues.Put(FIELD_TOKEN_ATTR, (int)tokenInfoBasic_.tokenAttr); +} + +int HapTokenInfoInner::RestoreHapTokenBasicInfo(const GenericValues& inGenericValues) +{ + tokenInfoBasic_.userID = inGenericValues.GetInt(FIELD_USER_ID); + tokenInfoBasic_.bundleName = inGenericValues.GetString(FIELD_BUNDLE_NAME); + if (!DataValidator::IsBundleNameValid(tokenInfoBasic_.bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: 0x%{public}x bundle name is error", tokenInfoBasic_.tokenID); + return RET_FAILED; + } + + tokenInfoBasic_.apiVersion = inGenericValues.GetInt(FIELD_API_VERSION); + tokenInfoBasic_.instIndex = inGenericValues.GetInt(FIELD_INST_INDEX); + tokenInfoBasic_.dlpType = inGenericValues.GetInt(FIELD_DLP_TYPE); + tokenInfoBasic_.appID = inGenericValues.GetString(FIELD_APP_ID); + if (!DataValidator::IsAppIDDescValid(tokenInfoBasic_.appID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: 0x%{public}x appID is error", tokenInfoBasic_.tokenID); + return RET_FAILED; + } + + tokenInfoBasic_.deviceID = inGenericValues.GetString(FIELD_DEVICE_ID); + if (!DataValidator::IsDeviceIdValid(tokenInfoBasic_.deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: 0x%{public}x devId is error", tokenInfoBasic_.tokenID); + return RET_FAILED; + } + int aplNum = inGenericValues.GetInt(FIELD_APL); + if (DataValidator::IsAplNumValid(aplNum)) { + tokenInfoBasic_.apl = (ATokenAplEnum)aplNum; + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: 0x%{public}x apl is error, value %{public}d", + tokenInfoBasic_.tokenID, aplNum); + return RET_FAILED; + } + tokenInfoBasic_.ver = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (tokenInfoBasic_.ver != DEFAULT_TOKEN_VERSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: 0x%{public}x version is error, version %{public}d", + tokenInfoBasic_.tokenID, tokenInfoBasic_.ver); + return RET_FAILED; + } + tokenInfoBasic_.tokenAttr = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); + return RET_SUCCESS; +} + +int HapTokenInfoInner::RestoreHapTokenInfo(AccessTokenID tokenId, + const GenericValues& tokenValue, + const std::vector& permStateRes) +{ + tokenInfoBasic_.tokenID = tokenId; + int ret = RestoreHapTokenBasicInfo(tokenValue); + if (ret != RET_SUCCESS) { + return RET_FAILED; + } + permPolicySet_ = PermissionPolicySet::RestorePermissionPolicy(tokenId, permStateRes); + return RET_SUCCESS; +} + +void HapTokenInfoInner::StoreHapBasicInfo(std::vector& valueList) const +{ + GenericValues genericValues; + TranslationIntoGenericValues(genericValues); + valueList.emplace_back(genericValues); +} + +void HapTokenInfoInner::StoreHapInfo(std::vector& hapInfoValues, + std::vector& permStateValues) const +{ + if (isRemote_) { + ACCESSTOKEN_LOG_INFO(LABEL, + "token %{public}x is remote hap token, will not store", tokenInfoBasic_.tokenID); + return; + } + StoreHapBasicInfo(hapInfoValues); + if (permPolicySet_ != nullptr) { + permPolicySet_->StorePermissionPolicySet(permStateValues); + } +} + +std::shared_ptr HapTokenInfoInner::GetHapInfoPermissionPolicySet() const +{ + return permPolicySet_; +} + +int HapTokenInfoInner::GetUserID() const +{ + return tokenInfoBasic_.userID; +} + +int HapTokenInfoInner::GetDlpType() const +{ + return tokenInfoBasic_.dlpType; +} + +std::string HapTokenInfoInner::GetBundleName() const +{ + return tokenInfoBasic_.bundleName; +} + +int HapTokenInfoInner::GetInstIndex() const +{ + return tokenInfoBasic_.instIndex; +} + +AccessTokenID HapTokenInfoInner::GetTokenID() const +{ + return tokenInfoBasic_.tokenID; +} + +HapTokenInfo HapTokenInfoInner::GetHapInfoBasic() const +{ + return tokenInfoBasic_; +} + +void HapTokenInfoInner::SetTokenBaseInfo(const HapTokenInfo& baseInfo) +{ + tokenInfoBasic_ = baseInfo; +} + +void HapTokenInfoInner::SetPermissionPolicySet(std::shared_ptr& policySet) +{ + permPolicySet_ = policySet; +} + +bool HapTokenInfoInner::IsRemote() const +{ + return isRemote_; +} + +void HapTokenInfoInner::SetRemote(bool isRemote) +{ + isRemote_ = isRemote; +} + +void HapTokenInfoInner::ToString(std::string& info) const +{ + info.append(R"({)"); + info.append("\n"); + info.append(R"( "tokenID": )" + std::to_string(tokenInfoBasic_.tokenID) + ",\n"); + info.append(R"( "tokenAttr": )" + std::to_string(tokenInfoBasic_.tokenAttr) + ",\n"); + info.append(R"( "ver": )" + std::to_string(tokenInfoBasic_.ver) + ",\n"); + info.append(R"( "userId": )" + std::to_string(tokenInfoBasic_.userID) + ",\n"); + info.append(R"( "bundleName": ")" + tokenInfoBasic_.bundleName + R"(")" + ",\n"); + info.append(R"( "instIndex": )" + std::to_string(tokenInfoBasic_.instIndex) + ",\n"); + info.append(R"( "dlpType": )" + std::to_string(tokenInfoBasic_.dlpType) + ",\n"); + info.append(R"( "appID": ")" + tokenInfoBasic_.appID + R"(")" + ",\n"); + info.append(R"( "deviceID": ")" + tokenInfoBasic_.deviceID + R"(")" + ",\n"); + info.append(R"( "apl": )" + std::to_string(tokenInfoBasic_.apl) + ",\n"); + info.append(R"( "isRemote": )" + std::to_string(isRemote_) + ",\n"); + + if (permPolicySet_ != nullptr) { + permPolicySet_->ToString(info); + } + info.append("}"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp new file mode 100644 index 000000000..00c656f84 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_info_inner.h" + +#include "data_translator.h" +#include "data_validator.h" +#include "field_const.h" +#include "nlohmann/json.hpp" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "NativeTokenInfoInner"}; +} + +NativeTokenInfoInner::NativeTokenInfoInner() : isRemote_(false) +{ + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenID = 0; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.apl = APL_NORMAL; +} + +NativeTokenInfoInner::NativeTokenInfoInner(NativeTokenInfo& native, + const std::vector& permStateList) : isRemote_(false) +{ + tokenInfoBasic_ = native; + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(native.tokenID, + permStateList); +} + +NativeTokenInfoInner::~NativeTokenInfoInner() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, + "tokenID: %{public}u destruction", tokenInfoBasic_.tokenID); +} + +int NativeTokenInfoInner::Init(AccessTokenID id, const std::string& processName, + int apl, const std::vector& dcap, + const std::vector& nativeAcls, + const std::vector& permStateList) +{ + tokenInfoBasic_.tokenID = id; + if (!DataValidator::IsProcessNameValid(processName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: %{public}u process name is null", tokenInfoBasic_.tokenID); + return RET_FAILED; + } + tokenInfoBasic_.processName = processName; + if (!DataValidator::IsAplNumValid(apl)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: %{public}u init failed, apl %{public}d is invalid", + tokenInfoBasic_.tokenID, apl); + return RET_FAILED; + } + tokenInfoBasic_.apl = (ATokenAplEnum)apl; + tokenInfoBasic_.dcap = dcap; + tokenInfoBasic_.nativeAcls = nativeAcls; + + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, + permStateList); + return RET_SUCCESS; +} + +std::string NativeTokenInfoInner::DcapToString(const std::vector& dcap) const +{ + std::string dcapStr; + for (auto iter = dcap.begin(); iter != dcap.end(); iter++) { + dcapStr.append(*iter); + if (iter != (dcap.end() - 1)) { + dcapStr.append(","); + } + } + return dcapStr; +} + +std::string NativeTokenInfoInner::NativeAclsToString(const std::vector& nativeAcls) const +{ + std::string nativeAclsStr; + for (auto iter = nativeAcls.begin(); iter != nativeAcls.end(); iter++) { + nativeAclsStr.append(*iter); + if (iter != (nativeAcls.end() - 1)) { + nativeAclsStr.append(","); + } + } + return nativeAclsStr; +} + +int NativeTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const +{ + outGenericValues.Put(FIELD_TOKEN_ID, (int)tokenInfoBasic_.tokenID); + outGenericValues.Put(FIELD_PROCESS_NAME, tokenInfoBasic_.processName); + outGenericValues.Put(FIELD_APL, tokenInfoBasic_.apl); + outGenericValues.Put(FIELD_TOKEN_VERSION, tokenInfoBasic_.ver); + outGenericValues.Put(FIELD_DCAP, DcapToString(tokenInfoBasic_.dcap)); + outGenericValues.Put(FIELD_NATIVE_ACLS, NativeAclsToString(tokenInfoBasic_.nativeAcls)); + outGenericValues.Put(FIELD_TOKEN_ATTR, (int)tokenInfoBasic_.tokenAttr); + + return RET_SUCCESS; +} + +int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const GenericValues& inGenericValues, + const std::vector& permStateRes) +{ + tokenInfoBasic_.tokenID = tokenId; + tokenInfoBasic_.processName = inGenericValues.GetString(FIELD_PROCESS_NAME); + if (!DataValidator::IsProcessNameValid(tokenInfoBasic_.processName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: %{public}u process name is null", tokenInfoBasic_.tokenID); + return RET_FAILED; + } + int aplNum = inGenericValues.GetInt(FIELD_APL); + if (!DataValidator::IsAplNumValid(aplNum)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: %{public}u apl is error, value %{public}d", + tokenInfoBasic_.tokenID, aplNum); + return RET_FAILED; + } + tokenInfoBasic_.apl = (ATokenAplEnum)aplNum; + tokenInfoBasic_.ver = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (tokenInfoBasic_.ver != DEFAULT_TOKEN_VERSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "tokenID: %{public}u version is error, version %{public}d", + tokenInfoBasic_.tokenID, tokenInfoBasic_.ver); + return RET_FAILED; + } + + SetDcaps(inGenericValues.GetString(FIELD_DCAP)); + SetNativeAcls(inGenericValues.GetString(FIELD_NATIVE_ACLS)); + tokenInfoBasic_.tokenAttr = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); + + std::vector permDefRes = {}; + permPolicySet_ = PermissionPolicySet::RestorePermissionPolicy(tokenId, + permStateRes); + return RET_SUCCESS; +} + +void NativeTokenInfoInner::TranslateToNativeTokenInfo(NativeTokenInfo& InfoParcel) const +{ + InfoParcel.apl = tokenInfoBasic_.apl; + InfoParcel.ver = tokenInfoBasic_.ver; + InfoParcel.processName = tokenInfoBasic_.processName; + InfoParcel.dcap = tokenInfoBasic_.dcap; + InfoParcel.nativeAcls = tokenInfoBasic_.nativeAcls; + InfoParcel.tokenID = tokenInfoBasic_.tokenID; + InfoParcel.tokenAttr = tokenInfoBasic_.tokenAttr; +} + +void NativeTokenInfoInner::StoreNativeInfo(std::vector& valueList, + std::vector& permStateValues) const +{ + if (isRemote_) { + return; + } + GenericValues genericValues; + TranslationIntoGenericValues(genericValues); + valueList.emplace_back(genericValues); + + if (permPolicySet_ != nullptr) { + permPolicySet_->StorePermissionPolicySet(permStateValues); + } +} + +AccessTokenID NativeTokenInfoInner::GetTokenID() const +{ + return tokenInfoBasic_.tokenID; +} + +std::vector NativeTokenInfoInner::GetDcap() const +{ + return tokenInfoBasic_.dcap; +} + +std::vector NativeTokenInfoInner::GetNativeAcls() const +{ + return tokenInfoBasic_.nativeAcls; +} + +std::string NativeTokenInfoInner::GetProcessName() const +{ + return tokenInfoBasic_.processName; +} + +std::shared_ptr NativeTokenInfoInner::GetNativeInfoPermissionPolicySet() const +{ + return permPolicySet_; +} + +bool NativeTokenInfoInner::IsRemote() const +{ + return isRemote_; +} + +void NativeTokenInfoInner::SetRemote(bool isRemote) +{ + isRemote_ = isRemote; +} + +void NativeTokenInfoInner::SetDcaps(const std::string& dcapStr) +{ + std::string::size_type start = 0; + while (true) { + std::string::size_type offset = dcapStr.find(',', start); + if (offset == std::string::npos) { + tokenInfoBasic_.dcap.push_back(dcapStr.substr(start)); + break; + } + tokenInfoBasic_.dcap.push_back(dcapStr.substr(start, offset)); + start = offset + 1; + } +} + +void NativeTokenInfoInner::SetNativeAcls(const std::string& AclsStr) +{ + std::string::size_type start = 0; + while (true) { + std::string::size_type offset = AclsStr.find(',', start); + if (offset == std::string::npos) { + tokenInfoBasic_.nativeAcls.push_back(AclsStr.substr(start)); + break; + } + tokenInfoBasic_.nativeAcls.push_back(AclsStr.substr(start, offset)); + start = offset + 1; + } +} + +void NativeTokenInfoInner::ToString(std::string& info) const +{ + info.append(R"({)"); + info.append("\n"); + info.append(R"( "tokenID": )" + std::to_string(tokenInfoBasic_.tokenID) + ",\n"); + info.append(R"( "tokenAttr": )" + std::to_string(tokenInfoBasic_.tokenAttr) + ",\n"); + info.append(R"( "ver": )" + std::to_string(tokenInfoBasic_.ver) + ",\n"); + info.append(R"( "processName": ")" + tokenInfoBasic_.processName + R"(")" + ",\n"); + info.append(R"( "apl": )" + std::to_string(tokenInfoBasic_.apl) + ",\n"); + info.append(R"( "dcap": ")" + DcapToString(tokenInfoBasic_.dcap) + R"(")" + ",\n"); + info.append(R"( "nativeAcls": ")" + NativeAclsToString(tokenInfoBasic_.nativeAcls) + R"(")" + ",\n"); + info.append(R"( "isRemote": )" + std::to_string(isRemote_? 1 : 0) + ",\n"); + if (permPolicySet_ != nullptr) { + permPolicySet_->PermStateToString(tokenInfoBasic_.apl, tokenInfoBasic_.nativeAcls, info); + } + info.append("}"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp new file mode 100644 index 000000000..37cd2eee0 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +#include + +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "data_validator.h" +#include "native_token_receptor.h" +#include "securec.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "NativeTokenReceptor"}; +} + +int32_t NativeReqPermsGet( + const nlohmann::json& j, std::vector& permStateList) +{ + std::vector permReqList; + if (j.find(JSON_PERMS) == j.end()) { + return RET_FAILED; + } + permReqList = j.at(JSON_PERMS).get>(); + if (permReqList.size() > MAX_REQ_PERM_NUM) { + return RET_FAILED; + } + std::set permRes; + for (const auto& permReq : permReqList) { + PermissionStateFull permState; + if (permRes.count(permReq) != 0) { + continue; + } + permState.permissionName = permReq; + permState.isGeneral = true; + permState.resDeviceID.push_back(""); + permState.grantStatus.push_back(PERMISSION_GRANTED); + permState.grantFlags.push_back(PERMISSION_SYSTEM_FIXED); + permStateList.push_back(permState); + permRes.insert(permReq); + } + return RET_SUCCESS; +} + +// nlohmann json need the function named from_json to parse NativeTokenInfo +void from_json(const nlohmann::json& j, std::shared_ptr& p) +{ + NativeTokenInfo native; + if (j.find(JSON_PROCESS_NAME) != j.end()) { + native.processName = j.at(JSON_PROCESS_NAME).get(); + if (!DataValidator::IsProcessNameValid(native.processName)) { + return; + } + } else { + return; + } + + if (j.find(JSON_APL) != j.end()) { + int aplNum = j.at(JSON_APL).get(); + if (DataValidator::IsAplNumValid(aplNum)) { + native.apl = (ATokenAplEnum)aplNum; + } else { + return; + } + } else { + return; + } + + if (j.find(JSON_VERSION) != j.end()) { + native.ver = (uint8_t)j.at(JSON_VERSION).get(); + if (native.ver != DEFAULT_TOKEN_VERSION) { + return; + } + } else { + return; + } + + if (j.find(JSON_TOKEN_ID) != j.end()) { + native.tokenID = j.at(JSON_TOKEN_ID).get(); + if (native.tokenID == 0 || + AccessTokenIDManager::GetTokenIdTypeEnum(native.tokenID) != TOKEN_NATIVE) { + return; + } + } else { + return; + } + + if (j.find(JSON_TOKEN_ATTR) != j.end()) { + native.tokenAttr = j.at(JSON_TOKEN_ATTR).get(); + } else { + return; + } + + if (j.find(JSON_DCAPS) != j.end()) { + native.dcap = j.at(JSON_DCAPS).get>(); + if (native.dcap.size() > MAX_DCAPS_NUM) { + return; + } + } else { + return; + } + + if (j.find(JSON_ACLS) != j.end()) { + native.nativeAcls = j.at(JSON_ACLS).get>(); + if (native.nativeAcls.size() > MAX_REQ_PERM_NUM) { + return; + } + } else { + return; + } + + std::vector permStateList; + if (NativeReqPermsGet(j, permStateList) != RET_SUCCESS) { + return; + } + + p = std::make_shared(native, permStateList); +} + +int32_t NativeTokenReceptor::ParserNativeRawData(const std::string& nativeRawData, + std::vector>& tokenInfos) +{ + nlohmann::json jsonRes = nlohmann::json::parse(nativeRawData, nullptr, false); + if (jsonRes.is_discarded()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "jsonRes is invalid."); + return RET_FAILED; + } + for (auto it = jsonRes.begin(); it != jsonRes.end(); it++) { + auto token = it->get>(); + if (token != nullptr) { + tokenInfos.emplace_back(token); + } + } + return RET_SUCCESS; +} + +int NativeTokenReceptor::ReadCfgFile(std::string& nativeRawData) +{ + int32_t fd = open(NATIVE_TOKEN_CONFIG_FILE.c_str(), O_RDONLY); + if (fd < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "open failed errno %{public}d.", errno); + return RET_FAILED; + } + struct stat statBuffer; + + if (fstat(fd, &statBuffer) != 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fstat failed."); + close(fd); + return RET_FAILED; + } + + if (statBuffer.st_size == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is invalid."); + close(fd); + return RET_FAILED; + } + if (statBuffer.st_size > MAX_NATIVE_CONFIG_FILE_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is too large."); + close(fd); + return RET_FAILED; + } + nativeRawData.reserve(statBuffer.st_size); + + char buff[BUFFER_SIZE] = { 0 }; + ssize_t readLen = 0; + while ((readLen = read(fd, buff, BUFFER_SIZE)) > 0) { + nativeRawData.append(buff, readLen); + } + close(fd); + + if (readLen == 0) { + return RET_SUCCESS; + } + return RET_FAILED; +} + +int NativeTokenReceptor::Init() +{ + if (ready_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "native token has been inited."); + return RET_SUCCESS; + } + + std::string nativeRawData; + int ret = ReadCfgFile(nativeRawData); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "readCfgFile failed."); + return RET_FAILED; + } + std::vector> tokenInfos; + ret = ParserNativeRawData(nativeRawData, tokenInfos); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ParserNativeRawData failed."); + return RET_FAILED; + } + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + + ready_ = true; + ACCESSTOKEN_LOG_INFO(LABEL, "init ok."); + return RET_SUCCESS; +} + +NativeTokenReceptor& NativeTokenReceptor::GetInstance() +{ + static NativeTokenReceptor instance; + return instance; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp new file mode 100644 index 000000000..ca2c8c9b3 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_modify_notifier.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "token_sync_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenModifyNotifier"}; +} + +TokenModifyNotifier::TokenModifyNotifier() : hasInited_(false) {} + +TokenModifyNotifier::~TokenModifyNotifier() {} + +void TokenModifyNotifier::AddHapTokenObservation(AccessTokenID tokenID) +{ + if (AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID) != TOKEN_HAP) { + ACCESSTOKEN_LOG_INFO(LABEL, "Observation token is not hap token"); + return; + } + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + observationSet_.insert(tokenID); + } +} + +void TokenModifyNotifier::NotifyTokenDelete(AccessTokenID tokenID) +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "hap token is not observed"); + return; + } + observationSet_.erase(tokenID); + deleteTokenList_.emplace_back(tokenID); + NotifyTokenChangedIfNeed(); +} + +void TokenModifyNotifier::NotifyTokenModify(AccessTokenID tokenID) +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "hap token is not observed"); + return; + } + modifiedTokenList_.emplace_back(tokenID); + NotifyTokenChangedIfNeed(); +} + +TokenModifyNotifier& TokenModifyNotifier::GetInstance() +{ + static TokenModifyNotifier instance; + + if (!instance.hasInited_) { + Utils::UniqueWriteGuard infoGuard(instance.initLock_); + if (!instance.hasInited_) { + instance.notifyTokenWorker_.Start(1); + instance.hasInited_ = true; + } + } + + return instance; +} + +void TokenModifyNotifier::NotifyTokenSyncTask() +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + for (AccessTokenID deleteToken : deleteTokenList_) { + TokenSyncKit::DeleteRemoteHapTokenInfo(deleteToken); + } + + for (AccessTokenID modifyToken : modifiedTokenList_) { + HapTokenInfoForSync hapSync; + int ret = AccessTokenInfoManager::GetInstance().GetHapTokenSync(modifyToken, hapSync); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "the hap token 0x%{public}x need to sync is not found!", modifyToken); + continue; + } + TokenSyncKit::UpdateRemoteHapTokenInfo(hapSync); + } + deleteTokenList_.clear(); + modifiedTokenList_.clear(); +} +void TokenModifyNotifier::NotifyTokenChangedIfNeed() +{ + if (notifyTokenWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, " has notify task!"); + return; + } + + notifyTokenWorker_.AddTask([]() { + TokenModifyNotifier::GetInstance().NotifyTokenSyncTask(); + }); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/3503.xml b/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/3503.xml new file mode 100644 index 000000000..b56ef0380 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/3503.xml @@ -0,0 +1,24 @@ + + + + accesstoken_service + + 3503 + libaccesstoken_manager_service.z.so + true + false + 1 + + diff --git a/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/BUILD.gn b/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/BUILD.gn new file mode 100644 index 000000000..dffd35da0 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/main/sa_profile/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/ohos/sa_profile/sa_profile.gni") + +if (is_standard_system) { + ohos_sa_profile("accesstoken_sa_profile_standard") { + part_name = "access_token" + + sources = [ "3503.xml" ] + } +} diff --git a/security_access_token-yl_0822/services/accesstokenmanager/test/BUILD.gn b/security_access_token-yl_0822/services/accesstokenmanager/test/BUILD.gn new file mode 100644 index 000000000..0dd6433de --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/test/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +ohos_unittest("libaccesstoken_manager_service_standard_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/service", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/token", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/permission", + "//base/security/access_token/services/accesstokenmanager/main/cpp/include/database", + "//base/security/access_token/services/common/database/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//third_party/json/include", + "//third_party/googletest/include", + "//commonlibrary/c_utils/base/include", + ] + + sources = [ + "unittest/cpp/src/accesstoken_info_manager_test.cpp", + "unittest/cpp/src/native_token_receptor_test.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + if (dlp_permission_enable == true) { + cflags_cc += [ "-DSUPPORT_SANDBOX_APP" ] + } + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", + "//base/security/access_token/services/accesstokenmanager/:accesstoken_manager_service", + "//base/security/access_token/services/common/database:accesstoken_database_cxx", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libaccesstoken_manager_service_standard_test" ] +} diff --git a/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp new file mode 100644 index 000000000..fbe8f922a --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp @@ -0,0 +1,706 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_info_manager_test.h" + +#include +#include +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#ifdef SUPPORT_SANDBOX_APP +#define private public +#include "dlp_permission_set_manager.h" +#include "dlp_permission_set_parser.h" +#undef private +#endif +#include "permission_manager.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManagerTest" +}; + +static constexpr int32_t DEFAULT_API_VERSION = 8; +static PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "open the door", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; + +static PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "break the door", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; + +static PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {1}, + .isGeneral = true, + .permissionName = "open the door", + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "break the door", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {1, 3}, + .resDeviceID = {"device 1", "device 2"} +}; + +static HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +static HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; + +static PermissionStateFull g_infoManagerTestStateA = { + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; +static PermissionStateFull g_infoManagerTestStateB = { + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; +static PermissionStateFull g_infoManagerTestStateC = { + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; +static PermissionStateFull g_infoManagerTestStateD = { + .grantFlags = {1}, + .grantStatus = {PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; + +static PermissionDef g_infoManagerPermDef1 = { + .permissionName = "ohos.permission.MEDIA_LOCATION", + .bundleName = "accesstoken_test", + .grantMode = USER_GRANT, + .label = "label", + .labelId = 1, + .description = "MEDIA_LOCATION", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; +static PermissionDef g_infoManagerPermDef2 = { + .permissionName = "ohos.permission.MICROPHONE", + .bundleName = "accesstoken_test", + .grantMode = USER_GRANT, + .label = "label", + .labelId = 1, + .description = "MICROPHONE", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; +static PermissionDef g_infoManagerPermDef3 = { + .permissionName = "ohos.permission.READ_CALENDAR", + .bundleName = "accesstoken_test", + .grantMode = USER_GRANT, + .label = "label", + .labelId = 1, + .description = "READ_CALENDAR", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; +static PermissionDef g_infoManagerPermDef4 = { + .permissionName = "ohos.permission.READ_CALL_LOG", + .bundleName = "accesstoken_test", + .grantMode = USER_GRANT, + .label = "label", + .labelId = 1, + .description = "READ_CALL_LOG", + .descriptionId = 1, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; +} + +void AccessTokenInfoManagerTest::SetUpTestCase() +{} + +void AccessTokenInfoManagerTest::TearDownTestCase() +{} + +void AccessTokenInfoManagerTest::SetUp() +{} + +void AccessTokenInfoManagerTest::TearDown() +{} + +HWTEST_F(AccessTokenInfoManagerTest, Init001, TestSize.Level1) +{ + AccessTokenInfoManager::GetInstance().Init(); + AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + + std::string dumpInfo; + AccessTokenInfoManager::GetInstance().DumpTokenInfo(getTokenId, dumpInfo); + GTEST_LOG_(INFO) << "dump all:" << dumpInfo.c_str(); + + // delete test token + if (getTokenId != 0) { + int ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(getTokenId); + ASSERT_EQ(RET_SUCCESS, ret); + } + + ASSERT_EQ(RET_SUCCESS, RET_SUCCESS); +} + +/** + * @tc.name: CreateHapTokenInfo001 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, CreateHapTokenInfo001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; + + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(nullptr, tokenInfo); +} + +/** + * @tc.name: CreateHapTokenInfo002 + * @tc.desc: Verify the CreateHapTokenInfo add one hap token twice function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, CreateHapTokenInfo002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AddHapToken001 fill data"); + + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenIDEx tokenIdEx1 = {0}; + ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx1); + ASSERT_EQ(RET_FAILED, ret); + ASSERT_EQ(0, tokenIdEx1.tokenIdExStruct.tokenID); + GTEST_LOG_(INFO) << "add same hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: GetHapTokenID001 + * @tc.desc: Verify the GetHapTokenID by userID/bundleName/instIndex, function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, GetHapTokenID001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + ASSERT_EQ(tokenIdEx.tokenIdExStruct.tokenID, getTokenId); + GTEST_LOG_(INFO) << "find hap info"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + GTEST_LOG_(INFO) << "remove the token info"; + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: UpdateHapToken001 + * @tc.desc: Verify the UpdateHapToken token function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(AccessTokenInfoManagerTest, UpdateHapToken001, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(g_infoManagerTestInfoParms, + g_infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + HapPolicyParams policy = g_infoManagerTestPolicyPrams; + policy.apl = APL_SYSTEM_BASIC; + ret = AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenIdEx.tokenIdExStruct.tokenID, + std::string("updateAppId"), DEFAULT_API_VERSION, policy); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "update the hap token"; + + std::shared_ptr tokenInfo; + tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_NE(nullptr, tokenInfo); + std::string infoDes; + tokenInfo->ToString(infoDes); + GTEST_LOG_(INFO) << "get hap token info:" << infoDes.c_str(); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenIdEx.tokenIdExStruct.tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +#ifdef SUPPORT_SANDBOX_APP +static void PrepareJsonData1() +{ + std::string testStr = R"({"dlpPermissions":[)"\ + R"({"name":"ohos.permission.CAPTURE_SCREEN","dlpGrantRange":"none"},)"\ + R"({"name":"ohos.permission.CHANGE_ABILITY_ENABLED_STATE","dlpGrantRange":"all"},)"\ + R"({"name":"ohos.permission.CLEAN_APPLICATION_DATA","dlpGrantRange":"full_control"}]})"; + + std::vector dlpPerms; + int res = DlpPermissionSetParser::GetInstance().ParserDlpPermsRawData(testStr, dlpPerms); + if (res != RET_SUCCESS) { + GTEST_LOG_(INFO) << "ParserDlpPermsRawData failed:"; + } + for (auto iter = dlpPerms.begin(); iter != dlpPerms.end(); iter++) { + GTEST_LOG_(INFO) << "iter:" << iter->permissionName.c_str(); + } + DlpPermissionSetManager::GetInstance().ProcessDlpPermInfos(dlpPerms); +} + +/** + * @tc.name: DlpPermissionConfig001 + * @tc.desc: test DLP_COMMON app with system_grant permissions. + * @tc.type: FUNC + * @tc.require: SR000GVIGR + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig001, TestSize.Level1) +{ + PrepareJsonData1(); + + g_infoManagerTestStateA.permissionName = "ohos.permission.CAPTURE_SCREEN"; + g_infoManagerTestStateB.permissionName = "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"; + g_infoManagerTestStateC.permissionName = "ohos.permission.CLEAN_APPLICATION_DATA"; + g_infoManagerTestStateD.permissionName = "ohos.permission.COMMONEVENT_STICKY"; + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "DlpPermissionConfig001", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_COMMON, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CAPTURE_SCREEN"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CLEAN_APPLICATION_DATA"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.COMMONEVENT_STICKY"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: DlpPermissionConfig002 + * @tc.desc: test DLP_READ app with system_grant permissions. + * @tc.type: FUNC + * @tc.require: SR000GVIGR + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig002, TestSize.Level1) +{ + PrepareJsonData1(); + + g_infoManagerTestStateA.permissionName = "ohos.permission.CAPTURE_SCREEN"; + g_infoManagerTestStateB.permissionName = "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"; + g_infoManagerTestStateC.permissionName = "ohos.permission.CLEAN_APPLICATION_DATA"; + g_infoManagerTestStateD.permissionName = "ohos.permission.COMMONEVENT_STICKY"; + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "DlpPermissionConfig002", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_READ, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CAPTURE_SCREEN"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CLEAN_APPLICATION_DATA"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.COMMONEVENT_STICKY"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: DlpPermissionConfig003 + * @tc.desc: test DLP_FULL_CONTROL app with system_grant permissions. + * @tc.type: FUNC + * @tc.require: SR000GVIGR + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig003, TestSize.Level1) +{ + PrepareJsonData1(); + + g_infoManagerTestStateA.permissionName = "ohos.permission.CAPTURE_SCREEN"; + g_infoManagerTestStateB.permissionName = "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"; + g_infoManagerTestStateC.permissionName = "ohos.permission.CLEAN_APPLICATION_DATA"; + g_infoManagerTestStateD.permissionName = "ohos.permission.COMMONEVENT_STICKY"; + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "DlpPermissionConfig003", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_FULL_CONTROL, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CAPTURE_SCREEN"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CHANGE_ABILITY_ENABLED_STATE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.CLEAN_APPLICATION_DATA"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken( + tokenID, "ohos.permission.COMMONEVENT_STICKY"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +static void PrepareUserPermState() +{ + g_infoManagerTestStateA.permissionName = "ohos.permission.MEDIA_LOCATION"; + g_infoManagerTestStateA.grantStatus[0] = PERMISSION_DENIED; + g_infoManagerTestStateB.permissionName = "ohos.permission.MICROPHONE"; + g_infoManagerTestStateB.grantStatus[0] = PERMISSION_DENIED; + g_infoManagerTestStateC.permissionName = "ohos.permission.READ_CALENDAR"; + g_infoManagerTestStateC.grantStatus[0] = PERMISSION_DENIED; + g_infoManagerTestStateD.permissionName = "ohos.permission.READ_CALL_LOG"; + g_infoManagerTestStateD.grantStatus[0] = PERMISSION_DENIED; +} + +static void PrepareJsonData2() +{ + std::string testStr = R"({"dlpPermissions":[)"\ + R"({"name":"ohos.permission.MEDIA_LOCATION","dlpGrantRange":"none"},)"\ + R"({"name":"ohos.permission.MICROPHONE","dlpGrantRange":"all"},)"\ + R"({"name":"ohos.permission.READ_CALENDAR","dlpGrantRange":"full_control"}]})"; + + std::vector dlpPerms; + int res = DlpPermissionSetParser::GetInstance().ParserDlpPermsRawData(testStr, dlpPerms); + if (res != RET_SUCCESS) { + GTEST_LOG_(INFO) << "ParserDlpPermsRawData failed:"; + } + DlpPermissionSetManager::GetInstance().ProcessDlpPermInfos(dlpPerms); +} + +/** + * @tc.name: DlpPermissionConfig004 + * @tc.desc: test DLP_COMMON app with user_grant permissions. + * @tc.type: FUNC + * @tc.require: SR000GVIGR + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig004, TestSize.Level1) +{ + PrepareJsonData2(); + PrepareUserPermState(); + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerPermDef1, g_infoManagerPermDef2, + g_infoManagerPermDef3, g_infoManagerPermDef4}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_COMMON, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MEDIA_LOCATION", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MICROPHONE", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALENDAR", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALL_LOG", PERMISSION_USER_FIXED); + + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MEDIA_LOCATION"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MICROPHONE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALENDAR"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALL_LOG"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: DlpPermissionConfig005 + * @tc.desc: test DLP_READ app with user_grant permissions. + * @tc.type: FUNC + * @tc.require: SR000GVIGR + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig005, TestSize.Level1) +{ + PrepareJsonData2(); + PrepareUserPermState(); + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerPermDef1, g_infoManagerPermDef2, + g_infoManagerPermDef3, g_infoManagerPermDef4}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_READ, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MEDIA_LOCATION", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MICROPHONE", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALENDAR", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALL_LOG", PERMISSION_USER_FIXED); + + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MEDIA_LOCATION"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MICROPHONE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALENDAR"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALL_LOG"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} + +/** + * @tc.name: DlpPermissionConfig006 + * @tc.desc: test DLP_FULL_CONTROL app with user_grant permissions. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AccessTokenInfoManagerTest, DlpPermissionConfig006, TestSize.Level1) +{ + PrepareJsonData2(); + PrepareUserPermState(); + + static HapPolicyParams infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerPermDef1, g_infoManagerPermDef2, + g_infoManagerPermDef3, g_infoManagerPermDef4}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB, + g_infoManagerTestStateC, g_infoManagerTestStateD} + }; + static HapInfoParams infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .dlpType = DLP_FULL_CONTROL, + .appIDDesc = "testtesttesttest" + }; + AccessTokenIDEx tokenIdEx = {0}; + int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo(infoManagerTestInfoParms, + infoManagerTestPolicyPrams, tokenIdEx); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "add a hap token"; + + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MEDIA_LOCATION", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.MICROPHONE", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALENDAR", PERMISSION_USER_FIXED); + PermissionManager::GetInstance().GrantPermission(tokenID, + "ohos.permission.READ_CALL_LOG", PERMISSION_USER_FIXED); + + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MEDIA_LOCATION"); + ASSERT_EQ(PERMISSION_DENIED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.MICROPHONE"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALENDAR"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + ret = PermissionManager::GetInstance().VerifyAccessToken(tokenID, "ohos.permission.READ_CALL_LOG"); + ASSERT_EQ(PERMISSION_GRANTED, ret); + + ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(tokenID); + ASSERT_EQ(RET_SUCCESS, ret); + GTEST_LOG_(INFO) << "remove the token info"; +} +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h new file mode 100644 index 000000000..03cbc7d1c --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKEN_INFO_MANAGER_TEST_H +#define ACCESSTOKEN_INFO_MANAGER_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenInfoManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_INFO_MANAGER_TEST_H diff --git a/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp new file mode 100644 index 000000000..ee7554514 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.cpp @@ -0,0 +1,706 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_token_receptor_test.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_info_manager.h" +#include "accesstoken_kit.h" +#include "permission_manager.h" +#include "data_storage.h" +#include "field_const.h" +#include "permission_state_full.h" +#define private public +#include "nativetoken_kit.h" +#include "native_token_receptor.h" +#undef private +#include "securec.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "NativeTokenReceptorTest"}; +} + +void NativeTokenReceptorTest::SetUpTestCase() +{ + // delete all test 0x28100000 - 0x28100007 + for (unsigned int i = 0x28100000; i <= 0x28100007; i++) { + AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(i); + } +} + +void NativeTokenReceptorTest::TearDownTestCase() +{} + +void NativeTokenReceptorTest::SetUp() +{} + +void NativeTokenReceptorTest::TearDown() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test down!"); +} + +/** + * @tc.name: ParserNativeRawData001 + * @tc.desc: Verify processing right native token json. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ParserNativeRawData001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ParserNativeRawData001!"); + std::string testStr = R"([)"\ + R"({"processName":"process6","APL":3,"version":1,"tokenId":685266937,"tokenAttr":0,)"\ + R"("dcaps":["AT_CAP","ST_CAP"], "permissions":[], "nativeAcls":[]},)"\ + R"({"processName":"process5","APL":3,"version":1,"tokenId":678065606,"tokenAttr":0,)"\ + R"("dcaps":["AT_CAP","ST_CAP"], "permissions":[], "nativeAcls":[]}])"; + + NativeTokenReceptor& receptor = NativeTokenReceptor::GetInstance(); + std::vector> tokenInfos; + receptor.ParserNativeRawData(testStr, tokenInfos); + int size = tokenInfos.size(); + ASSERT_EQ(2, size); + ASSERT_NE(nullptr, tokenInfos[0]); + ASSERT_NE(nullptr, tokenInfos[1]); + + ASSERT_EQ("process6", tokenInfos[0]->GetProcessName()); + ASSERT_EQ(685266937, tokenInfos[0]->GetTokenID()); + ASSERT_EQ(2, tokenInfos[0]->GetDcap().size()); + ASSERT_EQ("AT_CAP", (tokenInfos[0]->GetDcap())[0]); + ASSERT_EQ("ST_CAP", (tokenInfos[0]->GetDcap())[1]); + + ASSERT_EQ("process5", tokenInfos[1]->GetProcessName()); + ASSERT_EQ(678065606, tokenInfos[1]->GetTokenID()); + ASSERT_EQ(2, tokenInfos[1]->GetDcap().size()); + ASSERT_EQ("AT_CAP", (tokenInfos[1]->GetDcap())[0]); + ASSERT_EQ("ST_CAP", (tokenInfos[1]->GetDcap())[1]); +} + +/** + * @tc.name: ParserNativeRawData002 + * @tc.desc: Verify processing wrong native token json. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ParserNativeRawData002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ParserNativeRawData002!"); + std::string testStr = R"([{"processName":""}])"; + std::vector> tokenInfos; + + NativeTokenReceptor& receptor = NativeTokenReceptor::GetInstance(); + + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([{"processName":"", }])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([{"processName":"process6"}, {}])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([{"processName":""}, {"":"", ""}])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([{"processName":"process6", "tokenId":685266937, "APL":3, "version":new}])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([{"processName":"process6", "tokenId":685266937, "APL":7, "version":1}])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"({"NativeToken":[{"processName":"process6", "tokenId":685266937, "APL":7, "version":1}]})"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"({"NativeToken":[{"processName":"process6", "tokenId":685266937, "APL":7, "version":1}])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"(["NativeToken":])"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); + + testStr = R"([)"; + receptor.ParserNativeRawData(testStr, tokenInfos); + ASSERT_EQ(0, tokenInfos.size()); +} + +namespace OHOS { +namespace Security { +namespace AccessToken { + extern void from_json(const nlohmann::json& j, std::shared_ptr& p); +} +} +} + +/** + * @tc.name: from_json001 + * @tc.desc: Verify from json right case. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, from_json001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test from_json001!"); + nlohmann::json j = nlohmann::json{ + {"processName", "process6"}, + {"APL", APL_SYSTEM_CORE}, + {"version", 1}, + {"tokenId", 685266937}, + {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}, + {"permissions", {"ohos.permission.PLACE_CALL"}}, + {"nativeAcls", {"ohos.permission.PLACE_CALL"}}}; + std::shared_ptr p; + from_json(j, p); + ASSERT_NE((p == nullptr), true); +} + +/** + * @tc.name: from_json002 + * @tc.desc: Verify from json wrong case. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, from_json002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test from_json002!"); + // version wrong + nlohmann::json j = nlohmann::json{ + {"processName", "process6"}, {"APL", APL_SYSTEM_CORE}, + {"version", 2}, {"tokenId", 685266937}, + {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}}; + std::shared_ptr p; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); + + // APL wrong + j = nlohmann::json{ + {"processName", "process6"}, + {"APL", -1}, {"version", 1}, + {"tokenId", 685266937}, {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}}; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); + + // tokenId wrong + j = nlohmann::json{ + {"processName", "process6"}, + {"APL", APL_SYSTEM_BASIC}, {"version", 1}, + {"tokenId", 0}, {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}}; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); + + // process name empty + j = nlohmann::json{ + {"processName", ""}, + {"APL", APL_SYSTEM_BASIC}, {"version", 1}, + {"tokenId", 685266937}, {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}}; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); + + // process name too long + std::string name(512, 'c'); + j = nlohmann::json{ + {"processName", name}, + {"APL", APL_SYSTEM_BASIC}, {"version", 1}, + {"tokenId", 685266937}, {"tokenAttr", 0}, + {"dcaps", {"AT_CAP", "ST_CAP"}}}; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); + + // lose process name + j = nlohmann::json{ + {"APL", APL_SYSTEM_BASIC}, + {"version", 1}, {"tokenId", 685266937}, + {"tokenAttr", 0}, {"dcaps", {"AT_CAP", "ST_CAP"}}}; + from_json(j, p); + ASSERT_EQ((p == nullptr), true); +} + +/** + * @tc.name: ProcessNativeTokenInfos001 + * @tc.desc: test add one native token + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos001!"); + std::vector> tokenInfos; + + // test process one + NativeTokenInfo info = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test0", + .tokenID = 0x28100000, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + std::vector permStateList = {}; + std::shared_ptr nativeToken = std::make_shared(info, permStateList); + tokenInfos.emplace_back(nativeToken); + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info.apl); + ASSERT_EQ(findInfo.ver, info.ver); + ASSERT_EQ(findInfo.processName, info.processName); + ASSERT_EQ(findInfo.tokenID, info.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info.tokenAttr); + ASSERT_EQ(findInfo.dcap, info.dcap); + + // wait fresh tokens to sql. + sleep(3); + + // get sql data + std::vector nativeTokenResults; + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenResults); + std::vector permStateRes; + DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); + for (GenericValues nativeTokenValue : nativeTokenResults) { + AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(FIELD_TOKEN_ID); + if (tokenId != info.tokenID) { + continue; + } + GTEST_LOG_(INFO) <<"apl " << nativeTokenValue.GetInt(FIELD_APL); + std::shared_ptr native = std::make_shared(); + ASSERT_NE(native, nullptr); + ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue, permStateRes); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(native->GetTokenID(), info.tokenID); + ASSERT_EQ(native->GetProcessName(), info.processName); + ASSERT_EQ(native->GetDcap(), info.dcap); + } + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos002 + * @tc.desc: test add two native tokens. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos002!"); + std::vector> tokenInfos; + + NativeTokenInfo info1 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test1", + .tokenID = 0x28100001, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + NativeTokenInfo info2 = { + .apl = APL_SYSTEM_BASIC, + .ver = 1, + .processName = "native_token_test2", + .tokenID = 0x28100002, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + PermissionStateFull infoManagerTestState1 = { + .grantFlags = {0}, + .grantStatus = {0}, + .isGeneral = true, + .permissionName = "ohos.permission.ACCELEROMETER", + .resDeviceID = {"local"} + }; + + PermissionStateFull infoManagerTestState2 = { + .permissionName = "ohos.permission.MANAGE_USER_IDM", + .isGeneral = true, + .grantFlags = {0, 2}, + .grantStatus = {0, 0}, + .resDeviceID = {"device 1", "device 2"} + }; + + PermissionStateFull infoManagerTestState3 = { + .permissionName = "ohos.permission.USER_TEAT", + .isGeneral = true, + .grantFlags = {0, 2}, + .grantStatus = {0, 0}, + .resDeviceID = {"device 1", "device 2"} + }; + + std::vector permStateList = { + infoManagerTestState1, infoManagerTestState2, infoManagerTestState3}; + std::shared_ptr nativeToken1 = std::make_shared(info1, permStateList); + + std::shared_ptr permPolicySet = + nativeToken1->GetNativeInfoPermissionPolicySet(); + GTEST_LOG_(INFO) <<"permPolicySet: " << permPolicySet; + + std::vector permList; + permPolicySet->GetPermissionStateFulls(permList); + for (auto& perm : permList) { + GTEST_LOG_(INFO) <<"perm.permissionName: " << perm.permissionName; + } + + tokenInfos.emplace_back(nativeToken1); + + std::shared_ptr nativeToken2 = std::make_shared(info2, permStateList); + tokenInfos.emplace_back(nativeToken2); + + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + NativeTokenInfo findInfo; + + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info1.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info1.apl); + ASSERT_EQ(findInfo.ver, info1.ver); + ASSERT_EQ(findInfo.processName, info1.processName); + ASSERT_EQ(findInfo.tokenID, info1.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info1.tokenAttr); + ASSERT_EQ(findInfo.dcap, info1.dcap); + + ret = PermissionManager::GetInstance().VerifyAccessToken(info1.tokenID, "ohos.permission.MANAGE_USER_IDM"); + ASSERT_EQ(ret, PERMISSION_GRANTED); + ret = PermissionManager::GetInstance().VerifyAccessToken(info1.tokenID, "ohos.permission.ACCELEROMETER"); + ASSERT_EQ(ret, PERMISSION_GRANTED); + ret = PermissionManager::GetInstance().VerifyAccessToken(info1.tokenID, "ohos.permission.DISCOVER_BLUETOOTH"); + ASSERT_EQ(ret, PERMISSION_DENIED); + + ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info2.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info2.apl); + ASSERT_EQ(findInfo.ver, info2.ver); + ASSERT_EQ(findInfo.processName, info2.processName); + ASSERT_EQ(findInfo.tokenID, info2.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info2.tokenAttr); + ASSERT_EQ(findInfo.dcap, info2.dcap); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info1.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); + + ret = PermissionManager::GetInstance().VerifyAccessToken(info2.tokenID, "ohos.permission.MANAGE_USER_IDM"); + ASSERT_EQ(ret, PERMISSION_GRANTED); + ret = PermissionManager::GetInstance().VerifyAccessToken(info2.tokenID, "ohos.permission.ACCELEROMETER"); + ASSERT_EQ(ret, PERMISSION_GRANTED); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info2.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos003 + * @tc.desc: test add nullptr tokenInfo. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos003!"); + std::vector> tokenInfos; + + std::shared_ptr nativeToken1 = std::make_shared(); + tokenInfos.emplace_back(nativeToken1); + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + ASSERT_EQ(RET_SUCCESS, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos004 + * @tc.desc: test add repeat id, but process doesn't + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos004, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos004!"); + std::vector> tokenInfos; + + NativeTokenInfo info3 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test3", + .tokenID = 0x28100003, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + NativeTokenInfo info4 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test4", + .tokenID = 0x28100003, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + std::vector permStateList = {}; + std::shared_ptr nativeToken3 = std::make_shared(info3, permStateList); + tokenInfos.emplace_back(nativeToken3); + + std::shared_ptr nativeToken4 = std::make_shared(info4, permStateList); + tokenInfos.emplace_back(nativeToken4); + + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info3.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info3.apl); + ASSERT_EQ(findInfo.ver, info3.ver); + ASSERT_EQ(findInfo.processName, info3.processName); + ASSERT_EQ(findInfo.tokenID, info3.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info3.tokenAttr); + ASSERT_EQ(findInfo.dcap, info3.dcap); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info3.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos005 + * @tc.desc: test add repeat process, but id doesn't + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos005, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos005!"); + std::vector> tokenInfos; + + NativeTokenInfo info5 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test5", + .tokenID = 0x28100005, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + NativeTokenInfo info6 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test5", + .tokenID = 0x28100006, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + std::vector permStateList = {}; + std::shared_ptr nativeToken5 = std::make_shared(info5, permStateList); + tokenInfos.emplace_back(nativeToken5); + + std::shared_ptr nativeToken6 = std::make_shared(info6, permStateList); + tokenInfos.emplace_back(nativeToken6); + + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info5.tokenID, findInfo); + ASSERT_EQ(ret, RET_FAILED); + + ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info6.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info6.apl); + ASSERT_EQ(findInfo.ver, info6.ver); + ASSERT_EQ(findInfo.processName, info6.processName); + ASSERT_EQ(findInfo.tokenID, info6.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info6.tokenAttr); + ASSERT_EQ(findInfo.dcap, info6.dcap); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info6.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos006 + * @tc.desc: test add repeat process and id + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos006, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos006!"); + std::vector> tokenInfos; + + NativeTokenInfo info7 = { + .apl = APL_NORMAL, + .ver = 1, + .processName = "native_token_test7", + .tokenID = 0x28100007, + .tokenAttr = 0, + .dcap = {"AT_CAP", "ST_CAP"} + }; + + NativeTokenInfo info8 = { + .apl = APL_SYSTEM_BASIC, + .ver = 1, + .processName = "native_token_test7", + .tokenID = 0x28100007, + .tokenAttr = 0, + .dcap = {"AT_CAP"} + }; + std::vector permStateList = {}; + std::shared_ptr nativeToken7 = std::make_shared(info7, permStateList); + tokenInfos.emplace_back(nativeToken7); + + std::shared_ptr nativeToken8 = std::make_shared(info8, permStateList); + tokenInfos.emplace_back(nativeToken8); + + AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); + + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(info7.tokenID, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.apl, info8.apl); + ASSERT_EQ(findInfo.ver, info8.ver); + ASSERT_EQ(findInfo.processName, info8.processName); + ASSERT_EQ(findInfo.tokenID, info8.tokenID); + ASSERT_EQ(findInfo.tokenAttr, info8.tokenAttr); + ASSERT_EQ(findInfo.dcap, info8.dcap); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(info8.tokenID); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: init001 + * @tc.desc: test get native cfg + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, init001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test init001!"); + std::vector> tokenInfos; + + const char *dcaps[1]; + dcaps[0] = "AT_CAP_01"; + int dcapNum = 1; + const char *perms[2]; + perms[0] = "ohos.permission.test1"; + perms[1] = "ohos.permission.test2"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = dcapNum, + .permsNum = 2, + .aclsNum = 0, + .dcaps = dcaps, + .perms = perms, + .acls = nullptr, + .processName = "native_token_test7", + .aplStr = "system_core", + }; + uint64_t tokenId = ::GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenId, 0); + + NativeTokenReceptor::GetInstance().Init(); + NativeTokenInfo findInfo; + int ret = AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(tokenId, findInfo); + ASSERT_EQ(ret, RET_SUCCESS); + ASSERT_EQ(findInfo.processName, infoInstance.processName); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(tokenId); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: ProcessNativeTokenInfos007 + * @tc.desc: test get native cfg + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(NativeTokenReceptorTest, ProcessNativeTokenInfos007, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "test ProcessNativeTokenInfos007!"); + + const char *dcaps[1]; + dcaps[0] = "AT_CAP_01"; + int dcapNum = 1; + + char apl3[32]; + (void)strcpy_s(apl3, sizeof(apl3), "system_core"); + char apl2[32]; + (void)strcpy_s(apl2, sizeof(apl2), "system_basic"); + char apl1[32]; + (void)strcpy_s(apl1, sizeof(apl1), "normal"); + + NativeTokenInfoParams infoInstance = { + .dcapsNum = dcapNum, + .permsNum = 0, + .aclsNum = 0, + .dcaps = dcaps, + .perms = nullptr, + .acls = nullptr, + }; + infoInstance.aplStr = apl3; + infoInstance.processName = "ProcessNativeTokenInfos007_003"; + uint64_t tokenIdApl3 = ::GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenIdApl3, 0); + + infoInstance.aplStr = apl2; + infoInstance.processName = "ProcessNativeTokenInfos007_002"; + uint64_t tokenIdApl2 = ::GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenIdApl2, 0); + + infoInstance.aplStr = apl1; + infoInstance.processName = "ProcessNativeTokenInfos007_001"; + uint64_t tokenIdApl1 = ::GetAccessTokenId(&infoInstance); + ASSERT_NE(tokenIdApl1, 0); + + NativeTokenReceptor& receptor = NativeTokenReceptor::GetInstance(); + receptor.ready_ = false; + + receptor.Init(); + // wait fresh tokens to sql. + sleep(3); + + const std::string permission = "ohos.permission.SEND_MESSAGES"; + int ret = PermissionManager::GetInstance().VerifyNativeToken(tokenIdApl3, permission); + ASSERT_EQ(ret, PERMISSION_GRANTED); + + ret = PermissionManager::GetInstance().VerifyNativeToken(tokenIdApl2, permission); + ASSERT_EQ(ret, PERMISSION_GRANTED); + + ret = PermissionManager::GetInstance().VerifyNativeToken(tokenIdApl1, permission); + ASSERT_EQ(ret, PERMISSION_DENIED); + + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(tokenIdApl3); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(tokenIdApl2); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenInfoManager::GetInstance().RemoveNativeTokenInfo(tokenIdApl1); + ASSERT_EQ(ret, RET_SUCCESS); +} \ No newline at end of file diff --git a/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.h b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.h new file mode 100644 index 000000000..f03f06442 --- /dev/null +++ b/security_access_token-yl_0822/services/accesstokenmanager/test/unittest/cpp/src/native_token_receptor_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_TOKEN_RECEPTOR_TEST_H +#define NATIVE_TOKEN_RECEPTOR_TEST_H + +#include +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class NativeTokenReceptorTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // NATIVE_TOKEN_RECEPTOR_TEST_H diff --git a/security_access_token-yl_0822/services/common/database/BUILD.gn b/security_access_token-yl_0822/services/common/database/BUILD.gn new file mode 100644 index 000000000..99beae0ed --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_shared_library("accesstoken_database_cxx") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ "include" ] + + sources = [ + "src/generic_values.cpp", + "src/sqlite_helper.cpp", + "src/statement.cpp", + "src/variant_value.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//third_party/sqlite:sqlite", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + if (build_selinux) { + external_deps += [ "selinux:librestorecon" ] + cflags_cc += [ "-DWITH_SELINUX" ] + } +} diff --git a/security_access_token-yl_0822/services/common/database/include/field_const.h b/security_access_token-yl_0822/services/common/database/include/field_const.h new file mode 100644 index 000000000..aaa185f04 --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/include/field_const.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIELD_CONST_H +#define FIELD_CONST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string FIELD_TOKEN_ID = "token_id"; +const std::string FIELD_USER_ID = "user_id"; +const std::string FIELD_BUNDLE_NAME = "bundle_name"; +const std::string FIELD_INST_INDEX = "inst_index"; +const std::string FIELD_DLP_TYPE = "dlp_type"; +const std::string FIELD_APP_ID = "app_id"; +const std::string FIELD_DEVICE_ID = "device_id"; +const std::string FIELD_APL = "apl"; +const std::string FIELD_TOKEN_VERSION = "token_version"; +const std::string FIELD_TOKEN_ATTR = "token_attr"; +const std::string FIELD_PROCESS_NAME = "process_name"; +const std::string FIELD_DCAP = "dcap"; +const std::string FIELD_NATIVE_ACLS = "native_acls"; +const std::string FIELD_PERMISSION_NAME = "permission_name"; +const std::string FIELD_GRANT_MODE = "grant_mode"; +const std::string FIELD_AVAILABLE_LEVEL = "available_level"; +const std::string FIELD_PROVISION_ENABLE = "provision_enable"; +const std::string FIELD_DISTRIBUTED_SCENE_ENABLE = "distributed_scene_enable"; +const std::string FIELD_LABEL = "label"; +const std::string FIELD_LABEL_ID = "label_id"; +const std::string FIELD_DESCRIPTION = "description"; +const std::string FIELD_DESCRIPTION_ID = "description_id"; +const std::string FIELD_GRANT_STATE = "grant_state"; +const std::string FIELD_GRANT_FLAG = "grant_flag"; +const std::string FIELD_GRANT_IS_GENERAL = "is_general"; + +const std::string FIELD_OP_CODE = "op_code"; +const std::string FIELD_STATUS = "status"; +const std::string FIELD_TIMESTAMP = "timestamp"; +const std::string FIELD_ACCESS_DURATION = "access_duration"; +const std::string FIELD_ACCESS_COUNT = "access_count"; +const std::string FIELD_REJECT_COUNT = "reject_count"; + +const std::string FIELD_TIMESTAMP_BEGIN = "timestamp_begin"; +const std::string FIELD_TIMESTAMP_END = "timestamp_end"; +const std::string FIELD_FLAG = "flag"; + +const std::string FIELD_API_VERSION = "api_version"; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // FIELD_CONST_H diff --git a/security_access_token-yl_0822/services/common/database/include/generic_values.h b/security_access_token-yl_0822/services/common/database/include/generic_values.h new file mode 100644 index 000000000..beaf7384a --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/include/generic_values.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GENERIC_VALUES_H +#define GENERIC_VALUES_H + +#include +#include +#include + +#include "variant_value.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class GenericValues final { +public: + GenericValues() = default; + virtual ~GenericValues() = default; + + void Put(const std::string& key, int32_t value); + + void Put(const std::string& key, int64_t value); + + void Put(const std::string& key, const std::string& value); + + void Put(const std::string& key, const VariantValue& value); + + std::vector GetAllKeys() const; + + VariantValue Get(const std::string& key) const; + + int32_t GetInt(const std::string& key) const; + + int64_t GetInt64(const std::string& key) const; + + std::string GetString(const std::string& key) const; + + void Remove(const std::string& key); +private: + std::map map_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // GENERIC_VALUES_H diff --git a/security_access_token-yl_0822/services/common/database/include/sqlite_helper.h b/security_access_token-yl_0822/services/common/database/include/sqlite_helper.h new file mode 100644 index 000000000..eec1f54f0 --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/include/sqlite_helper.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SQLITE_HELPER_H +#define SQLITE_HELPER_H + +#include + +#include "statement.h" + +#include "sqlite3sym.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SqliteHelper { +public: + explicit SqliteHelper(const std::string& dbName, const std::string& dbPath, int32_t version); + virtual ~SqliteHelper(); + + void Open(); + void Close(); + + int32_t BeginTransaction() const; + int32_t CommitTransaction() const; + int32_t RollbackTransaction() const; + + Statement Prepare(const std::string& sql) const; + int32_t ExecuteSql(const std::string& sql) const; + std::string SpitError() const; + + virtual void OnCreate() = 0; + virtual void OnUpdate() = 0; + +private: + inline static const std::string PRAGMA_VERSION_COMMAND = "PRAGMA user_version"; + static const int32_t GENERAL_ERROR = -1; + + const std::string dbName_; + const std::string dbPath_; + int32_t currentVersion_; + sqlite3* db_; + + int32_t GetVersion() const; + void SetVersion() const; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SQLITE_HELPER_H diff --git a/security_access_token-yl_0822/services/common/database/include/statement.h b/security_access_token-yl_0822/services/common/database/include/statement.h new file mode 100644 index 000000000..f2280cf0d --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/include/statement.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STATEMENT_H +#define STATEMENT_H + +#include + +#include "variant_value.h" + +#include "sqlite3sym.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class Statement final { +public: + enum State { BUSY, ROW, DONE, MISUSE, UNKNOWN }; + + Statement(sqlite3* db, const std::string& sql); + virtual ~Statement(); + + void Bind(const int32_t index, const std::string& text); + void Bind(const int32_t index, int32_t value); + void Bind(const int32_t index, int64_t value); + void Bind(const std::string& tableColumnName, const VariantValue& value); + + State Step(); + int32_t Reset(); + + std::string GetColumnString(const int32_t column) const; + int32_t GetColumnInt(const int32_t column) const; + int64_t GetColumnInt64(const int32_t column) const; + std::string GetColumnName(const int32_t column) const; + int32_t GetParameterIndex(const std::string& name) const; + int32_t GetColumnCount() const; + VariantValue GetValue(const int32_t column, const bool flagInt64) const; + +private: + sqlite3* db_; + sqlite3_stmt* statement_; + const std::string sql_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // STATEMENT_H diff --git a/security_access_token-yl_0822/services/common/database/include/variant_value.h b/security_access_token-yl_0822/services/common/database/include/variant_value.h new file mode 100644 index 000000000..aab2dba2f --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/include/variant_value.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef VARIANT_VALUE_H +#define VARIANT_VALUE_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ValueType { + TYPE_NULL, + TYPE_INT, + TYPE_INT64, + TYPE_STRING, +}; + +class VariantValue final { +public: + VariantValue(); + virtual ~VariantValue(); + + explicit VariantValue(int32_t value); + explicit VariantValue(int64_t value); + explicit VariantValue(const std::string& value); + + ValueType GetType() const; + int32_t GetInt() const; + int64_t GetInt64() const; + std::string GetString() const; + + static const int32_t DEFAULT_VALUE = -1; + +private: + ValueType type_; + std::variant value_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // VARIANT_VALUE_H diff --git a/security_access_token-yl_0822/services/common/database/src/generic_values.cpp b/security_access_token-yl_0822/services/common/database/src/generic_values.cpp new file mode 100644 index 000000000..c80ad00ae --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/src/generic_values.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +void GenericValues::Put(const std::string& key, int32_t value) +{ + map_.insert(std::make_pair(key, VariantValue(value))); +} + +void GenericValues::Put(const std::string& key, int64_t value) +{ + map_.insert(std::make_pair(key, VariantValue(value))); +} + +void GenericValues::Put(const std::string& key, const std::string& value) +{ + map_.insert(std::make_pair(key, VariantValue(value))); +} + +void GenericValues::Put(const std::string& key, const VariantValue& value) +{ + map_.insert(std::make_pair(key, value)); +} + +VariantValue GenericValues::Get(const std::string& key) const +{ + auto iter = map_.find(key); + if (iter == map_.end()) { + return VariantValue(); + } + return iter->second; +} + +int32_t GenericValues::GetInt(const std::string& key) const +{ + auto it = map_.find(key); + if (it == map_.end()) { + return VariantValue::DEFAULT_VALUE; + } + return it->second.GetInt(); +} + +int64_t GenericValues::GetInt64(const std::string& key) const +{ + auto it = map_.find(key); + if (it == map_.end()) { + return VariantValue::DEFAULT_VALUE; + } + return it->second.GetInt64(); +} + +std::string GenericValues::GetString(const std::string& key) const +{ + auto it = map_.find(key); + if (it == map_.end()) { + return std::string(); + } + return it->second.GetString(); +} + +std::vector GenericValues::GetAllKeys() const +{ + std::vector keys; + for (auto it = map_.begin(); it != map_.end(); ++it) { + keys.emplace_back(it->first); + } + return keys; +} + +void GenericValues::Remove(const std::string& key) +{ + if (map_.count(key) > 0) { + map_.erase(key); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/common/database/src/sqlite_helper.cpp b/security_access_token-yl_0822/services/common/database/src/sqlite_helper.cpp new file mode 100644 index 000000000..b3f36752c --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/src/sqlite_helper.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sqlite_helper.h" + +#include "accesstoken_log.h" +#ifdef WITH_SELINUX +#include +#endif // WITH_SELINUX + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SqliteHelper"}; +} + +SqliteHelper::SqliteHelper(const std::string& dbName, const std::string& dbPath, int32_t version) + : dbName_(dbName), dbPath_(dbPath), currentVersion_(version), db_(nullptr) +{} + +SqliteHelper::~SqliteHelper() +{} + +void SqliteHelper::Open() +{ + if (db_ != nullptr) { + return; + } + if (dbName_.empty() || dbPath_.empty() || currentVersion_ < 0) { + return; + } + std::string fileName = dbPath_ + dbName_; + int32_t res = sqlite3_open(fileName.c_str(), &db_); + if (res != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to open db: %{public}s", sqlite3_errmsg(db_)); + return; + } + +#ifdef WITH_SELINUX + Restorecon(fileName.c_str()); +#endif // WITH_SELINUX + + int32_t version = GetVersion(); + if (version == currentVersion_) { + return; + } + + BeginTransaction(); + if (version == 0) { + OnCreate(); + } else { + if (version < currentVersion_) { + OnUpdate(); + } + } + SetVersion(); + CommitTransaction(); +} + +void SqliteHelper::Close() +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return; + } + int32_t ret = sqlite3_close(db_); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_WARN(LABEL, "sqlite3_close error, ret=%{public}d", ret); + return; + } + db_ = nullptr; +} + +int32_t SqliteHelper::BeginTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int32_t result = 0; + int32_t ret = sqlite3_exec(db_, "BEGIN;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int32_t SqliteHelper::CommitTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int32_t result = 0; + int32_t ret = sqlite3_exec(db_, "COMMIT;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int32_t SqliteHelper::RollbackTransaction() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return GENERAL_ERROR; + } + int32_t result = 0; + char* errorMessage = nullptr; + int32_t ret = sqlite3_exec(db_, "ROLLBACK;", nullptr, nullptr, &errorMessage); + if (ret != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +Statement SqliteHelper::Prepare(const std::string& sql) const +{ + return Statement(db_, sql); +} + +int32_t SqliteHelper::ExecuteSql(const std::string& sql) const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return GENERAL_ERROR; + } + char* errorMessage = nullptr; + int32_t result = 0; + int32_t res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &errorMessage); + if (res != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); + result = GENERAL_ERROR; + } + sqlite3_free(errorMessage); + return result; +} + +int32_t SqliteHelper::GetVersion() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return GENERAL_ERROR; + } + auto statement = Prepare(PRAGMA_VERSION_COMMAND); + int32_t version = 0; + while (statement.Step() == Statement::State::ROW) { + version = statement.GetColumnInt(0); + } + ACCESSTOKEN_LOG_INFO(LABEL, "version: %{public}d", version); + return version; +} + +void SqliteHelper::SetVersion() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return; + } + auto statement = Prepare(PRAGMA_VERSION_COMMAND + " = " + std::to_string(currentVersion_)); + statement.Step(); +} + +std::string SqliteHelper::SpitError() const +{ + if (db_ == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); + return ""; + } + return sqlite3_errmsg(db_); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/common/database/src/statement.cpp b/security_access_token-yl_0822/services/common/database/src/statement.cpp new file mode 100644 index 000000000..7e33e1e06 --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/src/statement.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "statement.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "Statement"}; +} + +Statement::Statement(sqlite3* db, const std::string& sql) : db_(db), sql_(sql) +{ + if (sqlite3_prepare_v2(db, sql.c_str(), sql.size(), &statement_, nullptr) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot prepare, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +Statement::~Statement() +{ + sqlite3_finalize(statement_); + statement_ = nullptr; +} + +void Statement::Bind(const int32_t index, const std::string& text) +{ + if (sqlite3_bind_text(statement_, index, text.c_str(), text.size(), SQLITE_TRANSIENT) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind string, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +void Statement::Bind(const int32_t index, int32_t value) +{ + if (sqlite3_bind_int(statement_, index, value) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind int32_t, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +void Statement::Bind(const int32_t index, int64_t value) +{ + if (sqlite3_bind_int(statement_, index, value) != SQLITE_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind int32_t, errorMsg: %{public}s", sqlite3_errmsg(db_)); + } +} + +int32_t Statement::GetColumnInt(const int32_t column) const +{ + return sqlite3_column_int(statement_, column); +} + +int64_t Statement::GetColumnInt64(const int32_t column) const +{ + return sqlite3_column_int64(statement_, column); +} + +std::string Statement::GetColumnString(const int32_t column) const +{ + return std::string(reinterpret_cast(sqlite3_column_text(statement_, column))); +} + +std::string Statement::GetColumnName(const int32_t column) const +{ + return sqlite3_column_name(statement_, column); +} + +Statement::State Statement::Step() +{ + int32_t ret = sqlite3_step(statement_); + switch (ret) { + case SQLITE_ROW: + return Statement::State::ROW; + case SQLITE_DONE: + return Statement::State::DONE; + case SQLITE_BUSY: + return Statement::State::BUSY; + case SQLITE_MISUSE: + return Statement::State::MISUSE; + default: + return Statement::State::UNKNOWN; + } +} + +int32_t Statement::GetParameterIndex(const std::string& name) const +{ + return sqlite3_bind_parameter_index(statement_, name.c_str()); +} + +void Statement::Bind(const std::string& tableColumnName, const VariantValue& value) +{ + int32_t index = GetParameterIndex(":" + tableColumnName); + if (value.GetType() == ValueType::TYPE_STRING) { + Bind(index, value.GetString()); + } else if (value.GetType() == ValueType::TYPE_INT) { + Bind(index, value.GetInt()); + } else if (value.GetType() == ValueType::TYPE_INT64) { + Bind(index, value.GetInt64()); + } +} + +int32_t Statement::Reset() +{ + return sqlite3_reset(statement_); +} + +int32_t Statement::GetColumnCount() const +{ + return sqlite3_column_count(statement_); +} + +VariantValue Statement::GetValue(const int32_t column, const bool flagInt64) const +{ + int32_t type = sqlite3_column_type(statement_, column); + switch (type) { + case SQLITE_INTEGER: + if (flagInt64) { + return VariantValue(GetColumnInt64(column)); + } else { + return VariantValue(GetColumnInt(column)); + } + case SQLITE_TEXT: + return VariantValue(GetColumnString(column)); + default: + return VariantValue(); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/common/database/src/variant_value.cpp b/security_access_token-yl_0822/services/common/database/src/variant_value.cpp new file mode 100644 index 000000000..17f7a0a26 --- /dev/null +++ b/security_access_token-yl_0822/services/common/database/src/variant_value.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "variant_value.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +VariantValue::VariantValue() : type_(ValueType::TYPE_NULL) +{} + +VariantValue::~VariantValue() +{} + +VariantValue::VariantValue(int32_t value) : type_(ValueType::TYPE_INT) +{ + value_ = value; +} + +VariantValue::VariantValue(int64_t value) : type_(ValueType::TYPE_INT64) +{ + value_ = value; +} + +VariantValue::VariantValue(const std::string& value) : type_(ValueType::TYPE_STRING) +{ + value_ = value; +} + +ValueType VariantValue::GetType() const +{ + return type_; +} + +int32_t VariantValue::GetInt() const +{ + if (type_ != ValueType::TYPE_INT) { + return DEFAULT_VALUE; + } + + return std::get(value_); +} + +int64_t VariantValue::GetInt64() const +{ + if (type_ != ValueType::TYPE_INT64) { + return DEFAULT_VALUE; + } + + return std::get(value_); +} + +std::string VariantValue::GetString() const +{ + if (type_ != ValueType::TYPE_STRING) { + return std::string(); + } + + return std::get(value_); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/BUILD.gn b/security_access_token-yl_0822/services/privacymanager/BUILD.gn new file mode 100644 index 000000000..a6db98aa7 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_prebuilt_etc("privacy.rc") { + source = "privacy.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "access_token" +} + +if (is_standard_system) { + ohos_shared_library("privacy_manager_service") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "include/active", + "include/common", + "include/database", + "include/record", + "include/service", + "//base/security/access_token/frameworks/privacy/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "//base/security/access_token/services/common/database/include", + "//third_party/json/include", + ] + + sources = [ + "src/active/active_status_callback_manager.cpp", + "src/active/perm_active_status_callback_death_recipient.cpp", + "src/active/perm_active_status_change_callback_proxy.cpp", + "src/common/constant.cpp", + "src/common/time_util.cpp", + "src/common/to_string.cpp", + "src/database/data_translator.cpp", + "src/database/permission_used_record_db.cpp", + "src/record/on_permission_used_record_callback_proxy.cpp", + "src/record/on_permission_used_record_callback_stub.cpp", + "src/record/permission_record.cpp", + "src/record/permission_record_manager.cpp", + "src/record/permission_record_repository.cpp", + "src/record/permission_used_record_cache.cpp", + "src/service/privacy_manager_service.cpp", + "src/service/privacy_manager_stub.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/frameworks/privacy:privacy_communication_adapter_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/services/common/database:accesstoken_database_cxx", + "//base/security/access_token/services/privacymanager:privacy.rc", + "//third_party/sqlite:sqlite", + "//utils/native/base:utils", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + } +} diff --git a/security_access_token-yl_0822/services/privacymanager/include/active/active_status_callback_manager.h b/security_access_token-yl_0822/services/privacymanager/include/active/active_status_callback_manager.h new file mode 100644 index 000000000..df6d801ae --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/active/active_status_callback_manager.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACTIVE_STATUS_CHANGE_CALLBACK_MANAGER_H +#define ACTIVE_STATUS_CHANGE_CALLBACK_MANAGER_H + +#include +#include + +#include "access_token.h" +#include "accesstoken_log.h" +#include "perm_active_status_callback_death_recipient.h" +#include "perm_active_status_change_callback_proxy.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct CallbackData { + CallbackData() : permList_(), callbackObject_(nullptr) + {} + CallbackData(const std::vector& permList, sptr callback) + : permList_(permList), callbackObject_(callback) + {} + + std::vector permList_; + sptr callbackObject_; +}; + +class ActiveStatusCallbackManager { +public: + virtual ~ActiveStatusCallbackManager(); + ActiveStatusCallbackManager(); + static ActiveStatusCallbackManager& GetInstance(); + + int32_t AddCallback( + const std::vector& permList, const sptr& callback); + int32_t RemoveCallback(const sptr& callback); + bool NeedCalled(const std::vector& permList, const std::string& permName); + void ExecuteCallbackAsync( + AccessTokenID tokenId, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType); + +private: + std::mutex mutex_; + std::vector callbackDataList_; + sptr callbackDeathRecipient_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACTIVE_STATUS_CHANGE_CALLBACK_MANAGER_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_callback_death_recipient.h b/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_callback_death_recipient.h new file mode 100644 index 000000000..c69e05e3e --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_callback_death_recipient.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_STATUS_CALLBACK_DEATH_RECIPIENT_H +#define PERM_ACTIVE_STATUS_CALLBACK_DEATH_RECIPIENT_H + + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusCallbackDeathRecipient : public IRemoteObject::DeathRecipient { +public: + PermActiveStatusCallbackDeathRecipient() = default; + virtual ~PermActiveStatusCallbackDeathRecipient() = default; + + virtual void OnRemoteDied(const wptr &remote); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERM_ACTIVE_STATUS_CALLBACK_DEATH_RECIPIENT_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_change_callback_proxy.h b/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_change_callback_proxy.h new file mode 100644 index 000000000..db358c94b --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/active/perm_active_status_change_callback_proxy.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERM_ACTIVE_STATUS_CHANGE_CALLBACK_PROXY_H +#define PERM_ACTIVE_STATUS_CHANGE_CALLBACK_PROXY_H + + +#include "i_perm_active_status_callback.h" + +#include "iremote_proxy.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusChangeCallbackProxy : public IRemoteProxy { +public: + explicit PermActiveStatusChangeCallbackProxy(const sptr& impl); + ~PermActiveStatusChangeCallbackProxy() override; + + virtual void ActiveStatusChangeCallback(ActiveChangeResponse& result) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERM_ACTIVE_STATUS_CHANGE_CALLBACK_PROXY_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/common/constant.h b/security_access_token-yl_0822/services/privacymanager/include/common/constant.h new file mode 100644 index 000000000..1893d77e3 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/common/constant.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CONSTANT_H +#define CONSTANT_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class Constant { +public: + enum OpCode { + OP_INVALID = -1, + OP_ANSWER_CALL = 0, + OP_READ_CALENDAR = 1, + OP_WRITE_CALENDAR = 2, + OP_SEND_MESSAGES = 3, + OP_WRITE_CALL_LOG = 4, + OP_READ_CALL_LOG = 5, + OP_READ_CELL_MESSAGES = 6, + OP_MICROPHONE = 7, + OP_RECEIVE_WAP_MESSAGES = 8, + OP_RECEIVE_SMS = 9, + OP_RECEIVE_MMS = 10, + OP_READ_MESSAGES = 11, + OP_READ_CONTACTS = 12, + OP_WRITE_CONTACTS = 13, + OP_LOCATION_IN_BACKGROUND = 14, + OP_LOCATION = 15, + OP_MEDIA_LOCATION = 16, + OP_CAMERA = 17, + OP_READ_MEDIA = 18, + OP_WRITE_MEDIA = 19, + OP_ACTIVITY_MOTION = 20, + OP_READ_HEALTH_DATA = 21, + OP_MANAGE_VOICEMAIL = 22, + OP_DISTRIBUTED_DATASYNC = 23, + }; + + enum ErrorCode { + FAILURE = -1, + SUCCESS = 0, + }; + + const static int32_t MAX_TOTAL_RECORD = 10000; + const static int32_t MAX_DETAIL_RECORD = 10; + const static int32_t RECORD_DELETE_TIME = 30 * 86400; + const static int32_t PRECISE = 60; + const static int32_t LATEST_RECORD_TIME = 7 * 86400; + const static std::string COUNT_CMD; + + const static std::map PERMISSION_OPCODE_MAP; +public: + static bool TransferPermissionToOpcode(const std::string& permissionName, int32_t& opCode); + static bool TransferOpcodeToPermission(int32_t opCode, std::string& permissionName); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // CONSTANT_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/common/time_util.h b/security_access_token-yl_0822/services/privacymanager/include/common/time_util.h new file mode 100644 index 000000000..064e68486 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/common/time_util.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TIME_UTIL_H +#define TIME_UTIL_H +#include +namespace OHOS { +namespace Security { +namespace AccessToken { +class TimeUtil { +public: + static int64_t GetCurrentTimestamp(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // TIME_UTIL_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/common/to_string.h b/security_access_token-yl_0822/services/privacymanager/include/common/to_string.h new file mode 100644 index 000000000..de6dd9290 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/common/to_string.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TO_STRING_H +#define TO_STRING_H + +#include +#include "permission_used_request.h" +#include "permission_used_result.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class ToString { +public: + static void DetailUsedRecordToString( + bool isAccessDetail, const std::vector& detailRecord, std::string& infos); + static void PermissionUsedRecordToString( + const std::vector& permissionRecords, std::string& infos); + static void BundleUsedRecordToString(const BundleUsedRecord& bundleRecord, std::string& infos); + static void PermissionUsedResultToString(const PermissionUsedResult& result, std::string& infos); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TO_STRING_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/database/data_translator.h b/security_access_token-yl_0822/services/privacymanager/include/database/data_translator.h new file mode 100644 index 000000000..488d887ff --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/database/data_translator.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_TRANSLATOR_H +#define DATA_TRANSLATOR_H + +#include + +#include "permission_used_request.h" +#include "permission_used_result.h" +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DataTranslator final { +public: + static int32_t TranslationIntoGenericValues(const PermissionUsedRequest& request, + GenericValues& andGenericValues, GenericValues& orGenericValues); + static int32_t TranslationGenericValuesIntoPermissionUsedRecord( + const GenericValues& inGenericValues, PermissionUsedRecord& permissionRecord); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DATA_TRANSLATOR_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/database/permission_used_record_db.h b/security_access_token-yl_0822/services/privacymanager/include/database/permission_used_record_db.h new file mode 100644 index 000000000..6b1192669 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/database/permission_used_record_db.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RECORD_DB_H +#define PERMISSION_USED_RECORD_DB_H + +#include "generic_values.h" +#include "sqlite_helper.h" + +#include "nocopyable.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct SqliteTable { +public: + std::string tableName_; + std::vector tableColumnNames_; +}; +class PermissionUsedRecordDb : public SqliteHelper { +public: + enum DataType { + PERMISSION_RECORD, + }; + enum ExecuteResult { FAILURE = -1, SUCCESS }; + static PermissionUsedRecordDb& GetInstance(); + + ~PermissionUsedRecordDb() override; + + int32_t Add(DataType type, const std::vector& values); + int32_t Remove(DataType type, const GenericValues& conditions); + int32_t FindByConditions(DataType type, const GenericValues& andConditions, + const GenericValues& orConditions, std::vector& results); + int32_t Modify(DataType type, const GenericValues& modifyValues, const GenericValues& conditions); + int32_t Count(DataType type, GenericValues& result); + int32_t DeleteExpireRecords(DataType type, const GenericValues& andConditions); + int32_t DeleteExcessiveRecords(DataType type, unsigned excessiveSize); + int32_t GetDistinctValue(DataType type, const std::string& condition, std::vector& results); + + void OnCreate() override; + void OnUpdate() override; + +private: + PermissionUsedRecordDb(); + DISALLOW_COPY_AND_MOVE(PermissionUsedRecordDb); + + std::map dataTypeToSqlTable_; + OHOS::Utils::RWLock rwLock_; + + int32_t CreatePermissionRecordTable() const; + + std::string CreateInsertPrepareSqlCmd(DataType type) const; + std::string CreateDeletePrepareSqlCmd( + DataType type, const std::vector& columnNames = std::vector()) const; + std::string CreateSelectByConditionPrepareSqlCmd(DataType type, + const std::vector& andColumns, const std::vector& orColumns) const; + std::string CreateUpdatePrepareSqlCmd(DataType type, const std::vector& modifyColumns, + const std::vector& conditionColumns) const; + std::string CreateCountPrepareSqlCmd(DataType type) const; + std::string CreateDeleteExpireRecordsPrepareSqlCmd(DataType type, + const std::vector& andColumns) const; + std::string CreateDeleteExcessiveRecordsPrepareSqlCmd(DataType type, uint32_t excessiveSize) const; + std::string CreateGetDistinctValue(DataType type, const std::string conditionColumns) const; + +private: + inline static const std::string PERMISSION_RECORD_TABLE = "permission_record_table"; + inline static const std::string DATABASE_NAME = "permission_used_record.db"; + inline static const std::string DATABASE_PATH = "/data/service/el1/public/access_token/"; + static const int32_t DATABASE_VERSION = 1; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // PERMISSION_USED_RECORD_DB_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_proxy.h b/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_proxy.h new file mode 100644 index 000000000..3a6975bd0 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_proxy.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ON_PERMISSION_USED_RECORD_CALLBACK_PROXY_H +#define ON_PERMISSION_USED_RECORD_CALLBACK_PROXY_H + + +#include "on_permission_used_record_callback.h" + +#include "iremote_proxy.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class OnPermissionUsedRecordCallbackProxy : public IRemoteProxy { +public: + explicit OnPermissionUsedRecordCallbackProxy(const sptr& impl); + ~OnPermissionUsedRecordCallbackProxy() override; + + virtual void OnQueried(ErrCode code, PermissionUsedResult& result) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ON_PERMISSION_USED_RECORD_CALLBACK_PROXY_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_stub.h b/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_stub.h new file mode 100644 index 000000000..b6120fe1b --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/on_permission_used_record_callback_stub.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ON_PERMISSION_USED_RECORD_CALLBACK_STUB_H +#define ON_PERMISSION_USED_RECORD_CALLBACK_STUB_H + + +#include "on_permission_used_record_callback.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class OnPermissionUsedRecordCallbackStub : public IRemoteStub { +public: + OnPermissionUsedRecordCallbackStub() = default; + virtual ~OnPermissionUsedRecordCallbackStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ON_PERMISSION_USED_RECORD_CALLBACK_STUB_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/permission_record.h b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record.h new file mode 100644 index 000000000..f2c0abb07 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_RECORD_H +#define PERMISSION_RECORD_H + +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionRecord { + uint32_t tokenId = 0; + int32_t opCode = 0; + int32_t status = 0; + int64_t timestamp = 0L; + int64_t accessDuration = 0L; + int32_t accessCount = 0; + int32_t rejectCount = 0; + + PermissionRecord() = default; + + static void TranslationIntoGenericValues(const PermissionRecord& record, GenericValues& values); + static void TranslationIntoPermissionRecord(const GenericValues& values, PermissionRecord& record); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_RECORD_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_manager.h b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_manager.h new file mode 100644 index 000000000..b100bef9c --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_manager.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_RECORD_MANAGER_H +#define PERMISSION_RECORD_MANAGER_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "nocopyable.h" +#include "on_permission_used_record_callback.h" +#include "permission_record.h" +#include "permission_used_request.h" +#include "permission_used_result.h" + +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionRecordManager final { +public: + static PermissionRecordManager& GetInstance(); + virtual ~PermissionRecordManager(); + + void Init(); + int32_t AddPermissionUsedRecord( + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount); + void RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID); + int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); + int32_t GetPermissionUsedRecordsAsync( + const PermissionUsedRequest& request, const sptr& callback); + std::string DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName); + int32_t StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName); + int32_t StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName); + int32_t RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback); + int32_t UnRegisterPermActiveStatusCallback(const sptr& callback); + bool IsAllowUsingPermission(AccessTokenID tokenId, const std::string& permissionName); +private: + PermissionRecordManager(); + DISALLOW_COPY_AND_MOVE(PermissionRecordManager); + + bool GetLocalRecordTokenIdList(std::set& tokenIdList); + int32_t AddRecord(const PermissionRecord& record); + bool GetPermissionsRecord(AccessTokenID tokenId, const std::string& permissionName, + int32_t successCount, int32_t failCount, PermissionRecord& record); + bool CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord); + void ExecuteDeletePermissionRecordTask(); + int32_t DeletePermissionRecord(int32_t days); + bool GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result); + bool GetRecords(int32_t flag, std::vector recordValues, + BundleUsedRecord& bundleRecord, PermissionUsedResult& result); + void UpdateRecords(int32_t flag, const PermissionUsedRecord& inBundleRecord, PermissionUsedRecord& outBundleRecord); + + std::string GetDeviceId(AccessTokenID tokenId); + + OHOS::ThreadPool deleteTaskWorker_; + bool hasInited_; + OHOS::Utils::RWLock rwLock_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_RECORD_MANAGER_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_node.h b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_node.h new file mode 100644 index 000000000..d56b3d800 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_node.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_UESD_RECORD_NODE_H +#define PERMISSION_UESD_RECORD_NODE_H + +#include +#include "permission_record.h" +#include "rwlock.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +struct PermissionUsedRecordNode { + std::weak_ptr pre; + std::shared_ptr next; + PermissionRecord record; + + PermissionUsedRecordNode() = default; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_UESD_RECORD_NODE_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_repository.h b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_repository.h new file mode 100644 index 000000000..0e249f33d --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/permission_record_repository.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_RECORD_REPOSITORY_H +#define PERMISSION_RECORD_REPOSITORY_H + +#include +#include "generic_values.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionRecordRepository final { +public: + virtual ~PermissionRecordRepository(); + PermissionRecordRepository(); + + static PermissionRecordRepository& GetInstance(); + + bool AddRecordValues(const std::vector& recordValues); + bool FindRecordValues(const GenericValues& andConditionValues, + const GenericValues& orConditionValues, std::vector& recordValues); + bool RemoveRecordValues(const GenericValues& conditionValues); + bool GetAllRecordValuesByKey(const std::string& condition, std::vector& resultValues); + int32_t CountRecordValues(GenericValues& resultValues); + bool DeleteExpireRecordsValues(const GenericValues& andConditions); + bool DeleteExcessiveSizeRecordValues(uint32_t excessiveSize); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_RECORD_REPOSITORY_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/record/permission_used_record_cache.h b/security_access_token-yl_0822/services/privacymanager/include/record/permission_used_record_cache.h new file mode 100644 index 000000000..6f6745e60 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/record/permission_used_record_cache.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RECORD_CACHE_H +#define PERMISSION_USED_RECORD_CACHE_H + +#include +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "nocopyable.h" +#include "permission_record.h" +#include "permission_record_node.h" +#include "rwlock.h" +#include "thread_pool.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionUsedRecordCache { +public: + static PermissionUsedRecordCache& GetInstance(); + int32_t AddRecordToBuffer(PermissionRecord& record); + void MergeRecord(PermissionRecord& record, std::shared_ptr curFindMergePos); + void AddToPersistQueue(const std::shared_ptr persistPendingBufferHead); + void ExecuteReadRecordBufferTask(); + int32_t PersistPendingRecords(); + void GetPersistPendingRecordsAndReset(); + int32_t RemoveRecords(const GenericValues &record); + void RemoveRecordsFromPersistPendingBufferQueue(const GenericValues &record, + std::shared_ptr persistPendingBufferHead, + std::shared_ptr persistPendingBufferEnd); + void GetRecords(const std::vector& permissionList, + const GenericValues &andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues); + void GetAllRecords(const std::vector& permissionList, + const GenericValues &andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues); + void GetRecordsFromPersistPendingBufferQueue(const std::vector& permissionList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues, const std::set& opCodeList); + bool RecordCompare(const AccessTokenID tokenId, const std::set& opCodeList, + const GenericValues &andConditionValues, const PermissionRecord &record); + void FindTokenIdList(std::set& tokenIdList); + void TransferToOpcode(std::set& opCodeList, + const std::vector& permissionList); + void AddRecordNode(const PermissionRecord& record); + void DeleteRecordNode(std::shared_ptr deleteRecordNode); + +private: + int32_t readableSize_ = 0; + std::shared_ptr recordBufferHead_ = std::make_shared(); + std::shared_ptr curRecordBufferPos_ = recordBufferHead_; + std::vector> persistPendingBufferQueue_; + int64_t nextPersistTimestamp_ = 0L; + const static int32_t INTERVAL = 60 * 15; + const static int32_t MAX_PERSIST_SIZE = 100; + int32_t persistIsRunning_ = 0; + OHOS::Utils::RWLock cacheLock_; + OHOS::ThreadPool readRecordBufferTaskWorker_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_USED_RECORD_CACHE_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_service.h b/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_service.h new file mode 100644 index 000000000..4fd047428 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_service.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRIVACY_MANAGER_SERVICE_H +#define PRIVACY_MANAGER_SERVICE_H + +#include + +#include "privacy_manager_stub.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "singleton.h" +#include "system_ability.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class PrivacyManagerService final : public SystemAbility, public PrivacyManagerStub { + DECLARE_DELAYED_SINGLETON(PrivacyManagerService); + DECLEAR_SYSTEM_ABILITY(PrivacyManagerService); + +public: + void OnStart() override; + void OnStop() override; + + int32_t AddPermissionUsedRecord( + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount) override; + int32_t StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; + int32_t StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; + int32_t RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) override; + int32_t GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) override; + int32_t GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, const sptr& callback) override; + std::string DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) override; + int32_t RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) override; + int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) override; + bool IsAllowUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; +private: + bool Initialize() const; + + ServiceRunningState state_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_MANAGER_SERVICE_H diff --git a/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_stub.h b/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_stub.h new file mode 100644 index 000000000..a388be35d --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/include/service/privacy_manager_stub.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PRIVACY_MANAGER_STUB_H +#define PRIVACY_MANAGER_STUB_H + +#include "i_privacy_manager.h" + +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PrivacyManagerStub : public IRemoteStub { +public: + PrivacyManagerStub() = default; + virtual ~PrivacyManagerStub() = default; + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + +private: + void AddPermissionUsedRecordInner(MessageParcel& data, MessageParcel& reply); + void StartUsingPermissionInner(MessageParcel& data, MessageParcel& reply); + void StopUsingPermissionInner(MessageParcel& data, MessageParcel& reply); + void RemovePermissionUsedRecordsInner(MessageParcel& data, MessageParcel& reply); + void GetPermissionUsedRecordsInner(MessageParcel& data, MessageParcel& reply); + void GetPermissionUsedRecordsAsyncInner(MessageParcel& data, MessageParcel& reply); + void DumpRecordInfoInner(MessageParcel& data, MessageParcel& reply); + void RegisterPermActiveStatusCallbackInner(MessageParcel& data, MessageParcel& reply); + void UnRegisterPermActiveStatusCallbackInner(MessageParcel& data, MessageParcel& reply); + void IsAllowUsingPermissionInner(MessageParcel& data, MessageParcel& reply); + bool IsAccessTokenCalling() const; + static const int32_t ACCESSTOKEN_UID = 3020; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_MANAGER_STUB_H diff --git a/security_access_token-yl_0822/services/privacymanager/privacy.cfg b/security_access_token-yl_0822/services/privacymanager/privacy.cfg new file mode 100644 index 000000000..30d01427c --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/privacy.cfg @@ -0,0 +1,11 @@ +{ + "services" : [{ + "name" : "privacy_service", + "path" : ["/system/bin/sa_main", "/system/profile/privacy_service.xml"], + "importance" : -20, + "uid" : "access_token", + "gid" : ["access_token"], + "secon" : "u:r:privacy_service:s0" + } + ] +} diff --git a/security_access_token-yl_0822/services/privacymanager/privacy.rc b/security_access_token-yl_0822/services/privacymanager/privacy.rc new file mode 100644 index 000000000..975763754 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/privacy.rc @@ -0,0 +1,22 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +on late-fs + start privacy_service + +service privacy_service /system/bin/sa_main /system/profile/privacy_service.xml + class privacy_service + priority -20 + user access_token + group access_token + seclabel u:r:privacy_service:s0 diff --git a/security_access_token-yl_0822/services/privacymanager/sa_profile/3505.xml b/security_access_token-yl_0822/services/privacymanager/sa_profile/3505.xml new file mode 100644 index 000000000..60b5eae50 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/sa_profile/3505.xml @@ -0,0 +1,24 @@ + + + + privacy_service + + 3505 + libprivacy_manager_service.z.so + true + true + 1 + + diff --git a/security_access_token-yl_0822/services/privacymanager/sa_profile/BUILD.gn b/security_access_token-yl_0822/services/privacymanager/sa_profile/BUILD.gn new file mode 100644 index 000000000..1bf6fc36a --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/sa_profile/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/ohos/sa_profile/sa_profile.gni") + +if (is_standard_system) { + ohos_sa_profile("privacy_sa_profile_standard") { + part_name = "access_token" + + sources = [ "3505.xml" ] + } +} diff --git a/security_access_token-yl_0822/services/privacymanager/src/active/active_status_callback_manager.cpp b/security_access_token-yl_0822/services/privacymanager/src/active/active_status_callback_manager.cpp new file mode 100644 index 000000000..b14bcd6e2 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/active/active_status_callback_manager.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "active_status_callback_manager.h" + +#include +#include +#include + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "ActiveStatusCallbackManager" +}; +static const time_t MAX_TIMEOUT_SEC = 30; +static const time_t MAX_CALLBACK_SIZE = 200; +} + +ActiveStatusCallbackManager& ActiveStatusCallbackManager::GetInstance() +{ + static ActiveStatusCallbackManager instance; + return instance; +} + +ActiveStatusCallbackManager::ActiveStatusCallbackManager() + : callbackDeathRecipient_(sptr( + new (std::nothrow) PermActiveStatusCallbackDeathRecipient())) +{ +} + +ActiveStatusCallbackManager::~ActiveStatusCallbackManager() +{ +} + +int32_t ActiveStatusCallbackManager::AddCallback( + const std::vector& permList, const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "callback %{public}p ", (IRemoteObject *)callback); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "input is nullptr"); + return RET_FAILED; + } + + callback->AddDeathRecipient(callbackDeathRecipient_); + + CallbackData recordInstance; + recordInstance.callbackObject_ = callback; + recordInstance.permList_ = permList; + + std::lock_guard lock(mutex_); + if (callbackDataList_.size() > MAX_CALLBACK_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "list size has reached max value"); + return RET_FAILED; + } + callbackDataList_.emplace_back(recordInstance); + + ACCESSTOKEN_LOG_INFO(LABEL, "recordInstance is added"); + return RET_SUCCESS; +} + +int32_t ActiveStatusCallbackManager::RemoveCallback(const sptr& callback) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "called"); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "callback is nullptr"); + return RET_FAILED; + } + + std::lock_guard lock(mutex_); + + for (auto it = callbackDataList_.begin(); it != callbackDataList_.end(); ++it) { + if (callback == (*it).callbackObject_) { + ACCESSTOKEN_LOG_INFO(LABEL, "find callback"); + if (callbackDeathRecipient_ != nullptr) { + callback->RemoveDeathRecipient(callbackDeathRecipient_); + } + (*it).callbackObject_ = nullptr; + callbackDataList_.erase(it); + break; + } + } + return RET_SUCCESS; +} + +bool ActiveStatusCallbackManager::NeedCalled(const std::vector& permList, const std::string& permName) +{ + if (permList.empty()) { + return true; + } + for (const auto& perm : permList) { + if (perm == permName) { + return true; + } + } + return false; +} + +void ActiveStatusCallbackManager::ExecuteCallbackAsync( + AccessTokenID tokenId, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "entry"); + + auto callbackFunc = [&]() { + ACCESSTOKEN_LOG_INFO(LABEL, "callbackStart"); + std::lock_guard lock(mutex_); + for (auto it = callbackDataList_.begin(); it != callbackDataList_.end(); ++it) { + std::vector permList = (*it).permList_; + if (!NeedCalled(permList, permName)) { + ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}u, permName %{public}s", tokenId, permName.c_str()); + continue; + } + auto callback = iface_cast((*it).callbackObject_); + if (callback != nullptr) { + ActiveChangeResponse resInfo; + resInfo.type = changeType; + resInfo.permissionName = permName; + resInfo.tokenID = tokenId; + resInfo.deviceId = deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "callback excute changeType %{public}d", changeType); + callback->ActiveStatusChangeCallback(resInfo); + } + } + }; + + std::packaged_task callbackTask(callbackFunc); + std::future fut = callbackTask.get_future(); + std::make_unique(std::move(callbackTask))->detach(); + + ACCESSTOKEN_LOG_INFO(LABEL, "Waiting for the callback execution complete..."); + std::future_status status = fut.wait_for(std::chrono::seconds(MAX_TIMEOUT_SEC)); + if (status == std::future_status::timeout) { + ACCESSTOKEN_LOG_WARN(LABEL, "callbackTask callback execution timeout"); + } + ACCESSTOKEN_LOG_INFO(LABEL, "The callback execution is complete"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_callback_death_recipient.cpp b/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_callback_death_recipient.cpp new file mode 100644 index 000000000..1acb1bdec --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_callback_death_recipient.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_active_status_callback_death_recipient.h" + +#include "access_token.h" +#include "active_status_callback_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "PermActiveStatusCallbackDeathRecipient" +}; +} +void PermActiveStatusCallbackDeathRecipient::OnRemoteDied(const wptr &remote) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "enter"); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote object is nullptr"); + return; + } + + sptr object = remote.promote(); + if (object == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "object is nullptr"); + return; + } + ActiveStatusCallbackManager::GetInstance().RemoveCallback(object); + ACCESSTOKEN_LOG_INFO(LABEL, "end"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_change_callback_proxy.cpp b/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_change_callback_proxy.cpp new file mode 100644 index 000000000..5b41136ed --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/active/perm_active_status_change_callback_proxy.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "perm_active_status_change_callback_proxy.h" + +#include "accesstoken_log.h" +#include "perm_active_response_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermActiveStatusChangeCallbackProxy" +}; +} + +PermActiveStatusChangeCallbackProxy::PermActiveStatusChangeCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +PermActiveStatusChangeCallbackProxy::~PermActiveStatusChangeCallbackProxy() +{} + +void PermActiveStatusChangeCallbackProxy::ActiveStatusChangeCallback(ActiveChangeResponse& result) +{ + MessageParcel data; + data.WriteInterfaceToken(IPermActiveStatusCallback::GetDescriptor()); + + ActiveChangeResponseParcel resultParcel; + resultParcel.changeResponse = result; + if (!data.WriteParcelable(&resultParcel)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable"); + return; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return; + } + int32_t requestResult = remote->SendRequest( + static_cast(IPermActiveStatusCallback::PERM_ACTIVE_STATUS_CHANGE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "SendRequest success"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/common/constant.cpp b/security_access_token-yl_0822/services/privacymanager/src/common/constant.cpp new file mode 100644 index 000000000..1a9b74855 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/common/constant.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "constant.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string Constant::COUNT_CMD = "COUNT"; +const std::map Constant::PERMISSION_OPCODE_MAP = { + std::map::value_type("ohos.permission.ANSWER_CALL", Constant::OP_ANSWER_CALL), + std::map::value_type("ohos.permission.READ_CALENDAR", Constant::OP_READ_CALENDAR), + std::map::value_type("ohos.permission.WRITE_CALENDAR", Constant::OP_WRITE_CALENDAR), + std::map::value_type("ohos.permission.SEND_MESSAGES", Constant::OP_SEND_MESSAGES), + std::map::value_type("ohos.permission.WRITE_CALL_LOG", Constant::OP_WRITE_CALL_LOG), + std::map::value_type("ohos.permission.READ_CALL_LOG", Constant::OP_READ_CALL_LOG), + std::map::value_type("ohos.permission.READ_CELL_MESSAGES", Constant::OP_READ_CELL_MESSAGES), + std::map::value_type("ohos.permission.MICROPHONE", Constant::OP_MICROPHONE), + std::map::value_type( + "ohos.permission.RECEIVE_WAP_MESSAGES", Constant::OP_RECEIVE_WAP_MESSAGES), + std::map::value_type("ohos.permission.RECEIVE_SMS", Constant::OP_RECEIVE_SMS), + std::map::value_type("ohos.permission.RECEIVE_MMS", Constant::OP_RECEIVE_MMS), + std::map::value_type("ohos.permission.READ_MESSAGES", Constant::OP_READ_MESSAGES), + std::map::value_type("ohos.permission.READ_CONTACTS", Constant::OP_READ_CONTACTS), + std::map::value_type("ohos.permission.WRITE_CONTACTS", Constant::OP_WRITE_CONTACTS), + std::map::value_type( + "ohos.permission.LOCATION_IN_BACKGROUND", Constant::OP_LOCATION_IN_BACKGROUND), + std::map::value_type("ohos.permission.LOCATION", Constant::OP_LOCATION), + std::map::value_type("ohos.permission.MEDIA_LOCATION", Constant::OP_MEDIA_LOCATION), + std::map::value_type("ohos.permission.CAMERA", Constant::OP_CAMERA), + std::map::value_type("ohos.permission.READ_MEDIA", Constant::OP_READ_MEDIA), + std::map::value_type("ohos.permission.WRITE_MEDIA", Constant::OP_WRITE_MEDIA), + std::map::value_type("ohos.permission.ACTIVITY_MOTION", Constant::OP_ACTIVITY_MOTION), + std::map::value_type("ohos.permission.READ_HEALTH_DATA", Constant::OP_READ_HEALTH_DATA), + std::map::value_type("ohos.permission.MANAGE_VOICEMAIL", Constant::OP_MANAGE_VOICEMAIL), + std::map::value_type( + "ohos.permission.DISTRIBUTED_DATASYNC", Constant::OP_DISTRIBUTED_DATASYNC), +}; + +bool Constant::TransferPermissionToOpcode(const std::string& permissionName, int32_t& opCode) +{ + if (PERMISSION_OPCODE_MAP.count(permissionName) == 0) { + return false; + } + opCode = PERMISSION_OPCODE_MAP.at(permissionName); + return true; +} + +bool Constant::TransferOpcodeToPermission(int32_t opCode, std::string& permissionName) +{ + auto iter = std::find_if(PERMISSION_OPCODE_MAP.begin(), PERMISSION_OPCODE_MAP.end(), + [opCode](const std::map::value_type item) { + return item.second == opCode; + }); + if (iter == PERMISSION_OPCODE_MAP.end()) { + return false; + } + permissionName = iter->first; + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/common/time_util.cpp b/security_access_token-yl_0822/services/privacymanager/src/common/time_util.cpp new file mode 100644 index 000000000..eff098ca9 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/common/time_util.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "time_util.h" +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +int64_t TimeUtil::GetCurrentTimestamp() +{ + const time_t timestamp = time(NULL); + return static_cast(timestamp); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/common/to_string.cpp b/security_access_token-yl_0822/services/privacymanager/src/common/to_string.cpp new file mode 100644 index 000000000..91b893e97 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/common/to_string.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "to_string.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +void ToString::DetailUsedRecordToString( + bool isAccessDetail, const std::vector& detailRecord, std::string& infos) +{ + if (isAccessDetail) { + infos.append(R"( "accessRecords": [)"); + } else { + infos.append(R"( "rejectRecords": [)"); + } + infos.append("\n"); + for (const auto& detail : detailRecord) { + infos.append(" {"); + infos.append("\n"); + infos.append(R"( "status": ")" + std::to_string(detail.status) + R"(")" + ",\n"); + infos.append(R"( "timestamp": ")" + std::to_string(detail.timestamp) + R"(")" + ",\n"); + infos.append(R"( "duration": )" + std::to_string(detail.accessDuration) + ",\n"); + infos.append(" },"); + infos.append("\n"); + } + + infos.append(" ]"); + infos.append("\n"); +} + +void ToString::PermissionUsedRecordToString( + const std::vector& permissionRecords, std::string& infos) +{ + infos.append(R"( "permissionRecords": [)"); + infos.append("\n"); + + for (const auto& perm : permissionRecords) { + infos.append(" {"); + infos.append("\n"); + infos.append(R"( "permissionName": ")" + perm.permissionName + R"(")" + ",\n"); + infos.append(R"( "accessCount": ")" + std::to_string(perm.accessCount) + R"(")" + ",\n"); + infos.append(R"( "rejectCount": )" + std::to_string(perm.rejectCount) + ",\n"); + infos.append(R"( "lastAccessTime": )" + std::to_string(perm.lastAccessTime) + ",\n"); + infos.append(R"( "lastRejectTime": )" + std::to_string(perm.lastRejectTime) + ",\n"); + infos.append(R"( "lastAccessDuration": )" + std::to_string(perm.lastAccessDuration) + ",\n"); + ToString::DetailUsedRecordToString(true, perm.accessRecords, infos); + ToString::DetailUsedRecordToString(false, perm.rejectRecords, infos); + infos.append(" },"); + infos.append("\n"); + } + + infos.append(" ]"); + infos.append("\n"); +} + +void ToString::BundleUsedRecordToString(const BundleUsedRecord& bundleRecord, std::string& infos) +{ + infos.append("{"); + infos.append("\n"); + infos.append(R"( "tokenId": )" + std::to_string(bundleRecord.tokenId) + ",\n"); + infos.append(R"( "isRemote": )" + std::to_string(bundleRecord.isRemote) + ",\n"); + infos.append(R"( "bundleName": )" + bundleRecord.bundleName + ",\n"); + infos.append(R"( "deviceId": )" + bundleRecord.deviceId + ",\n"); + + ToString::PermissionUsedRecordToString(bundleRecord.permissionRecords, infos); + + infos.append("}"); + infos.append("\n"); +} + +void ToString::PermissionUsedResultToString(const PermissionUsedResult& result, std::string& infos) +{ + if (result.bundleRecords.empty()) { + return; + } + infos.append(R"("beginTime": )" + std::to_string(result.beginTimeMillis) + ",\n"); + infos.append(R"("endTime": )" + std::to_string(result.endTimeMillis) + ",\n"); + + for (const auto& res : result.bundleRecords) { + ToString::BundleUsedRecordToString(res, infos); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/database/data_translator.cpp b/security_access_token-yl_0822/services/privacymanager/src/database/data_translator.cpp new file mode 100644 index 000000000..27753200f --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/database/data_translator.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_translator.h" + +#include "constant.h" +#include "field_const.h" +#include "time_util.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +int32_t DataTranslator::TranslationIntoGenericValues(const PermissionUsedRequest& request, + GenericValues& andGenericValues, GenericValues& orGenericValues) +{ + int64_t begin = request.beginTimeMillis; + int64_t end = request.endTimeMillis; + if ((begin < 0) || (end < 0) || (begin > end)) { + return Constant::FAILURE; + } + + if (request.flag != FLAG_PERMISSION_USAGE_SUMMARY && request.flag != FLAG_PERMISSION_USAGE_DETAIL) { + return Constant::FAILURE; + } + + if (begin == 0 && end == 0) { + int64_t beginTime = TimeUtil::GetCurrentTimestamp() - Constant::LATEST_RECORD_TIME; + begin = (beginTime < 0) ? 0 : beginTime; + end = TimeUtil::GetCurrentTimestamp(); + } + + if (begin != 0) { + andGenericValues.Put(FIELD_TIMESTAMP_BEGIN, begin); + } + if (end != 0) { + andGenericValues.Put(FIELD_TIMESTAMP_END, end); + } + + for (const auto& perm : request.permissionList) { + int32_t opCode; + if (Constant::TransferPermissionToOpcode(perm, opCode)) { + orGenericValues.Put(FIELD_OP_CODE, opCode); + } else { + orGenericValues.Put(FIELD_OP_CODE, Constant::OP_INVALID); + } + } + return Constant::SUCCESS; +} + +int32_t DataTranslator::TranslationGenericValuesIntoPermissionUsedRecord(const GenericValues& inGenericValues, + PermissionUsedRecord& permissionRecord) +{ + std::string permission; + int32_t opCode = inGenericValues.GetInt(FIELD_OP_CODE); + if (!Constant::TransferOpcodeToPermission(opCode, permission)) { + return Constant::FAILURE; + } + + int64_t timestamp = inGenericValues.GetInt64(FIELD_TIMESTAMP); + permissionRecord.permissionName = permission; + + if (inGenericValues.GetInt(FIELD_ACCESS_COUNT) != 0) { + permissionRecord.accessCount = inGenericValues.GetInt(FIELD_ACCESS_COUNT); + permissionRecord.lastAccessTime = timestamp; + permissionRecord.lastAccessDuration = inGenericValues.GetInt64(FIELD_ACCESS_DURATION); + } + + if (inGenericValues.GetInt(FIELD_REJECT_COUNT) != 0) { + permissionRecord.rejectCount = inGenericValues.GetInt(FIELD_REJECT_COUNT); + permissionRecord.lastRejectTime = timestamp; + } + + if (inGenericValues.GetInt(FIELD_FLAG) == 0) { + return Constant::SUCCESS; + } + + UsedRecordDetail detail; + detail.status = inGenericValues.GetInt(FIELD_STATUS); + if (permissionRecord.lastAccessTime > 0) { + detail.timestamp = permissionRecord.lastAccessTime; + detail.accessDuration = inGenericValues.GetInt64(FIELD_ACCESS_DURATION); + permissionRecord.accessRecords.emplace_back(detail); + } + if (permissionRecord.lastRejectTime > 0) { + detail.timestamp = permissionRecord.lastRejectTime; + permissionRecord.rejectRecords.emplace_back(detail); + } + return Constant::SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/database/permission_used_record_db.cpp b/security_access_token-yl_0822/services/privacymanager/src/database/permission_used_record_db.cpp new file mode 100644 index 000000000..9c3a78662 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/database/permission_used_record_db.cpp @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_record_db.h" + +#include "accesstoken_log.h" +#include "constant.h" +#include "field_const.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionUsedRecordDb" +}; +} + +PermissionUsedRecordDb& PermissionUsedRecordDb::GetInstance() +{ + static PermissionUsedRecordDb instance; + return instance; +} + +PermissionUsedRecordDb::~PermissionUsedRecordDb() +{ + Close(); +} + +void PermissionUsedRecordDb::OnCreate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Entry"); + CreatePermissionRecordTable(); +} + +void PermissionUsedRecordDb::OnUpdate() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Entry"); +} + +PermissionUsedRecordDb::PermissionUsedRecordDb() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATABASE_VERSION) +{ + SqliteTable permissionRecordTable; + permissionRecordTable.tableName_ = PERMISSION_RECORD_TABLE; + permissionRecordTable.tableColumnNames_ = { + FIELD_TOKEN_ID, + FIELD_OP_CODE, + FIELD_STATUS, + FIELD_TIMESTAMP, + FIELD_ACCESS_DURATION, + FIELD_ACCESS_COUNT, + FIELD_REJECT_COUNT + }; + + dataTypeToSqlTable_ = { + {PERMISSION_RECORD, permissionRecordTable}, + }; + Open(); +} + +int32_t PermissionUsedRecordDb::Add(DataType type, const std::vector& values) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string prepareSql = CreateInsertPrepareSqlCmd(type); + auto statement = Prepare(prepareSql); + BeginTransaction(); + bool isExecuteSuccessfully = true; + for (const auto& value : values) { + std::vector columnNames = value.GetAllKeys(); + for (const auto& columnName : columnNames) { + statement.Bind(columnName, value.Get(columnName)); + } + int32_t ret = statement.Step(); + if (ret != Statement::State::DONE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", SpitError().c_str()); + isExecuteSuccessfully = false; + } + statement.Reset(); + } + if (!isExecuteSuccessfully) { + ACCESSTOKEN_LOG_ERROR(LABEL, "rollback transaction."); + RollbackTransaction(); + return FAILURE; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "commit transaction."); + CommitTransaction(); + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::Remove(DataType type, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector columnNames = conditions.GetAllKeys(); + std::string prepareSql = CreateDeletePrepareSqlCmd(type, columnNames); + auto statement = Prepare(prepareSql); + for (const auto& columnName : columnNames) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int32_t ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int32_t PermissionUsedRecordDb::Modify( + DataType type, const GenericValues& modifyValues, const GenericValues& conditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector modifyColumns = modifyValues.GetAllKeys(); + std::vector conditionColumns = conditions.GetAllKeys(); + std::string prepareSql = CreateUpdatePrepareSqlCmd(type, modifyColumns, conditionColumns); + auto statement = Prepare(prepareSql); + for (const auto& columnName : modifyColumns) { + statement.Bind(columnName, modifyValues.Get(columnName)); + } + for (const auto& columnName : conditionColumns) { + statement.Bind(columnName, conditions.Get(columnName)); + } + int32_t ret = statement.Step(); + return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; +} + +int32_t PermissionUsedRecordDb::FindByConditions(DataType type, const GenericValues& andConditions, + const GenericValues& orConditions, std::vector& results) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector andColumns = andConditions.GetAllKeys(); + std::vector orColumns = orConditions.GetAllKeys(); + std::string prepareSql = CreateSelectByConditionPrepareSqlCmd(type, andColumns, orColumns); + auto statement = Prepare(prepareSql); + + for (const auto& columnName : andColumns) { + statement.Bind(columnName, andConditions.Get(columnName)); + } + for (const auto& columnName : orColumns) { + statement.Bind(columnName, orConditions.Get(columnName)); + } + + while (statement.Step() == Statement::State::ROW) { + int32_t columnCount = statement.GetColumnCount(); + GenericValues value; + for (int32_t i = 0; i < columnCount; i++) { + if (statement.GetColumnName(i) == FIELD_TIMESTAMP || statement.GetColumnName(i) == FIELD_ACCESS_DURATION) { + value.Put(statement.GetColumnName(i), statement.GetValue(i, true)); + } else { + value.Put(statement.GetColumnName(i), statement.GetValue(i, false)); + } + } + results.emplace_back(value); + } + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::GetDistinctValue(DataType type, + const std::string& condition, std::vector& results) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string getDistinctValueSql = CreateGetDistinctValue(type, condition); + auto statement = Prepare(getDistinctValueSql); + while (statement.Step() == Statement::State::ROW) { + int32_t columnCount = statement.GetColumnCount(); + GenericValues value; + for (int32_t i = 0; i < columnCount; i++) { + if (statement.GetColumnName(i) == FIELD_TOKEN_ID) { + value.Put(statement.GetColumnName(i), statement.GetValue(i, false)); + } else if (statement.GetColumnName(i) == FIELD_DEVICE_ID) { + value.Put(statement.GetColumnName(i), statement.GetColumnString(i)); + } + } + results.emplace_back(value); + } + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::Count(DataType type, GenericValues& result) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string countSql = CreateCountPrepareSqlCmd(type); + auto countStatement = Prepare(countSql); + if (countStatement.Step() == Statement::State::ROW) { + int32_t column = 0; + result.Put(Constant::COUNT_CMD, countStatement.GetValue(column, true)); + } + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::DeleteExpireRecords(DataType type, + const GenericValues& andConditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector andColumns = andConditions.GetAllKeys(); + if (!andColumns.empty()) { + std::string deleteExpireSql = CreateDeleteExpireRecordsPrepareSqlCmd(type, andColumns); + auto deleteExpireStatement = Prepare(deleteExpireSql); + for (const auto& columnName : andColumns) { + deleteExpireStatement.Bind(columnName, andConditions.Get(columnName)); + } + int32_t ret = deleteExpireStatement.Step(); + if (ret != Statement::State::DONE) { + return FAILURE; + } + } + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::DeleteExcessiveRecords(DataType type, unsigned excessiveSize) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string deleteExcessiveSql = CreateDeleteExcessiveRecordsPrepareSqlCmd(type, excessiveSize); + auto deleteExcessiveStatement = Prepare(deleteExcessiveSql); + if (deleteExcessiveStatement.Step() != Statement::State::DONE) { + return FAILURE; + } + return SUCCESS; +} + +std::string PermissionUsedRecordDb::CreateInsertPrepareSqlCmd(DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "insert into " + it->second.tableName_ + " values("; + int32_t i = 1; + for (const auto& columnName : it->second.tableColumnNames_) { + sql.append(":" + columnName); + if (i < (int32_t) it->second.tableColumnNames_.size()) { + sql.append(","); + } + i += 1; + } + sql.append(")"); + return sql; +} + +std::string PermissionUsedRecordDb::CreateDeletePrepareSqlCmd( + DataType type, const std::vector& columnNames) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where 1 = 1"; + for (const auto& columnName : columnNames) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + return sql; +} + +std::string PermissionUsedRecordDb::CreateUpdatePrepareSqlCmd(DataType type, + const std::vector& modifyColumns, const std::vector& conditionColumns) const +{ + if (modifyColumns.empty()) { + return std::string(); + } + + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + + std::string sql = "update " + it->second.tableName_ + " set "; + int32_t i = 1; + for (const auto& columnName : modifyColumns) { + sql.append(columnName + "=:" + columnName); + if (i < (int32_t) modifyColumns.size()) { + sql.append(","); + } + i += 1; + } + + if (!conditionColumns.empty()) { + sql.append(" where 1 = 1"); + for (const auto& columnName : conditionColumns) { + sql.append(" and "); + sql.append(columnName + "=:" + columnName); + } + } + return sql; +} + +std::string PermissionUsedRecordDb::CreateSelectByConditionPrepareSqlCmd(DataType type, + const std::vector& andColumns, const std::vector& orColumns) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + + std::string sql = "select * from " + it->second.tableName_ + " where 1 = 1"; + for (const auto& andColName : andColumns) { + if (andColName == FIELD_TIMESTAMP_BEGIN) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " >=:" + andColName); + } else if (andColName == FIELD_TIMESTAMP_END) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " <=:" + andColName); + } else { + sql.append(" and "); + sql.append(andColName + "=:" + andColName); + } + } + if (!orColumns.empty()) { + sql.append(" and ("); + for (const auto& orColName : orColumns) { + if (orColName.find(FIELD_OP_CODE) != std::string::npos) { + sql.append(FIELD_OP_CODE + " =:" + orColName); + sql.append(" or "); + } + } + sql.append("0)"); + } + return sql; +} + +std::string PermissionUsedRecordDb::CreateCountPrepareSqlCmd(DataType type) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "select count(*) from " + it->second.tableName_; + return sql; +} + +std::string PermissionUsedRecordDb::CreateDeleteExpireRecordsPrepareSqlCmd(DataType type, + const std::vector& andColumns) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where "; + sql.append(FIELD_TIMESTAMP + " in (select "); + sql.append(FIELD_TIMESTAMP + " from " + it->second.tableName_ + " where 1 = 1"); + for (const auto& andColName : andColumns) { + if (andColName == FIELD_TIMESTAMP_BEGIN) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " >=:" + andColName); + } else if (andColName == FIELD_TIMESTAMP_END) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " <=:" + andColName); + } else { + sql.append(" and "); + sql.append(andColName + "=:" + andColName); + } + } + sql.append(" )"); + return sql; +} + +std::string PermissionUsedRecordDb::CreateDeleteExcessiveRecordsPrepareSqlCmd(DataType type, + uint32_t excessiveSize) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where "; + sql.append(FIELD_TIMESTAMP + " in (select "); + sql.append(FIELD_TIMESTAMP + " from " + it->second.tableName_ + " order by "); + sql.append(FIELD_TIMESTAMP + " limit "); + sql.append(std::to_string(excessiveSize) + " )"); + return sql; +} + +std::string PermissionUsedRecordDb::CreateGetDistinctValue(DataType type, + const std::string conditionColumns) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "select distinct "; + sql.append(conditionColumns + " from "+ it->second.tableName_); + return sql; +} + +int32_t PermissionUsedRecordDb::CreatePermissionRecordTable() const +{ + auto it = dataTypeToSqlTable_.find(DataType::PERMISSION_RECORD); + if (it == dataTypeToSqlTable_.end()) { + return FAILURE; + } + std::string sql = "create table if not exists "; + sql.append(it->second.tableName_ + " (") + .append(FIELD_TOKEN_ID + " integer not null,") + .append(FIELD_OP_CODE + " integer not null,") + .append(FIELD_STATUS + " integer not null,") + .append(FIELD_TIMESTAMP + " integer not null,") + .append(FIELD_ACCESS_DURATION + " integer not null,") + .append(FIELD_ACCESS_COUNT + " integer not null,") + .append(FIELD_REJECT_COUNT + " integer not null,") + .append("primary key(" + FIELD_TOKEN_ID) + .append("," + FIELD_OP_CODE) + .append("," + FIELD_STATUS) + .append("," + FIELD_TIMESTAMP) + .append("))"); + return ExecuteSql(sql); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_proxy.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_proxy.cpp new file mode 100644 index 000000000..79ddc389d --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_proxy.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "on_permission_used_record_callback_proxy.h" + +#include "accesstoken_log.h" +#include "permission_used_result_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "OnPermissionUsedRecordCallbackProxy" +}; +} + +OnPermissionUsedRecordCallbackProxy::OnPermissionUsedRecordCallbackProxy(const sptr& impl) + : IRemoteProxy(impl) { +} + +OnPermissionUsedRecordCallbackProxy::~OnPermissionUsedRecordCallbackProxy() +{} + +void OnPermissionUsedRecordCallbackProxy::OnQueried(ErrCode code, PermissionUsedResult& result) +{ + MessageParcel data; + data.WriteInterfaceToken(OnPermissionUsedRecordCallback::GetDescriptor()); + if (!data.WriteInt32(code)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable(code)"); + return; + } + + PermissionUsedResultParcel resultParcel; + resultParcel.result = result; + if (!data.WriteParcelable(&resultParcel)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteParcelable(result)"); + return; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return; + } + int32_t requestResult = remote->SendRequest( + static_cast(OnPermissionUsedRecordCallback::ON_QUERIED), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "SendRequest success"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_stub.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_stub.cpp new file mode 100644 index 000000000..d4b821525 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/on_permission_used_record_callback_stub.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "on_permission_used_record_callback_stub.h" + +#include "accesstoken_log.h" +#include "constant.h" +#include "permission_used_result_parcel.h" +#include "constant.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "OnPermissionUsedRecordCallbackStub" +}; +} + +int32_t OnPermissionUsedRecordCallbackStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, code: 0x%{public}x", code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != OnPermissionUsedRecordCallback::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return Constant::FAILURE; + } + + int32_t msgCode = static_cast(code); + if (msgCode == OnPermissionUsedRecordCallback::ON_QUERIED) { + ErrCode errCode = data.ReadInt32(); + PermissionUsedResult result; + if (errCode != NO_ERROR) { + OnQueried(errCode, result); + return Constant::FAILURE; + } + sptr resultSptr = data.ReadParcelable(); + if (resultSptr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "errCode: %{public}d", errCode); + OnQueried(errCode, resultSptr->result); + } else { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return NO_ERROR; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/permission_record.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record.cpp new file mode 100644 index 000000000..643ec0f84 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_record.h" +#include "field_const.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +void PermissionRecord::TranslationIntoGenericValues(const PermissionRecord& record, GenericValues& values) +{ + values.Put(FIELD_TOKEN_ID, (int32_t)record.tokenId); + values.Put(FIELD_OP_CODE, record.opCode); + values.Put(FIELD_STATUS, record.status); + values.Put(FIELD_TIMESTAMP, record.timestamp); + values.Put(FIELD_ACCESS_DURATION, record.accessDuration); + values.Put(FIELD_ACCESS_COUNT, record.accessCount); + values.Put(FIELD_REJECT_COUNT, record.rejectCount); +} + +void PermissionRecord::TranslationIntoPermissionRecord(const GenericValues& values, PermissionRecord& record) +{ + record.tokenId = values.GetInt(FIELD_TOKEN_ID); + record.opCode = values.GetInt(FIELD_OP_CODE); + record.status = values.GetInt(FIELD_STATUS); + record.timestamp = values.GetInt64(FIELD_TIMESTAMP); + record.accessDuration = values.GetInt64(FIELD_ACCESS_DURATION); + record.accessCount = values.GetInt(FIELD_ACCESS_COUNT); + record.rejectCount = values.GetInt(FIELD_REJECT_COUNT); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_manager.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_manager.cpp new file mode 100644 index 000000000..9fa40b3f1 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_manager.cpp @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_record_manager.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "constant.h" +#include "constant_common.h" +#include "data_translator.h" +#include "field_const.h" +#include "permission_record_repository.h" +#include "permission_used_record_cache.h" +#include "active_status_callback_manager.h" +#include "time_util.h" +#include "to_string.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordManager" +}; +static const std::string DEFAULT_DEVICEID = "0"; +} +PermissionRecordManager& PermissionRecordManager::GetInstance() +{ + static PermissionRecordManager instance; + return instance; +} + +PermissionRecordManager::PermissionRecordManager() : hasInited_(false) {} + +PermissionRecordManager::~PermissionRecordManager() +{ + if (!hasInited_) { + return; + } + deleteTaskWorker_.Stop(); + hasInited_ = false; +} + +int32_t PermissionRecordManager::AddRecord(const PermissionRecord& record) +{ + Utils::UniqueWriteGuard lk(this->rwLock_); + return PermissionUsedRecordCache::GetInstance().AddRecordToBuffer(const_cast(record)); +} + +bool PermissionRecordManager::GetPermissionsRecord(AccessTokenID tokenId, const std::string& permissionName, + int32_t successCount, int32_t failCount, PermissionRecord& record) +{ + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId); + return false; + } + int32_t opCode; + if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission(%{public}s)", permissionName.c_str()); + return false; + } + if (successCount == 0 && failCount == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "successCount and failCount are both zero"); + return false; + } + record.tokenId = tokenId; + record.accessCount = successCount; + record.rejectCount = failCount; + record.opCode = opCode; + record.status = 0; + record.timestamp = TimeUtil::GetCurrentTimestamp(); + record.accessDuration = 0; + return true; +} + +int32_t PermissionRecordManager::AddPermissionUsedRecord(AccessTokenID tokenId, const std::string& permissionName, + int32_t successCount, int32_t failCount) +{ + ExecuteDeletePermissionRecordTask(); + + PermissionRecord record; + if (!GetPermissionsRecord(tokenId, permissionName, successCount, failCount, record)) { + return Constant::FAILURE; + } + + return AddRecord(record); +} + +void PermissionRecordManager::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) +{ + if (tokenId == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId is 0"); + return; + } + + // only support remove by tokenId(local) + std::string device = GetDeviceId(tokenId); + if (device.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId = %{public}d", tokenId); + return; + } + + if (!deviceID.empty() && device != deviceID) { + ACCESSTOKEN_LOG_ERROR(LABEL, "deviceID mismatch"); + return; + } + + Utils::UniqueWriteGuard lk(this->rwLock_); + GenericValues record; + record.Put(FIELD_TOKEN_ID, (int32_t)tokenId); + PermissionUsedRecordCache::GetInstance().RemoveRecords(record); // remove from cache and database +} + +int32_t PermissionRecordManager::GetPermissionUsedRecords( + const PermissionUsedRequest& request, PermissionUsedResult& result) +{ + ExecuteDeletePermissionRecordTask(); + + if (!request.isRemote && !GetRecordsFromLocalDB(request, result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to GetRecordsFromLocalDB"); + return Constant::FAILURE; + } + return Constant::SUCCESS; +} + +int32_t PermissionRecordManager::GetPermissionUsedRecordsAsync( + const PermissionUsedRequest& request, const sptr& callback) +{ + auto task = [request, callback]() { + ACCESSTOKEN_LOG_INFO(LABEL, "GetPermissionUsedRecordsAsync task called"); + PermissionUsedResult result; + int32_t ret = PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request, result); + callback->OnQueried(ret, result); + }; + std::thread recordThread(task); + recordThread.detach(); + return Constant::SUCCESS; +} + +bool PermissionRecordManager::GetLocalRecordTokenIdList(std::set& tokenIdList) +{ + std::vector results; + { + Utils::UniqueWriteGuard lk(this->rwLock_); + // find tokenId from cache + PermissionUsedRecordCache::GetInstance().FindTokenIdList(tokenIdList); + // find tokenId from database + PermissionRecordRepository::GetInstance().GetAllRecordValuesByKey(FIELD_TOKEN_ID, results); + } + for (const auto& res : results) { + tokenIdList.emplace(res.GetInt(FIELD_TOKEN_ID)); + } + return true; +} + +bool PermissionRecordManager::GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result) +{ + GenericValues andConditionValues; + GenericValues orConditionValues; + if (DataTranslator::TranslationIntoGenericValues(request, andConditionValues, orConditionValues) + != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "query time or flag is invalid"); + return false; + } + + std::set tokenIdList; + if (request.tokenId == 0) { + GetLocalRecordTokenIdList(tokenIdList); + } else { + tokenIdList.emplace(request.tokenId); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetLocalRecordTokenIdList.size = %{public}zu", tokenIdList.size()); + Utils::UniqueWriteGuard lk(this->rwLock_); + for (const auto& tokenId : tokenIdList) { + andConditionValues.Put(FIELD_TOKEN_ID, (int32_t)tokenId); + std::vector findRecordsValues; + PermissionUsedRecordCache::GetInstance().GetRecords(request.permissionList, + andConditionValues, orConditionValues, findRecordsValues); // find records from cache and database + andConditionValues.Remove(FIELD_TOKEN_ID); + BundleUsedRecord bundleRecord; + CreateBundleUsedRecord(tokenId, bundleRecord); + if (!findRecordsValues.empty()) { + if (!GetRecords(request.flag, findRecordsValues, bundleRecord, result)) { + return false; + } + } + + if (!bundleRecord.permissionRecords.empty()) { + result.bundleRecords.emplace_back(bundleRecord); + } + } + return true; +} + +bool PermissionRecordManager::CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord) +{ + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetHapTokenInfo failed"); + return false; + } + bundleRecord.tokenId = tokenId; + bundleRecord.isRemote = false; + bundleRecord.deviceId = ConstantCommon::GetLocalDeviceId(); + bundleRecord.bundleName = tokenInfo.bundleName; + return true; +} + +bool PermissionRecordManager::GetRecords( + int32_t flag, std::vector recordValues, BundleUsedRecord& bundleRecord, PermissionUsedResult& result) +{ + std::vector permissionRecords; + for (auto it = recordValues.rbegin(); it != recordValues.rend(); ++it) { + GenericValues record = *it; + PermissionUsedRecord tmpPermissionRecord; + int64_t timestamp = record.GetInt64(FIELD_TIMESTAMP); + result.beginTimeMillis = ((result.beginTimeMillis == 0) || (timestamp < result.beginTimeMillis)) ? + timestamp : result.beginTimeMillis; + result.endTimeMillis = (timestamp > result.endTimeMillis) ? timestamp : result.endTimeMillis; + + record.Put(FIELD_FLAG, flag); + if (DataTranslator::TranslationGenericValuesIntoPermissionUsedRecord(record, tmpPermissionRecord) + != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to transform opcode(%{public}d) into permission", + record.GetInt(FIELD_OP_CODE)); + continue; + } + + auto iter = std::find_if(permissionRecords.begin(), permissionRecords.end(), + [tmpPermissionRecord](const PermissionUsedRecord& rec) { + return tmpPermissionRecord.permissionName == rec.permissionName; + }); + if (iter != permissionRecords.end()) { + UpdateRecords(flag, tmpPermissionRecord, *iter); + } else { + permissionRecords.emplace_back(tmpPermissionRecord); + } + } + bundleRecord.permissionRecords = permissionRecords; + return true; +} + +void PermissionRecordManager::UpdateRecords( + int32_t flag, const PermissionUsedRecord& inBundleRecord, PermissionUsedRecord& outBundleRecord) +{ + outBundleRecord.accessCount += inBundleRecord.accessCount; + outBundleRecord.rejectCount += inBundleRecord.rejectCount; + if (inBundleRecord.lastAccessTime > outBundleRecord.lastAccessTime) { + outBundleRecord.lastAccessTime = inBundleRecord.lastAccessTime; + outBundleRecord.lastAccessDuration = inBundleRecord.lastAccessDuration; + } + outBundleRecord.lastRejectTime = (inBundleRecord.lastRejectTime > outBundleRecord.lastRejectTime) ? + inBundleRecord.lastRejectTime : outBundleRecord.lastRejectTime; + + if (flag == 0) { + return; + } + if (inBundleRecord.lastAccessTime > 0 && outBundleRecord.accessRecords.size() < Constant::MAX_DETAIL_RECORD) { + outBundleRecord.accessRecords.emplace_back(inBundleRecord.accessRecords[0]); + } + if (inBundleRecord.lastRejectTime > 0 && outBundleRecord.rejectRecords.size() < Constant::MAX_DETAIL_RECORD) { + outBundleRecord.rejectRecords.emplace_back(inBundleRecord.rejectRecords[0]); + } +} + +void PermissionRecordManager::ExecuteDeletePermissionRecordTask() +{ + if (deleteTaskWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "Already has delete task!"); + return; + } + + auto deleteRecordsTask = [this]() { + ACCESSTOKEN_LOG_DEBUG(LABEL, "DeletePermissionRecord task called"); + DeletePermissionRecord(Constant::RECORD_DELETE_TIME); + }; + deleteTaskWorker_.AddTask(deleteRecordsTask); +} + +int32_t PermissionRecordManager::DeletePermissionRecord(int32_t days) +{ + Utils::UniqueWriteGuard lk(this->rwLock_); + GenericValues countValue; + if (!PermissionRecordRepository::GetInstance().CountRecordValues(countValue)) { + return Constant::FAILURE; + } + int64_t total = countValue.GetInt64(Constant::COUNT_CMD); + if (total > Constant::MAX_TOTAL_RECORD) { + uint32_t excessiveSize = total - Constant::MAX_TOTAL_RECORD; + if (!PermissionRecordRepository::GetInstance().DeleteExcessiveSizeRecordValues(excessiveSize)) { + return Constant::FAILURE; + } + } + GenericValues andConditionValues; + int64_t deleteTimestamp = TimeUtil::GetCurrentTimestamp() - days; + andConditionValues.Put(FIELD_TIMESTAMP_END, deleteTimestamp); + if (!PermissionRecordRepository::GetInstance().DeleteExpireRecordsValues(andConditionValues)) { + return Constant::FAILURE; + } + return Constant::SUCCESS; +} + +std::string PermissionRecordManager::DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) +{ + PermissionUsedRequest request; + request.tokenId = tokenId; + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + if (!permissionName.empty()) { + request.permissionList.emplace_back(permissionName); + } + + PermissionUsedResult result; + if (!GetRecordsFromLocalDB(request, result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to GetRecordsFromLocalDB"); + return ""; + } + + if (result.bundleRecords.empty()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "no record"); + return ""; + } + std::string dumpInfo; + ToString::PermissionUsedResultToString(result, dumpInfo); + return dumpInfo; +} + +int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync( + tokenId, permissionName, ConstantCommon::GetLocalDeviceId(), PERM_ACTIVE_IN_FOREGROUND); + return Constant::SUCCESS; +} + +int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync( + tokenId, permissionName, ConstantCommon::GetLocalDeviceId(), PERM_INACTIVE); + return Constant::SUCCESS; +} + +int32_t PermissionRecordManager::RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) +{ + return ActiveStatusCallbackManager::GetInstance().AddCallback(permList, callback); +} + +int32_t PermissionRecordManager::UnRegisterPermActiveStatusCallback(const sptr& callback) +{ + return ActiveStatusCallbackManager::GetInstance().RemoveCallback(callback); +} + +std::string PermissionRecordManager::GetDeviceId(AccessTokenID tokenId) +{ + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) { + return ""; + } + if (tokenInfo.deviceID == DEFAULT_DEVICEID) { // local + return ConstantCommon::GetLocalDeviceId(); + } + return tokenInfo.deviceID; +} + +bool PermissionRecordManager::IsAllowUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + PermissionUsedRequest request; + request.tokenId = tokenId; + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + if (!permissionName.empty()) { + request.permissionList.emplace_back(permissionName); + } + + PermissionUsedResult result; + if (!GetRecordsFromLocalDB(request, result)) { + // ACCESSTOKEN_LOG_ERROR(LABEL, "failed to GetRecordsFromLocalDB"); + return false; + } + + if (result.bundleRecords.empty()) { + // ACCESSTOKEN_LOG_DEBUG(LABEL, "no record"); + return false; + } + bool allowperInfo = false; + // ToString::PermissionUsedResultToString(result, allowperInfo); + return allowperInfo; +} + +void PermissionRecordManager::Init() +{ + if (hasInited_) { + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "init"); + deleteTaskWorker_.Start(1); + hasInited_ = true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_repository.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_repository.cpp new file mode 100644 index 000000000..d9ff4fd42 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/permission_record_repository.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_record_repository.h" + +#include "accesstoken_log.h" +#include "permission_used_record_db.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordRepository" +}; +} + +PermissionRecordRepository& PermissionRecordRepository::GetInstance() +{ + static PermissionRecordRepository instance; + return instance; +} + +PermissionRecordRepository::PermissionRecordRepository() +{ +} + +PermissionRecordRepository::~PermissionRecordRepository() +{ +} + +bool PermissionRecordRepository::AddRecordValues(const std::vector& recordValues) +{ + if (PermissionUsedRecordDb::GetInstance().Add(PermissionUsedRecordDb::PERMISSION_RECORD, recordValues) + != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD table add fail"); + return false; + } + return true; +} + +bool PermissionRecordRepository::FindRecordValues(const GenericValues& andConditionValues, + const GenericValues& orConditionValues, std::vector& recordValues) +{ + if (PermissionUsedRecordDb::GetInstance().FindByConditions(PermissionUsedRecordDb::PERMISSION_RECORD, + andConditionValues, orConditionValues, recordValues) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD table find fail"); + return false; + } + return true; +} + +bool PermissionRecordRepository::RemoveRecordValues(const GenericValues& conditionValues) +{ + if (PermissionUsedRecordDb::GetInstance().Remove(PermissionUsedRecordDb::PERMISSION_RECORD, conditionValues) + != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD table add fail"); + return false; + } + return true; +} + +bool PermissionRecordRepository::GetAllRecordValuesByKey( + const std::string& condition, std::vector& resultValues) +{ + if (PermissionUsedRecordDb::GetInstance().GetDistinctValue(PermissionUsedRecordDb::PERMISSION_RECORD, + condition, resultValues) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD table add fail"); + return false; + } + return true; +} + +int32_t PermissionRecordRepository::CountRecordValues(GenericValues& resultValues) +{ + if (PermissionUsedRecordDb::GetInstance().Count(PermissionUsedRecordDb::PERMISSION_RECORD, resultValues) + != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot count PERMISSION_RECORD"); + return false; + } + return true; +} + +bool PermissionRecordRepository::DeleteExpireRecordsValues(const GenericValues& andConditions) +{ + if (PermissionUsedRecordDb::GetInstance().DeleteExpireRecords(PermissionUsedRecordDb::PERMISSION_RECORD, + andConditions) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD delete fail"); + return false; + } + return true; +} + +bool PermissionRecordRepository::DeleteExcessiveSizeRecordValues(uint32_t excessiveSize) +{ + if (PermissionUsedRecordDb::GetInstance().DeleteExcessiveRecords(PermissionUsedRecordDb::PERMISSION_RECORD, + excessiveSize) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD delete fail"); + return false; + } + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/record/permission_used_record_cache.cpp b/security_access_token-yl_0822/services/privacymanager/src/record/permission_used_record_cache.cpp new file mode 100644 index 000000000..8df9c8e01 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/record/permission_used_record_cache.cpp @@ -0,0 +1,425 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_record_cache.h" +#include "accesstoken_log.h" +#include "constant.h" +#include "field_const.h" +#include "generic_values.h" +#include "permission_record.h" +#include "permission_record_manager.h" +#include "permission_record_node.h" +#include "permission_record_repository.h" +#include "permission_used_record_db.h" +#include "time_util.h" +#include "to_string.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionUsedRecordCache" +}; +} + +PermissionUsedRecordCache& PermissionUsedRecordCache::GetInstance() +{ + static PermissionUsedRecordCache instance; + return instance; +} + +int32_t PermissionUsedRecordCache::AddRecordToBuffer(PermissionRecord& record) +{ + if (nextPersistTimestamp_ == 0) { + nextPersistTimestamp_ = record.timestamp + INTERVAL; + } + std::shared_ptr curFindMergePos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindMergePos = curRecordBufferPos_; + persistPendingBufferHead = recordBufferHead_; + int32_t remainCount = 0; + while (curFindMergePos != recordBufferHead_) { + auto pre = curFindMergePos->pre.lock(); + if ((record.timestamp - curFindMergePos->record.timestamp) >= INTERVAL) { + persistPendingBufferEnd = curFindMergePos; + break; + } else if (curFindMergePos->record.tokenId == record.tokenId && + record.opCode == curFindMergePos->record.opCode && + (record.timestamp - curFindMergePos->record.timestamp) <= Constant::PRECISE) { + MergeRecord(record, curFindMergePos); + } else { + remainCount++; + } + curFindMergePos = pre; + } + AddRecordNode(record); // refresh curRecordBUfferPos and readableSize + remainCount++; + if (persistPendingBufferEnd != nullptr) { + readableSize_ = remainCount; + std::shared_ptr tmpRecordBufferHead = + std::make_shared(); + tmpRecordBufferHead->next = persistPendingBufferEnd->next; + persistPendingBufferEnd->next.reset(); + recordBufferHead_ = tmpRecordBufferHead; + if (persistPendingBufferEnd == curRecordBufferPos_) { // persistPendingBufferEnd == curRecordBufferPos + curRecordBufferPos_ = recordBufferHead_; + } else { // remainCount !=0 ==> recordBufferHead->next != nullptr + recordBufferHead_->next->pre = recordBufferHead_; + } + } + } + if (persistPendingBufferEnd != nullptr) { + AddToPersistQueue(persistPendingBufferHead); + } + return Constant::SUCCESS; +} + +void PermissionUsedRecordCache::MergeRecord(PermissionRecord& record, + std::shared_ptr curFindMergePos) +{ + record.accessDuration += curFindMergePos->record.accessDuration; + record.accessCount += curFindMergePos->record.accessCount; + record.rejectCount += curFindMergePos->record.rejectCount; + if (curRecordBufferPos_ == curFindMergePos) { + curRecordBufferPos_ = curRecordBufferPos_->pre.lock(); + } + DeleteRecordNode(curFindMergePos); // delete old same node + readableSize_--; +} + +void PermissionUsedRecordCache::AddToPersistQueue( + const std::shared_ptr persistPendingBufferHead) +{ + bool startPersist = false; + { + Utils::UniqueWriteGuard lock2(this->cacheLock_); + persistPendingBufferQueue_.emplace_back(persistPendingBufferHead); + if ((TimeUtil::GetCurrentTimestamp() >= nextPersistTimestamp_ || + readableSize_ >= MAX_PERSIST_SIZE) && persistIsRunning_ == 0) { + startPersist = true; + } + } + if (startPersist) { + ExecuteReadRecordBufferTask(); + } +} + +void PermissionUsedRecordCache::ExecuteReadRecordBufferTask() +{ + if (readRecordBufferTaskWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "Already has read record buffer task!"); + return; + } + auto readRecordBufferTask = [this]() { + ACCESSTOKEN_LOG_INFO(LABEL, "ReadRecordBuffer task called"); + PersistPendingRecords(); + }; + readRecordBufferTaskWorker_.AddTask(readRecordBufferTask); +} + +int32_t PermissionUsedRecordCache::PersistPendingRecords() +{ + std::shared_ptr persistPendingBufferHead; + bool isEmpty; + std::vector insertValues; + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + isEmpty = persistPendingBufferQueue_.empty(); + persistIsRunning_ = 1; + nextPersistTimestamp_ = 0; + } + while (!isEmpty) { + { + Utils::UniqueWriteGuard lock2(this->cacheLock_); + persistPendingBufferHead = persistPendingBufferQueue_[0]; + persistPendingBufferQueue_.erase(persistPendingBufferQueue_.begin()); + } + std::shared_ptr curPendingRecordNode = + persistPendingBufferHead->next; + while (curPendingRecordNode != nullptr) { + auto next = curPendingRecordNode->next; + GenericValues tmpRecordValues; + PermissionRecord tmpRecord = curPendingRecordNode->record; + PermissionRecord::TranslationIntoGenericValues(tmpRecord, tmpRecordValues); + insertValues.emplace_back(tmpRecordValues); + DeleteRecordNode(curPendingRecordNode); + curPendingRecordNode = next; + } + if (!insertValues.empty() && !PermissionRecordRepository::GetInstance().AddRecordValues(insertValues)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to persist pending records"); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "Persist pending records successful"); + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + isEmpty = persistPendingBufferQueue_.empty(); + } + } + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + if (isEmpty) { // free persistPendingBufferQueue + std::vector> tmpPersistPendingBufferQueue; + std::swap(tmpPersistPendingBufferQueue, persistPendingBufferQueue_); + } + persistIsRunning_ = 0; + } + return true; +} + +int32_t PermissionUsedRecordCache::RemoveRecords(const GenericValues& record) +{ + AccessTokenID tokenId = record.GetInt(FIELD_TOKEN_ID); + std::shared_ptr curFindDeletePos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + int32_t countPersistPendingNode = 0; + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindDeletePos = recordBufferHead_->next; + persistPendingBufferHead = recordBufferHead_; + while (curFindDeletePos != nullptr) { + auto next = curFindDeletePos->next; + if (curFindDeletePos->record.tokenId == tokenId) { + if (curRecordBufferPos_ == curFindDeletePos) { + curRecordBufferPos_ = curFindDeletePos->pre.lock(); + } + DeleteRecordNode(curFindDeletePos); + readableSize_--; + } else if (TimeUtil::GetCurrentTimestamp() - + curFindDeletePos->record.timestamp >= INTERVAL) { + persistPendingBufferEnd = curFindDeletePos; + countPersistPendingNode++; + } + curFindDeletePos = next; + } + if (countPersistPendingNode != 0) { // refresh recordBufferHead + readableSize_ -= countPersistPendingNode; + std::shared_ptr tmpRecordBufferHead = + std::make_shared(); + tmpRecordBufferHead->next = persistPendingBufferEnd->next; + persistPendingBufferEnd->next.reset(); + recordBufferHead_ = tmpRecordBufferHead; + recordBufferHead_->pre.reset(); + if (persistPendingBufferEnd == curRecordBufferPos_) { + curRecordBufferPos_ = recordBufferHead_; + } else { // remainCount !=0 ==> recordBufferHead->next != nullptr + recordBufferHead_->next->pre = recordBufferHead_; + } + } + } + RemoveRecordsFromPersistPendingBufferQueue(record, persistPendingBufferHead, persistPendingBufferEnd); + return Constant::SUCCESS; +} + +void PermissionUsedRecordCache::RemoveRecordsFromPersistPendingBufferQueue(const GenericValues& record, + std::shared_ptr persistPendingBufferHead, + std::shared_ptr persistPendingBufferEnd) +{ + AccessTokenID tokenId = record.GetInt(FIELD_TOKEN_ID); + { + std::shared_ptr curFindDeletePos; + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto persistHead : persistPendingBufferQueue_) { + curFindDeletePos = persistHead->next; + while (curFindDeletePos != nullptr) { + auto next = curFindDeletePos->next; + if (curFindDeletePos->record.tokenId == tokenId) { + DeleteRecordNode(curFindDeletePos); + } + curFindDeletePos = next; + } + } + } + PermissionRecordRepository::GetInstance().RemoveRecordValues(record); // remove from database + } + if (persistPendingBufferEnd != nullptr) { // add to queue + AddToPersistQueue(persistPendingBufferHead); + } +} + +void PermissionUsedRecordCache::GetRecords(const std::vector& permissionList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues) +{ + std::set opCodeList; + std::shared_ptr curFindPos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + int32_t countPersistPendingNode = 0; + AccessTokenID tokenId = andConditionValues.GetInt(FIELD_TOKEN_ID); + TransferToOpcode(opCodeList, permissionList); + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindPos = recordBufferHead_->next; + persistPendingBufferHead = recordBufferHead_; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + if (RecordCompare(tokenId, opCodeList, andConditionValues, curFindPos->record)) { + GenericValues recordValues; + PermissionRecord::TranslationIntoGenericValues(curFindPos->record, recordValues); + findRecordsValues.emplace_back(recordValues); + } + if (TimeUtil::GetCurrentTimestamp() - curFindPos->record.timestamp >= INTERVAL) { + persistPendingBufferEnd = curFindPos; + countPersistPendingNode++; + } + curFindPos = next; + } + if (countPersistPendingNode != 0) { // refresh recordBufferHead + readableSize_ -= countPersistPendingNode; + std::shared_ptr tmpRecordBufferHead = + std::make_shared(); + tmpRecordBufferHead->next = persistPendingBufferEnd->next; + persistPendingBufferEnd->next.reset(); + recordBufferHead_ = tmpRecordBufferHead; + if (persistPendingBufferEnd == curRecordBufferPos_) { + curRecordBufferPos_ = recordBufferHead_; + } else { // remainCount !=0 ==> recordBufferHead->next != nullptr + recordBufferHead_->next->pre = recordBufferHead_; + } + } + } + GetRecordsFromPersistPendingBufferQueue(permissionList, andConditionValues, + orConditionValues, findRecordsValues, opCodeList); + if (countPersistPendingNode != 0) { + AddToPersistQueue(persistPendingBufferHead); + } +} + +void PermissionUsedRecordCache::GetRecordsFromPersistPendingBufferQueue( + const std::vector& permissionList, const GenericValues& andConditionValues, + const GenericValues& orConditionValues, std::vector& findRecordsValues, + const std::set& opCodeList) +{ + AccessTokenID tokenId = andConditionValues.GetInt(FIELD_TOKEN_ID); + std::shared_ptr curFindPos; + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto persistHead : persistPendingBufferQueue_) { + curFindPos = persistHead->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + if (RecordCompare(tokenId, opCodeList, andConditionValues, curFindPos->record)) { + GenericValues recordValues; + PermissionRecord::TranslationIntoGenericValues(curFindPos->record, recordValues); + findRecordsValues.emplace_back(recordValues); + } + curFindPos = next; + } + } + } + if (tokenId != INVALID_TOKENID && !PermissionRecordRepository::GetInstance().FindRecordValues( + andConditionValues, orConditionValues, findRecordsValues)) { // find records from database + ACCESSTOKEN_LOG_ERROR(LABEL, "find records from database failed"); + } +} + +void PermissionUsedRecordCache::TransferToOpcode(std::set& opCodeList, + const std::vector& permissionList) +{ + for (const auto& permission : permissionList) { + int32_t opCode = Constant::OP_INVALID; + Constant::TransferPermissionToOpcode(permission, opCode); + opCodeList.insert(opCode); + } +} + +bool PermissionUsedRecordCache::RecordCompare(const AccessTokenID tokenId, const std::set& opCodeList, + const GenericValues& andConditionValues, const PermissionRecord& record) +{ + // compare tokenId + if (record.tokenId != (int32_t)tokenId) { + return false; + } + // compare opCode + if (!opCodeList.empty() && opCodeList.find(record.opCode) == opCodeList.end()) { + return false; + } + // compare timestamp + std::vector andColumns = andConditionValues.GetAllKeys(); + if (!andColumns.empty()) { + for (auto andColumn : andColumns) { + if (andColumn == FIELD_TIMESTAMP_BEGIN && + record.timestamp < andConditionValues.GetInt64(andColumn)) { + return false; + } else if (andColumn == FIELD_TIMESTAMP_END && + record.timestamp > andConditionValues.GetInt64(andColumn)) { + return false; + } else if (andColumn == FIELD_TIMESTAMP && + record.timestamp != andConditionValues.GetInt64(andColumn)) { + return false; + } + } + } + return true; +} + +void PermissionUsedRecordCache::FindTokenIdList(std::set& tokenIdList) +{ + std::shared_ptr curFindPos; + { + // find tokenIdList from recordBuffer + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindPos = recordBufferHead_->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + tokenIdList.emplace((AccessTokenID)curFindPos->record.tokenId); + curFindPos = next; + } + } + { + // find tokenIdList from BufferQueue + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto persistHead : persistPendingBufferQueue_) { + curFindPos = persistHead->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + tokenIdList.emplace((AccessTokenID)curFindPos->record.tokenId); + curFindPos = next; + } + } + } + } +} + +void PermissionUsedRecordCache::AddRecordNode(const PermissionRecord& record) +{ + std::shared_ptr tmpRecordNode = std::make_shared(); + tmpRecordNode->record = record; + tmpRecordNode->pre = curRecordBufferPos_; + curRecordBufferPos_->next = tmpRecordNode; + curRecordBufferPos_ = curRecordBufferPos_->next; + readableSize_++; +} + +void PermissionUsedRecordCache::DeleteRecordNode(std::shared_ptr deleteRecordNode) +{ + std::shared_ptr pre = deleteRecordNode->pre.lock(); + if (deleteRecordNode->next == nullptr) { // End of the linked list + pre->next = nullptr; + } else { + std::shared_ptr next = deleteRecordNode->next; + pre->next = next; + next->pre = pre; + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_service.cpp b/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_service.cpp new file mode 100644 index 000000000..638d1fec0 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_service.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_manager_service.h" + +#include "accesstoken_log.h" +#include "constant_common.h" +#include "constant.h" +#include "ipc_skeleton.h" +#include "permission_record_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerService" +}; +} + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +PrivacyManagerService::PrivacyManagerService() + : SystemAbility(SA_ID_PRIVACY_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService()"); +} + +PrivacyManagerService::~PrivacyManagerService() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "~PrivacyManagerService()"); +} + +void PrivacyManagerService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService has already started!"); + return; + } + if (!Initialize()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, PrivacyManagerService start successfully!"); +} + +void PrivacyManagerService::OnStop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "stop service"); + state_ = ServiceRunningState::STATE_NOT_START; +} + +int32_t PrivacyManagerService::AddPermissionUsedRecord( + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount) +{ + return PermissionRecordManager::GetInstance().AddPermissionUsedRecord( + tokenId, permissionName, successCount, failCount); +} + +int32_t PrivacyManagerService::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + return PermissionRecordManager::GetInstance().StartUsingPermission(tokenId, permissionName); +} + +int32_t PrivacyManagerService::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + return PermissionRecordManager::GetInstance().StopUsingPermission(tokenId, permissionName); +} + +int32_t PrivacyManagerService::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) +{ + PermissionRecordManager::GetInstance().RemovePermissionUsedRecords(tokenId, deviceID); + return Constant::SUCCESS; +} + +int32_t PrivacyManagerService::GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) +{ + PermissionUsedResult permissionRecord; + int32_t ret = PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request.request, permissionRecord); + result.result = permissionRecord; + return ret; +} + +int32_t PrivacyManagerService::GetPermissionUsedRecords( + const PermissionUsedRequestParcel& request, const sptr& callback) +{ + return PermissionRecordManager::GetInstance().GetPermissionUsedRecordsAsync(request.request, callback); +} + +std::string PrivacyManagerService::DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) +{ + return PermissionRecordManager::GetInstance().DumpRecordInfo(tokenId, permissionName); +} + +int32_t PrivacyManagerService::RegisterPermActiveStatusCallback( + std::vector& permList, const sptr& callback) +{ + return PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback(permList, callback); +} + +int32_t PrivacyManagerService::UnRegisterPermActiveStatusCallback(const sptr& callback) +{ + return PermissionRecordManager::GetInstance().UnRegisterPermActiveStatusCallback(callback); +} + +bool PrivacyManagerService::IsAllowUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + return PermissionRecordManager::GetInstance().IsAllowUsingPermission(tokenId, permissionName); +} + +bool PrivacyManagerService::Initialize() const +{ + PermissionRecordManager::GetInstance().Init(); + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_stub.cpp b/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_stub.cpp new file mode 100644 index 000000000..79205fe41 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/src/service/privacy_manager_stub.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_manager_stub.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" + +#include "ipc_skeleton.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PrivacyManagerStub" +}; +static const uint32_t PERM_LIST_SIZE_MAX = 1024; +} + +int32_t PrivacyManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != IPrivacyManager::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return -1; + } + switch (code) { + case static_cast(IPrivacyManager::InterfaceCode::ADD_PERMISSION_USED_RECORD): + AddPermissionUsedRecordInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::START_USING_PERMISSION): + StartUsingPermissionInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::STOP_USING_PERMISSION): + StopUsingPermissionInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::DELETE_PERMISSION_USED_RECORDS): + RemovePermissionUsedRecordsInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::GET_PERMISSION_USED_RECORDS): + GetPermissionUsedRecordsInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::GET_PERMISSION_USED_RECORDS_ASYNC): + GetPermissionUsedRecordsAsyncInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::DUMP_RECORD_INFO): + DumpRecordInfoInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::REGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK): + RegisterPermActiveStatusCallbackInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::UNREGISTER_PERM_ACTIVE_STATUS_CHANGE_CALLBACK): + UnRegisterPermActiveStatusCallbackInner(data, reply); + break; + case static_cast(IPrivacyManager::InterfaceCode::IS_ALLOW_USING_PERMISSION): + IsAllowUsingPermissionInner(data, reply); + break; + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return NO_ERROR; +} + +void PrivacyManagerStub::AddPermissionUsedRecordInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); + if (AccessTokenKit::VerifyAccessToken( + callingTokenID, "ohos.permission.PERMISSION_USED_STATS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenId = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int32_t successCount = data.ReadInt32(); + int32_t failCount = data.ReadInt32(); + int32_t result = this->AddPermissionUsedRecord(tokenId, permissionName, successCount, failCount); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::StartUsingPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenId = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int32_t result = this->StartUsingPermission(tokenId, permissionName); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::StopUsingPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenId = data.ReadUint32(); + std::string permissionName = data.ReadString(); + int32_t result = this->StopUsingPermission(tokenId, permissionName); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::RemovePermissionUsedRecordsInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); + if (!IsAccessTokenCalling() && AccessTokenKit::VerifyAccessToken( + callingTokenID, "ohos.permission.PERMISSION_USED_STATS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenId = data.ReadUint32(); + std::string deviceID = data.ReadString(); + int32_t result = this->RemovePermissionUsedRecords(tokenId, deviceID); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::GetPermissionUsedRecordsInner(MessageParcel& data, MessageParcel& reply) +{ + PermissionUsedResultParcel responseParcel; + uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID(); + if (AccessTokenKit::VerifyAccessToken( + callingTokenID, "ohos.permission.PERMISSION_USED_STATS") == PERMISSION_DENIED) { + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); + reply.WriteParcelable(&responseParcel); + reply.WriteInt32(RET_FAILED); + return; + } + sptr requestParcel = data.ReadParcelable(); + if (requestParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable faild"); + reply.WriteParcelable(&responseParcel); + reply.WriteInt32(RET_FAILED); + return; + } + int32_t result = this->GetPermissionUsedRecords(*requestParcel, responseParcel); + reply.WriteParcelable(&responseParcel); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::GetPermissionUsedRecordsAsyncInner(MessageParcel& data, MessageParcel& reply) +{ + sptr requestParcel = data.ReadParcelable(); + if (requestParcel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable faild"); + reply.WriteInt32(RET_FAILED); + return; + } + sptr callback = iface_cast(data.ReadRemoteObject()); + int32_t result = this->GetPermissionUsedRecords(*requestParcel, callback); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::DumpRecordInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenId = data.ReadUint32(); + std::string permissionName = data.ReadString(); + std::string dumpInfo = this->DumpRecordInfo(tokenId, permissionName); + reply.WriteString(dumpInfo); +} + +void PrivacyManagerStub::RegisterPermActiveStatusCallbackInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t permListSize = data.ReadUint32(); + if (permListSize > PERM_LIST_SIZE_MAX) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read permListSize fail"); + reply.WriteInt32(RET_FAILED); + return; + } + std::vector permList; + for (uint32_t i = 0; i < permListSize; i++) { + std::string perm = data.ReadString(); + permList.emplace_back(perm); + } + sptr callback = data.ReadRemoteObject(); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read ReadRemoteObject fail"); + reply.WriteInt32(RET_FAILED); + return; + } + int32_t result = this->RegisterPermActiveStatusCallback(permList, callback); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::UnRegisterPermActiveStatusCallbackInner(MessageParcel& data, MessageParcel& reply) +{ + sptr callback = data.ReadRemoteObject(); + if (callback == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "read scopeParcel fail"); + reply.WriteInt32(RET_FAILED); + return; + } + + int32_t result = this->UnRegisterPermActiveStatusCallback(callback); + reply.WriteInt32(result); +} + +void PrivacyManagerStub::IsAllowUsingPermissionInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenId = data.ReadUint32(); + std::string permissionName = data.ReadString(); + bool allowperInfo = this->IsAllowUsingPermission(tokenId, permissionName); + reply.WriteBool(allowperInfo); +} + + +bool PrivacyManagerStub::IsAccessTokenCalling() const +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + return callingUid == ACCESSTOKEN_UID; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp b/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp new file mode 100644 index 000000000..c139fe2ab --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "add_permission_used_record_test.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +void AddPermissionUsedRecordTest::SetUpTestCase() +{} + +void AddPermissionUsedRecordTest::TearDownTestCase() +{ +} + +void AddPermissionUsedRecordTest::SetUp() +{ +} + +void AddPermissionUsedRecordTest::TearDown() +{ +} + +/** + * @tc.name: AddPermissionUsedRecord_001 + * @tc.desc: cannot AddPermissionUsedRecord with invalid tokenID and permission. + * @tc.type: FUNC + * @tc.require:AR000GK6TD===== + */ +HWTEST_F(AddPermissionUsedRecordTest, AddPermissionUsedRecord_001, TestSize.Level1) +{ + int32_t successCount = 1; + int32_t fasilCount = 0; + std::string permission = "ohon.permission.READ_CONTACTS"; + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, + g_InfoParmsA.bundleName, + g_InfoParmsA.instIndex); + int32_t ret = PrivacyKit::AddPermissionUsedRecord(0, permission, successCount, fasilCount); + ASSERT_EQ(RET_FAILED, ret); + + ret = PrivacyKit::AddPermissionUsedRecord(tokenID, "", successCount, fasilCount); + ASSERT_EQ(RET_FAILED, ret); +} diff --git a/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h b/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h new file mode 100644 index 000000000..8f6f83d31 --- /dev/null +++ b/security_access_token-yl_0822/services/privacymanager/test/add_permission_used_record_test/add_permission_used_record_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ADD_PERMISSION_USED_RECORD_TEST_H +#define ADD_PERMISSION_USED_RECORD_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AddPermissionUsedRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ADD_PERMISSION_USED_RECORD_TEST_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/BUILD.gn b/security_access_token-yl_0822/services/tokensyncmanager/BUILD.gn new file mode 100644 index 000000000..d2a228711 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/BUILD.gn @@ -0,0 +1,100 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") + +ohos_prebuilt_etc("token_sync.rc") { + source = "token_sync.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "access_token" +} + +group("tokensyncmanager") { + if (is_standard_system && token_sync_enable == true) { + deps = [ + "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", + "//base/security/access_token/services/tokensyncmanager:token_sync_manager_service", + "//base/security/access_token/services/tokensyncmanager/sa_profile:tokensync_sa_profile_standard", + ] + } +} + +ohos_shared_library("token_sync_manager_service") { + subsystem_name = "security" + part_name = "access_token" + + include_dirs = [ + "include/service", + "include/remote", + "include/command", + "include/common", + "include/device", + "include/protocol", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//third_party/json/include", + ] + + sources = [ + "src/command/base_remote_command.cpp", + "src/command/delete_remote_token_command.cpp", + "src/command/sync_remote_hap_token_command.cpp", + "src/command/sync_remote_native_token_command.cpp", + "src/command/update_remote_hap_token_command.cpp", + "src/common/constant.cpp", + "src/device/device_info_manager.cpp", + "src/device/device_info_repository.cpp", + "src/remote/remote_command_executor.cpp", + "src/remote/remote_command_factory.cpp", + "src/remote/remote_command_manager.cpp", + "src/remote/soft_bus_channel.cpp", + "src/remote/soft_bus_device_connection_listener.cpp", + "src/remote/soft_bus_manager.cpp", + "src/remote/soft_bus_session_listener.cpp", + "src/service/token_sync_event_handler.cpp", + "src/service/token_sync_manager_service.cpp", + "src/service/token_sync_manager_stub.cpp", + ] + + cflags_cc = [ + "-DHILOG_ENABLE", + "-DDEBUG_API_PERFORMANCE", + ] + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/services/tokensyncmanager:token_sync.rc", + "//third_party/zlib:libz", + ] + + external_deps = [ + "c_utils:utils", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + external_deps += [ "device_manager:devicemanagersdk" ] + } +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/command/base_remote_command.h b/security_access_token-yl_0822/services/tokensyncmanager/include/command/base_remote_command.h new file mode 100644 index 000000000..70c966aac --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/command/base_remote_command.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_REMOTE_COMMON_H +#define BASE_REMOTE_COMMON_H + +#include + +#include "constant.h" +#include "hap_token_info.h" +#include "native_token_info.h" +#include "nlohmann/json.hpp" +#include "permission_state_full.h" +#include "remote_protocol.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * The base class for command. You can treat this as remote command header. + */ +class BaseRemoteCommand { +public: + BaseRemoteCommand() = default; + virtual ~BaseRemoteCommand() = default; + + /* Prepare() is called in requestor */ + virtual void Prepare() = 0; + + /* Execute() is called in responser */ + virtual void Execute() = 0; + + /* Finish() is called in requestor, after get response, but the command object is not same with the request */ + virtual void Finish() = 0; + + virtual std::string ToJsonPayload() = 0; + nlohmann::json ToRemoteProtocolJson(); + void FromRemoteProtocolJson(const nlohmann::json& jsonObject); + + void ToPermStateJson(nlohmann::json& permStateJson, const PermissionStateFull& state); + void FromPermStateListJson(const nlohmann::json& hapTokenJson, + std::vector& permStateList); + + void FromHapTokenBasicInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfo& hapTokenBasicInfo); + + nlohmann::json ToHapTokenInfosJson(const HapTokenInfoForSync &tokenInfo); + void FromHapTokenInfoJson(const nlohmann::json& hapTokenJson, HapTokenInfoForSync& hapTokenInfo); + nlohmann::json ToNativeTokenInfoJson(const NativeTokenInfoForSync& tokenInfo); + void FromNativeTokenInfoJson(const nlohmann::json& nativeTokenJson, NativeTokenInfoForSync& nativeTokenInfo); + RemoteProtocol remoteProtocol_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // BASE_REMOTE_COMMON_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/command/delete_remote_token_command.h b/security_access_token-yl_0822/services/tokensyncmanager/include/command/delete_remote_token_command.h new file mode 100644 index 000000000..66c1b9c5d --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/command/delete_remote_token_command.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DELETE_REMOTE_TOKEN_COMMAND_H +#define DELETE_REMOTE_TOKEN_COMMAND_H + +#include "base_remote_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class DeleteRemoteTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + explicit DeleteRemoteTokenCommand(const std::string &json); + DeleteRemoteTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId, + AccessTokenID deleteID); + virtual ~DeleteRemoteTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "DeleteRemoteTokenCommand"; + AccessTokenID deleteTokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h b/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h new file mode 100644 index 000000000..0ed2b2e5c --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYNC_REMOTE_HAP_TOKEN_COMMAND_H +#define SYNC_REMOTE_HAP_TOKEN_COMMAND_H + +#include + +#include "access_token.h" +#include "base_remote_command.h" +#include "hap_token_info.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class SyncRemoteHapTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + explicit SyncRemoteHapTokenCommand(const std::string &json); + SyncRemoteHapTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID id); + virtual ~SyncRemoteHapTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "SyncRemoteHapTokenCommand"; + HapTokenInfoForSync hapTokenInfo_; + AccessTokenID requestTokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif + diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_native_token_command.h b/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_native_token_command.h new file mode 100644 index 000000000..95341d16e --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/command/sync_remote_native_token_command.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYNC_REMOTE_NATIVE_TOKEN_COMMAND_H +#define SYNC_REMOTE_NATIVE_TOKEN_COMMAND_H + +#include +#include + +#include "base_remote_command.h" +#include "native_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class SyncRemoteNativeTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + SyncRemoteNativeTokenCommand(const std::string &json); + SyncRemoteNativeTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId); + virtual ~SyncRemoteNativeTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "SyncRemoteNativeTokenCommand"; + std::vector nativeTokenInfo_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/command/update_remote_hap_token_command.h b/security_access_token-yl_0822/services/tokensyncmanager/include/command/update_remote_hap_token_command.h new file mode 100644 index 000000000..f3414792a --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/command/update_remote_hap_token_command.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UPDATE_REMOTE_HAP_TOKEN_COMMAND_H +#define UPDATE_REMOTE_HAP_TOKEN_COMMAND_H + +#include + +#include "access_token.h" +#include "base_remote_command.h" +#include "hap_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class UpdateRemoteHapTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + explicit UpdateRemoteHapTokenCommand(const std::string &json); + UpdateRemoteHapTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId, + const HapTokenInfoForSync& tokenInfo); + virtual ~UpdateRemoteHapTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "UpdateRemoteHapTokenCommand"; + HapTokenInfoForSync updateTokenInfo_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/common/constant.h b/security_access_token-yl_0822/services/tokensyncmanager/include/common/constant.h new file mode 100644 index 000000000..391c68658 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/common/constant.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CONSTANT_H +#define CONSTANT_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class Constant { +public: + /** + * Indicates message format version, should be compatible. + */ + const static int32_t DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION = 2; + + /** + * Status code, indicates general success. + */ + const static int32_t SUCCESS = 0; + + /** + * Status code, indicates general failure. + */ + const static int32_t FAILURE = -1; + + /** + * Status code, indicates failure but can retry. + */ + const static int32_t FAILURE_BUT_CAN_RETRY = -2; + + /** + * Status Code, indicates invalid command. + */ + const static int32_t INVALID_COMMAND = -14; + + /** + * Session Id, indicates invalid session. + */ + const static int32_t INVALID_SESSION = -1; + + /** + * Command status code, indicate a status of command before RPC call. + */ + const static int32_t STATUS_CODE_BEFORE_RPC = 100001; + + /** + * Command result string, indicates success. + */ + static const std::string COMMAND_RESULT_SUCCESS; + + /** + * Command result string, indicates failed. + */ + static const std::string COMMAND_RESULT_FAILED; + const static int32_t DELAY_SYNC_TOKEN_MS = 3000; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // CONSTANT_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info.h b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info.h new file mode 100644 index 000000000..a57c77fe4 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_INFO_H +#define DEVICE_INFO_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum DeviceIdType { + NETWORK_ID, + UNIVERSALLY_UNIQUE_ID, + UNIQUE_DISABILITY_ID, + UNKNOWN, +}; + +struct DeviceId { + std::string networkId; + std::string universallyUniqueId; + std::string uniqueDeviceId; +}; + +struct DeviceInfo { + DeviceId deviceId; + std::string deviceName; + std::string deviceType; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // DEVICE_INFO_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_manager.h b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_manager.h new file mode 100644 index 000000000..1008a1b08 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_manager.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_INFO_MANAGER_H +#define DEVICE_INFO_MANAGER_H + +#include + +#include "accesstoken_log.h" +#include "data_validator.h" +#include "device_info_repository.h" +#include "ipc_skeleton.h" +#include "parameter.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DeviceInfoManager { +public: + static DeviceInfoManager &GetInstance(); + + /** + * Get device info by device id. + * + * @param nodeId Device id. + * @param deviceIdType Device id type {@link DeviceIdType} + * @param deviceInfo Optional deviceInfo. + * @return True for success, false otherwise. + */ + bool GetDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType, DeviceInfo &deviceInfo) const; + + /** + * Check device info exist. Online and local device info will be here. + * + * @param nodeId Device id. + * @param deviceIdType Device id type {@link DeviceIdType} + * @return True for exist, false otherwise. + */ + bool ExistDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) const; + + /** + * Add device info with device ids and device properties. + * + * @param networkId Device networkId. + * @param universallyUniqueId Device uuid. + * @param uniqueDeviceId Device udid. + * @param deviceName Device name. + * @param deviceType Device type. + */ + void AddDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDeviceId, const std::string &deviceName, const std::string &deviceType); + + /** + * Remote all device info. + */ + void RemoveAllRemoteDeviceInfo(); + + /** + * Remove one device info. + * + * @param nodeId Device id. + * @param deviceIdType Device id type {@link DeviceIdType} + */ + void RemoveRemoteDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType); + + /** + * Convert nodeId to deviceId(UUID) if possible. + * + * @param nodeId which is considered as indefinite id, maybe deviceId(UUID) or networkId. + * @return The deviceId if local or device online, otherwise return empty string. + */ + std::string ConvertToUniversallyUniqueIdOrFetch(const std::string &nodeId) const; + + /** + * Convert nodeId to deviceId(UDID) if possible. + * + * @param nodeId which is considered as indefinite id, maybe deviceId(UDID) or networkId. + * @return The deviceId if local or device online, otherwise return empty string. + */ + std::string ConvertToUniqueDeviceIdOrFetch(const std::string &nodeId) const; + + /** + * Check nodeId is uuid or not. + * + * @param nodeId Node id. + * @return True if node id is uuid. False otherwise. + */ + bool IsDeviceUniversallyUniqueId(const std::string &nodeId) const; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DEVICE_INFO_MANAGER_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_repository.h b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_repository.h new file mode 100644 index 000000000..a617e757c --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/device/device_info_repository.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_INFO_REPOSITORY_H +#define DEVICE_INFO_REPOSITORY_H + +#include +#include +#include +#include + +#include "constant.h" +#include "device_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DeviceInfoRepository { +public: + static DeviceInfoRepository &GetInstance(); + + std::vector ListDeviceInfo(); + + bool FindDeviceInfo(const std::string &nodeId, DeviceIdType type, DeviceInfo &deviceInfo); + + void DeleteAllDeviceInfoExceptOne(const DeviceInfo deviceInfo); + + void SaveDeviceInfo(const DeviceInfo deviceInfo); + + void SaveDeviceInfo(const DeviceId deviceId, const std::string &deviceName, const std::string &deviceType); + + void SaveDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDeviceId, const std::string &deviceName, const std::string &deviceType); + + void DeleteDeviceInfo(const std::string &nodeId, const DeviceIdType type); + + void Clear(); + +private: + bool FindDeviceIdByNodeIdLocked(const std::string &nodeId, const DeviceIdType type, DeviceId &deviceId) const; + + bool FindDeviceInfoByDeviceIdLocked(const DeviceId deviceId, DeviceInfo &deviceInfo) const; + + bool FindDeviceIdByNetworkIdLocked(const std::string &networkId, DeviceId &deviceId) const; + + bool FindDeviceIdByUniversallyUniqueIdLocked(const std::string &universallyUniqueId, DeviceId &deviceId) const; + + bool FindDeviceIdByUniqueDeviceIdLocked(const std::string &uniqueDeviceId, DeviceId &deviceId) const; + + void DeleteDeviceInfoByDeviceIdLocked(const DeviceId deviceId); + + std::map deviceIdMapByNetworkId_; + + std::map deviceIdMapByUniversallyUniqueId_; + + std::map deviceIdMapByUniqueDeviceId_; + + std::map deviceInfoMap_; + + std::recursive_mutex stackLock_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DEVICE_INFO_REPOSITORY_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/protocol/remote_protocol.h b/security_access_token-yl_0822/services/tokensyncmanager/include/protocol/remote_protocol.h new file mode 100644 index 000000000..3585239b5 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/protocol/remote_protocol.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REMOTE_PROTOCOL_H +#define REMOTE_PROTOCOL_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct RemoteProtocol { + std::string commandName; + std::string uniqueId; + int32_t requestVersion; + std::string srcDeviceId; + std::string srcDeviceLevel; + std::string dstDeviceId; + std::string dstDeviceLevel; + int32_t statusCode; + std::string message; + int32_t responseVersion; + std::string responseDeviceId; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_executor.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_executor.h new file mode 100644 index 000000000..40bd0f3eb --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_executor.h @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REMOTE_COMMAND_EXECUTOR_H +#define REMOTE_COMMAND_EXECUTOR_H + +#include +#include + +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "remote_command_factory.h" +#include "rpc_channel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandExecutor final { +public: + RemoteCommandExecutor(const std::string &targetNodeId); + virtual ~RemoteCommandExecutor(); + + const std::shared_ptr& GetChannel() const + { + return ptrChannel_; + } + void SetChannel(const std::shared_ptr& ptrChannel) + { + ptrChannel_ = ptrChannel; + } + + /** + * @brief Factory method to create a rpc channel. we will only create SoftBusChannel by now. + * + * @param targetNodeId target device node id(udid) + * @return Returns a shared_ptr if the operation is successful, returns nullptr otherwise. + * @see SoftBusChannel + * @since 1.0 + * @version 1.0 + */ + static const std::shared_ptr CreateChannel(const std::string &targetNodeId); + + /** + * @brief Process one command given. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns minus integer otherwise. + * @see void + * @since 1.0 + * @version 1.0 + */ + int ProcessOneCommand(const std::shared_ptr& ptrCommand); + + /** + * @brief Add one command into the buffer + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns INVALID_COMMAND otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int AddCommand(const std::shared_ptr& ptrCommand); + + /** + * @brief Process all the command in the buffer + * + * @param standalone true if run in a new thread or event runner, otherwise false. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see AddCommand ProcessOneCommand + * @since 1.0 + * @version 1.0 + */ + int ProcessBufferedCommands(bool standalone = false); + + /** + * @brief Process all the command in the buffer within a new thread. in deconstruct, we need to join this thread if + * needed. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return void + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + void ProcessBufferedCommandsWithThread(); + +private: + /** + * @brief execute a command in a specific place. + * for remote command, transfor the command json string by channel to softbus, and wait for softbus to response a + * json string. while remote response a json string, construct a remote command and finish it. + * if command buffer is empty, close the rpc channel. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @param isRemote where to run. true for remote, false for local. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ExecuteRemoteCommand(const std::shared_ptr& ptrCommand, bool isRemote); + + /** + * @brief create a rpc channel if not exist. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @param isRemote where to run. true for remote, false for local. + * @return void + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + void CreateChannelIfNeeded(); + + /** + * @brief finish a command + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ClientProcessResult(const std::shared_ptr& ptrCommand); + +private: + // target device node id(udid) + std::string targetNodeId_; + + // cached channel for buffered commands + std::shared_ptr ptrChannel_; + + // mutex to lock commands buffer for concurrent access. + std::recursive_mutex mutex_; + + // commands buffer + std::deque> commands_; + + // consumer running flag, true if the consumer is RUNNING, false otherwise. @see ProcessBufferedCommands + bool running_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // REMOTE_COMMAND_EXECUTOR_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_factory.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_factory.h new file mode 100644 index 000000000..b57559f21 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_factory.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REMOTE_COMMAND_FACTORY_H +#define REMOTE_COMMAND_FACTORY_H + +#include +#include +#include + +#include "access_token.h" +#include "delete_remote_token_command.h" +#include "hap_token_info.h" +#include "sync_remote_hap_token_command.h" +#include "sync_remote_native_token_command.h" +#include "update_remote_hap_token_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandFactory { +public: + static RemoteCommandFactory &GetInstance(); + + std::shared_ptr NewSyncRemoteHapTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID tokenID); + + std::shared_ptr NewDeleteRemoteTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID tokenID); + + std::shared_ptr NewUpdateRemoteHapTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo); + + std::shared_ptr NewSyncRemoteNativeTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId); + + std::shared_ptr NewRemoteCommandFromJson( + const std::string &commandName, const std::string &commandJsonString); + +private: + const std::string TAG = "RemoteCommandFactory"; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // REMOTE_COMMAND_FACTORY_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_manager.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_manager.h new file mode 100644 index 000000000..0621c6381 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/remote_command_manager.h @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REMOTE_COMMAND_MANAGER_H +#define REMOTE_COMMAND_MANAGER_H + +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant.h" +#include "data_validator.h" +#include "remote_command_executor.h" +#include "rpc_channel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandManager final { +public: + ~RemoteCommandManager(); + + /** + * @brief Singleton instance get method. + * + * @since 1.0 + * @version 1.0 + */ + static RemoteCommandManager &GetInstance(); + + /** + * @brief Init method. + * + * @see + * @since 1.0 + * @version 1.0 + */ + void Init(); + + /** + * @brief Execute a command now. + * + * @param udid The udid of a device which you want to execute on. if udid is empty, return -1. + * @param command A command extend BaseRemoteCommand. if command is nullptr, return -1. + * @return The execute result, returned from RemoteCommandExecutor. + * @see RemoteCommandExecutor.ExecuteOneCommand + * @since 1.0 + * @version 1.0 + */ + int ExecuteCommand(const std::string &udid, const std::shared_ptr& command); + + /** + * @brief Add a command to buffer. + * + * @param udid The udid of a device which you want to execute on. + * @param command A command extend BaseRemoteCommand. + * @return The add result, returned from RemoteCommandExecutor. by now, SUCCESS: 0. INVALID_COMMAND: -14 + * @see RemoteCommandExecutor.AddCommand + * @since 1.0 + * @version 1.0 + */ + int AddCommand(const std::string &udid, const std::shared_ptr& command); + + /** + * @brief Execute all buffered commands for given device. + * + * @param udid The udid of a device which you want to execute on. + * @return The execute result. SUCCESS: 0; FAILURE: -1. + * @see RemoteCommandExecutor.ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ProcessDeviceCommandImmediately(const std::string &udid); + + /** + * @brief Execute all buffered commands for all device asynchronized. + * + * @return The loop result. SUCCESS: 0. + * @see RemoteCommandExecutor.ProcessBufferedCommandsWithThread + * @since 1.0 + * @version 1.0 + */ + int Loop(); + + /** + * @brief Clear buffered commands. + * + * @since 1.0 + * @version 1.0 + */ + void Clear(); + + /** + * @brief Remove a command from buffer. + * + * @param udid The udid of a device which you want to remove. + */ + void RemoveCommand(const std::string &udid); + + /** + * @brief For event of device online, prepare channel and build connection with peer device. + * + * @param peerNodeId The udid of peer device. + * @return Result code indicates if notify successfully. SUCCESS: 0, FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int NotifyDeviceOnline(const std::string &peerNodeId); + + /** + * @brief For event of device offline, clean caches related to peer device. + * + * @param peerNodeId The peer device's nodeId, maybe uuid or udid . + * @return Result code indicates if notify successfully. SUCCESS: 0, FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int NotifyDeviceOffline(const std::string &peerNodeId); + + /** + * @brief Get remote command executor's channel for given nodeId. + * + * @param nodeId The peer device's nodeId, maybe uuid or udid or networkId. + * @return Channel instance if remote command executor has been created, null otherwise. + */ + std::shared_ptr GetExecutorChannel(const std::string &nodeId); + +private: + RemoteCommandManager(); + + // executors buffer + std::map> executors_; + // executors buffer mutex + std::mutex mutex_; + + /** + * @brief Fetch an executor from executors buffer. If not found, create one and cache it to buffer. + * + * @param nodeId The udid of a device which you want to get executor. + * @see void + * @since 1.0 + * @version 1.0 + */ + std::shared_ptr GetOrCreateRemoteCommandExecutor(const std::string &nodeId); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/rpc_channel.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/rpc_channel.h new file mode 100644 index 000000000..3a86540b6 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/rpc_channel.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RPC_CHANNEL_H +#define RPC_CHANNEL_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +/* + * Channel used for communicate with peer devices. + */ +class RpcChannel { +public: + /** + * @brief Build connection with peer device. + * + * @return Result code represent if build successfully. 0 indicates success, -1 indicates failure. + * @since 1.0 + * @version 1.0 + */ + virtual int BuildConnection() = 0; + + /** + * @brief Execute BaseRemoteCommand at peer device. + * + * @param commandName The name of Command. + * @param jsonPayload The json payload of command. + * @return Executed result response string. + * @since 1.0 + * @version 1.0 + */ + virtual std::string ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) = 0; + + /** + * @brief Handle data received. This interface only use for soft bus channel. + * + * @param session Session with peer device. + * @param bytes Data sent from the peer device. + * @param length Data length sent from the peer device. + * @since 1.0 + * @version 1.0 + */ + virtual void HandleDataReceived(int session, const unsigned char *bytes, int length) + {} + + /** + * @brief Close rpc connection when no data is being transmitted. + * + * @since 1.0 + * @version 1.0 + */ + virtual void CloseConnection() + {} + + /** + * @brief Release resources when the device offline. + * + * @since 1.0 + * @version 1.0 + */ + virtual void Release() {} +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_channel.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_channel.h new file mode 100644 index 000000000..775031e83 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_channel.h @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFT_BUS_CHANNEL_H +#define SOFT_BUS_CHANNEL_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "nlohmann/json.hpp" +#include "rpc_channel.h" +#include "session.h" +#include "random.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SoftBusChannel final : public RpcChannel, public std::enable_shared_from_this { +public: + SoftBusChannel(const std::string &deviceId); + virtual ~SoftBusChannel(); + + /** + * @brief Build connection with peer device. + * + * @return Result code, 0 indicated build successfully, -1 indicates failure. + * @since 1.0 + * @version 1.0 + * @see Release + */ + int BuildConnection() override; + + /** + * @brief Execute BaseRemoteCommand at peer device. + * + * @param commandName The name of Command. + * @param jsonPayload The json payload of command. + * @return Executed result response string. + * @since 1.0 + * @version 1.0 + */ + std::string ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) override; + + /** + * @brief Handle data received. This interface only use for soft bus channel. + * + * @param session Session with peer device. + * @param bytes Data sent from the peer device. + * @param length Data length sent from the peer device. + * @since 1.0 + * @version 1.0 + */ + void HandleDataReceived(int session, const unsigned char *bytes, int length) override; + + /** + * @brief Close rpc connection when no data is being transmitted. it will run in a delayed task. + * + * @since 1.0 + * @version 1.0 + */ + void CloseConnection() override; + + /** + * @brief Release resources when the device offline. + * + * @since 1.0 + * @version 1.0 + */ + void Release() override; + +private: + /** + * @brief compress json command to char array command. + * + * @param type request or response + * @param id unique message id + * @param commandName command name + * @param jsonPayload command notated by json string + * @param bytes transfer data array + * @param bytesLength transfer data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @see Compress + * @since 1.0 + * @version 1.0 + */ + int PrepareBytes(const std::string &type, const std::string &id, const std::string &commandName, + const std::string &jsonPayload, const unsigned char *bytes, int &bytesLength); + + /** + * @brief compress string to char array. + * + * @param json string to be compressed + * @param compressedBytes compressed data array + * @param compressedLength compressed data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int Compress(const std::string &json, const unsigned char *compressedBytes, int &compressedLength); + + /** + * @brief decompress char array to string. + * + * @param bytes compressed data array + * @param length compressed data length + * @return decompressed string + * @since 1.0 + * @version 1.0 + */ + std::string Decompress(const unsigned char *bytes, const int length); + + /** + * @brief transfer request data to soft bus. + * + * @param bytes data array to transfer + * @param bytesLength data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int SendRequestBytes(const unsigned char *bytes, const int bytesLength); + + /** + * @brief transfer response data to soft bus. + * + * @param session response session id + * @param bytes data array to transfer + * @param bytesLength data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int SendResponseBytes(int session, const unsigned char *bytes, const int bytesLength); + + /** + * @brief enforce session is available. if session is opened, reopen it. + * + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int CheckSessionMayReopenLocked(); + + /** + * @brief check session is available. + * + * @return The execute result, available: true, otherwise: false. + * @since 1.0 + * @version 1.0 + */ + bool IsSessionAvailable(); + + /** + * @brief cancel closing connection. + * + * @since 1.0 + * @version 1.0 + */ + void CancelCloseConnectionIfNeeded(); + + /** + * @brief request callback for HandleDataReceived + * + * @param id unique message id + * @param commandName command name + * @param jsonPayload command notated by json string + * @return decompressed string + * @see HandleDataReceived + * @since 1.0 + * @version 1.0 + */ + void HandleRequest( + int session, const std::string &id, const std::string &commandName, const std::string &jsonPayload); + + /** + * @brief response callback for HandleDataReceived + * + * @param id unique message id + * @param jsonPayload command notated by json string + * @return decompressed string + * @see HandleDataReceived + * @since 1.0 + * @version 1.0 + */ + void HandleResponse(const std::string &id, const std::string &jsonPayload); + + /** + * @brief temp function to generate uuid. + * + * @param buf uuid string + * @param bufSize uuid string size + * @since 1.0 + * @version 1.0 + */ + void random_uuid(char buf[37], int bufSize) + { + const int xbase = 15; + const int bbase = 255; + const int index6 = 6; + const int index8 = 8; + const int index3 = 3; + const int index5 = 5; + const int index7 = 7; + const int index9 = 9; + const int blen = 2; + const int uuidlen = 16; + const char *c = "89ab"; + char *p = buf; + int n; + + for (n = 0; n < uuidlen; ++n) { + int b = (int)(GetRandomUint32() % bbase); + switch (n) { + case index6: + if (sprintf_s(p, bufSize, "4%x", b % xbase) < 0) { + return; + } + break; + case index8: + if (sprintf_s(p, bufSize, "%c%x", c[GetRandomUint32() % strlen(c)], b % xbase) < 0) { + return; + } + break; + default: + if (sprintf_s(p, bufSize, "%02x", b) < 0) { + return; + } + break; + } + p += blen; + if (n == index3 || n == index5 || n == index7 || n == index9) { + *p++ = '-'; + break; + } + } + *p = 0; + // prevent array length warning + if (p - buf == bufSize) { + return; + } + } + + // bind device id for this channel + std::string deviceId_; + + // channel mutex + std::mutex mutex_; + + // connection closing state. true: in closing, false: otherwise + bool isDelayClosing_; + + // soft bus session mutex + std::mutex sessionMutex_; + + // soft bus session id, -1 for invalid session id. + int session_; + + // soft bus session busy flag, true: busy, false: otherwise + bool isSessionUsing_; + + // communication callbacks map. key: unique message id, value: response callback. + std::map> callbacks_; + + // callback function arguments: response string variable + std::string responseResult_; + // callback function execute variable + std::condition_variable loadedCond_; +}; + +class SoftBusMessage { +public: + SoftBusMessage( + const std::string &type, const std::string &id, const std::string &commandName, const std::string &jsonPayload) + : type_(type), id_(id), commandName_(commandName), jsonPayload_(jsonPayload) + {} + ~SoftBusMessage() = default; + + bool IsValid() const + { + if (this->type_.empty()) { + return false; + } + if (this->id_.empty()) { + return false; + } + if (this->commandName_.empty()) { + return false; + } + return !(this->jsonPayload_.empty()); + } + + /** + * Convert SoftBusMessage object to corresponding json string. + * + * @return Soft bus message json string. + */ + std::string ToJson() const + { + nlohmann::json json; + json["type"] = this->type_; + json["id"] = this->id_; + json["commandName"] = this->commandName_; + json["jsonPayload"] = this->jsonPayload_; + return json.dump(); + } + + const std::string &GetType() const + { + return type_; + } + const std::string &GetId() const + { + return id_; + } + const std::string &GetCommandName() const + { + return commandName_; + } + const std::string &GetJsonPayload() const + { + return jsonPayload_; + } + + static std::shared_ptr FromJson(const std::string &jsonString); +private: + std::string type_; + std::string id_; + std::string commandName_; + std::string jsonPayload_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // SOFT_BUS_CHANNEL_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h new file mode 100644 index 000000000..1f35e750b --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFT_BUS_DEVICE_CONNECTION_LISTENER_H +#define SOFT_BUS_DEVICE_CONNECTION_LISTENER_H + +#include +#include +#include + +#include "accesstoken_log.h" +#include "device_manager_callback.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class MyDmInitCallback final : public DistributedHardware::DmInitCallback { + void OnRemoteDied() override + {} +}; + +class SoftBusDeviceConnectionListener final : public DistributedHardware::DeviceStateCallback { +public: + SoftBusDeviceConnectionListener(); + ~SoftBusDeviceConnectionListener(); + + /** + * @brief node online callback + * + * @param deviceInfo node info + */ + void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + + /** + * @brief node offline callback + * + * @param deviceInfo node info + */ + void OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + + /** + * @brief node ready callback + * + * @param deviceInfo node info + */ + void OnDeviceReady(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + + /** + * @brief node changed callback + * + * @param deviceInfo node info + */ + void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_manager.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_manager.h new file mode 100644 index 000000000..ee66ebf68 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_manager.h @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFT_BUS_MANAGER_H +#define SOFT_BUS_MANAGER_H + +#include +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "device_manager.h" +#include "remote_command_executor.h" +#include "session.h" +#include "soft_bus_device_connection_listener.h" +#include "soft_bus_session_listener.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SoftBusManager final { +public: + virtual ~SoftBusManager(); + + /** + * @brief Get instance of SoftBusManager + * + * @return SoftBusManager's instance. + * @since 1.0 + * @version 1.0 + */ + static SoftBusManager &GetInstance(); + + /** + * @brief Bind soft bus service. + * + * @since 1.0 + * @version 1.0 + */ + void Initialize(); + + /** + * @brief Unbind soft bus service when DPMS has been destroyed. + * + * @since 1.0 + * @version 1.0 + */ + void Destroy(); + + /** + * @brief Open session with the peer device sychronized. + * + * @param deviceUdid The udid of peer device. + * @return Session id if open successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int OpenSession(const std::string &deviceUdid); + + /** + * @brief Close session with the peer device. + * + * @param session The session id need to close. + * @return 0 if close successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int CloseSession(int sessionId); + + /** + * @brief Get UUID(networkId) by deviceNodeId. + * + * @param deviceNodeId The valid networkId or deviceId(UDID) or deviceUuid. + * @return uuid if deviceManager is ready, empty string otherwise. + * @since 1.0 + * @version 1.0 + */ + std::string GetUniversallyUniqueIdByNodeId(const std::string &deviceNodeId); + + /** + * @brief Get deviceId(UDID) by deviceNodeId. + * + * @param deviceNodeId The valid networkId or deviceId(UDID) or deviceUuid. + * @return udid if deviceManager work correctly, empty string otherwise. + * @since 1.0 + * @version 1.0 + */ + std::string GetUniqueDeviceIdByNodeId(const std::string &deviceNodeId); + +public: + static const std::string SESSION_NAME; + +private: + SoftBusManager(); + int DeviceInit(); + int SessionInit(); + + /** + * @brief Fulfill local device info + * + * @return 0 if operate successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int FulfillLocalDeviceInfo(); + + /** + * @brief add all trusted device info. + * + * @since 1.0 + * @version 1.0 + */ + int AddTrustedDeviceInfo(); + + std::string GetUuidByNodeId(const std::string &nodeId) const; + std::string GetUdidByNodeId(const std::string &nodeId) const; + + const static std::string TOKEN_SYNC_PACKAGE_NAME; + + // soft bus session server opened flag + bool isSoftBusServiceBindSuccess_; + std::atomic_bool inited_; + + // init mutex + std::mutex mutex_; + + // fulfill thread mutex + std::mutex fulfillMutex_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SOFT_BUS_MANAGER_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_session_listener.h b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_session_listener.h new file mode 100644 index 000000000..b5dff9182 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/remote/soft_bus_session_listener.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFT_BUS_SESSION_LISTENER_H +#define SOFT_BUS_SESSION_LISTENER_H + +#include +#include +#include + +#include "accesstoken_log.h" +#include "session.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SoftBusSessionListener final { +public: + /** + * @brief Called when a session is opened. + * + * This function can be used to verify the session or initialize resources related to the session. + * + * @param sessionId Indicates the session ID. + * @param result 0 if the session is opened successfully, returns an error code otherwise. + * @return Returns 0 if the session connection is accepted; returns a non-zero value + * otherwise (you do not need to call {@link CloseSession} to close the session). + * @since 1.0 + * @version 1.0 + */ + static int32_t OnSessionOpened(int32_t sessionId, int32_t result); + + /** + * @brief Called when a session is closed. + * + * This function can be used to release resources related to the session. + * You do not need to call {@link CloseSession}. + * + * @param sessionId Indicates the session ID. + * @since 1.0 + * @version 1.0 + */ + static void OnSessionClosed(int32_t sessionId); + + /** + * @brief Called when data is received. + * + * This function is used to notify that data is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data received. + * @param dataLen Indicates the length of the data received. + * @since 1.0 + * @version 1.0 + */ + static void OnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen); + + /** + * @brief Called when message is received. + * + * This function is used to notify that message is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data received. + * @param dataLen Indicates the length of the message received. + * @since 1.0 + * @version 1.0 + */ + static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + + /** + * @brief get the state of a session. + * + * This function is used to verify that session is opened. + * + * @param sessionId Indicates the session ID. + * @return -2: sessionId not used, -1: session is in opening, greater than 0: session is opened. + * @since 1.0 + * @version 1.0 + */ + static int64_t GetSessionState(int32_t sessionId); + + static void DeleteSessionIdFromMap(int32_t sessionId); + + static const int64_t STATE_OPENING = -1; + static const int64_t STATE_NOTFOUND = -2; + static const int64_t MAX_ONBYTES_RECEIVED_DATA_LEN = 1024 * 1024 * 10; + +private: + /** + * key: sessionId, value: status. + * status: -1: opening, >0: opened timestamp + */ + static std::map g_SessionOpenedMap_; + /** + * mutex for map + */ + static std::mutex g_SessionMutex_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SOFT_BUS_SESSION_LISTENER_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_event_handler.h b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_event_handler.h new file mode 100644 index 000000000..db9ceaabd --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_event_handler.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_EVENT_HANDLER_H +#define TOKEN_SYNC_EVENT_HANDLER_H + +#include + +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncEventHandler : public AppExecFwk::EventHandler { +public: + explicit TokenSyncEventHandler(const std::shared_ptr& runner); + virtual ~TokenSyncEventHandler(); + + bool ProxyPostTask(const Callback &callback, int64_t delayTime); + + bool ProxyPostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + + void ProxyRemoveTask(const std::string &name); + +private: +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_EVENT_HANDLER_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_service.h b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_service.h new file mode 100644 index 000000000..0a796dbaf --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_service.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_MANAGER_SERVICE_H +#define TOKEN_SYNC_MANAGER_SERVICE_H + +#include + +#include "event_handler.h" +#include "hap_token_info_for_sync_parcel.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "singleton.h" +#include "system_ability.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_stub.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class TokenSyncManagerService final : public SystemAbility, public TokenSyncManagerStub { + DECLARE_DELAYED_SINGLETON(TokenSyncManagerService); + DECLEAR_SYSTEM_ABILITY(TokenSyncManagerService); + +public: + void OnStart() override; + void OnStop() override; + + std::shared_ptr GetSendEventHandler() const; + std::shared_ptr GetRecvEventHandler() const; + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) override; + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) override; + +private: + bool Initialize(); + + std::shared_ptr sendRunner_; + std::shared_ptr recvRunner_; + std::shared_ptr sendHandler_; + std::shared_ptr recvHandler_; + ServiceRunningState state_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_MANAGER_SERVICE_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_stub.h b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_stub.h new file mode 100644 index 000000000..f16fd8dd7 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/include/service/token_sync_manager_stub.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_MANAGER_STUB_H +#define TOKEN_SYNC_MANAGER_STUB_H + +#include "i_token_sync_manager.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncManagerStub : public IRemoteStub { +public: + TokenSyncManagerStub() = default; + virtual ~TokenSyncManagerStub() = default; + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override; + +private: + void GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_MANAGER_STUB_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/3504.xml b/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/3504.xml new file mode 100644 index 000000000..b0ef046f1 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/3504.xml @@ -0,0 +1,24 @@ + + + + token_sync_service + + 3504 + libtoken_sync_manager_service.z.so + false + true + 1 + + diff --git a/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/BUILD.gn b/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/BUILD.gn new file mode 100644 index 000000000..e993e0125 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/sa_profile/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/ohos.gni") +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("tokensync_sa_profile_standard") { + part_name = "access_token" + + sources = [ "3504.xml" ] +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/command/base_remote_command.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/command/base_remote_command.cpp new file mode 100644 index 000000000..404ac72a7 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/command/base_remote_command.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "base_remote_command.h" + +#include "accesstoken_log.h" +#include "data_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "BaseRemoteCommand"}; +} + +void BaseRemoteCommand::FromRemoteProtocolJson(const nlohmann::json& jsonObject) +{ + if (jsonObject.find("commandName") != jsonObject.end() && jsonObject.at("commandName").is_string()) { + remoteProtocol_.commandName = jsonObject.at("commandName").get(); + } + if (jsonObject.find("uniqueId") != jsonObject.end() && jsonObject.at("uniqueId").is_string()) { + remoteProtocol_.uniqueId = jsonObject.at("uniqueId").get(); + } + if (jsonObject.find("requestVersion") != jsonObject.end() && jsonObject.at("requestVersion").is_number()) { + remoteProtocol_.requestVersion = jsonObject.at("requestVersion").get(); + } + if (jsonObject.find("srcDeviceId") != jsonObject.end() && jsonObject.at("srcDeviceId").is_string()) { + remoteProtocol_.srcDeviceId = jsonObject.at("srcDeviceId").get(); + } + if (jsonObject.find("srcDeviceLevel") != jsonObject.end() && jsonObject.at("srcDeviceLevel").is_string()) { + remoteProtocol_.srcDeviceLevel = jsonObject.at("srcDeviceLevel").get(); + } + if (jsonObject.find("dstDeviceId") != jsonObject.end() && jsonObject.at("dstDeviceId").is_string()) { + remoteProtocol_.dstDeviceId = jsonObject.at("dstDeviceId").get(); + } + if (jsonObject.find("dstDeviceLevel") != jsonObject.end() && jsonObject.at("dstDeviceLevel").is_string()) { + remoteProtocol_.dstDeviceLevel = jsonObject.at("dstDeviceLevel").get(); + } + if (jsonObject.find("statusCode") != jsonObject.end() && jsonObject.at("statusCode").is_number()) { + remoteProtocol_.statusCode = jsonObject.at("statusCode").get(); + } + if (jsonObject.find("message") != jsonObject.end() && jsonObject.at("message").is_string()) { + remoteProtocol_.message = jsonObject.at("message").get(); + } + if (jsonObject.find("responseVersion") != jsonObject.end() && jsonObject.at("responseVersion").is_number()) { + remoteProtocol_.responseVersion = jsonObject.at("responseVersion").get(); + } + if (jsonObject.find("responseDeviceId") != jsonObject.end() && jsonObject.at("responseDeviceId").is_string()) { + remoteProtocol_.responseDeviceId = jsonObject.at("responseDeviceId").get(); + } +} + +nlohmann::json BaseRemoteCommand::ToRemoteProtocolJson() +{ + nlohmann::json j; + j["commandName"] = remoteProtocol_.commandName; + j["uniqueId"] = remoteProtocol_.uniqueId; + j["requestVersion"] = remoteProtocol_.requestVersion; + j["srcDeviceId"] = remoteProtocol_.srcDeviceId; + j["srcDeviceLevel"] = remoteProtocol_.srcDeviceLevel; + j["dstDeviceId"] = remoteProtocol_.dstDeviceId; + j["dstDeviceLevel"] = remoteProtocol_.dstDeviceLevel; + j["statusCode"] = remoteProtocol_.statusCode; + j["message"] = remoteProtocol_.message; + j["responseVersion"] = remoteProtocol_.responseVersion; + j["responseDeviceId"] = remoteProtocol_.responseDeviceId; + return j; +} + +nlohmann::json BaseRemoteCommand::ToNativeTokenInfoJson(const NativeTokenInfoForSync& tokenInfo) +{ + nlohmann::json permStatesJson; + for (const auto& permState : tokenInfo.permStateList) { + nlohmann::json permStateJson; + ToPermStateJson(permStateJson, permState); + permStatesJson.emplace_back(permStateJson); + } + + nlohmann::json DcapsJson = nlohmann::json(tokenInfo.baseInfo.dcap); + nlohmann::json NativeAclsJson = nlohmann::json(tokenInfo.baseInfo.nativeAcls); + nlohmann::json nativeTokenJson = nlohmann::json { + {"processName", tokenInfo.baseInfo.processName}, + {"apl", tokenInfo.baseInfo.apl}, + {"version", tokenInfo.baseInfo.ver}, + {"tokenId", tokenInfo.baseInfo.tokenID}, + {"tokenAttr", tokenInfo.baseInfo.tokenAttr}, + {"dcaps", DcapsJson}, + {"nativeAcls", NativeAclsJson}, + {"permState", permStatesJson}, + }; + return nativeTokenJson; +} + +void BaseRemoteCommand::ToPermStateJson(nlohmann::json& permStateJson, const PermissionStateFull& state) +{ + if (state.resDeviceID.size() != state.grantStatus.size() || state.resDeviceID.size() != state.grantFlags.size()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "state grant config size is invalid"); + return; + } + nlohmann::json permConfigsJson; + int size = (signed)state.resDeviceID.size(); + for (int i = 0; i < size; i++) { + nlohmann::json permConfigJson = nlohmann::json { + {"resDeviceID", state.resDeviceID[i]}, + {"grantStatus", state.grantStatus[i]}, + {"grantFlags", state.grantFlags[i]}, + }; + permConfigsJson.emplace_back(permConfigJson); + } + + permStateJson["permissionName"] = state.permissionName; + permStateJson["isGeneral"] = state.isGeneral; + permStateJson["grantConfig"] = permConfigsJson; +} + +nlohmann::json BaseRemoteCommand::ToHapTokenInfosJson(const HapTokenInfoForSync& tokenInfo) +{ + nlohmann::json permStatesJson; + for (const auto& permState : tokenInfo.permStateList) { + nlohmann::json permStateJson; + ToPermStateJson(permStateJson, permState); + permStatesJson.emplace_back(permStateJson); + } + + nlohmann::json hapTokensJson = nlohmann::json { + {"version", tokenInfo.baseInfo.ver}, + {"tokenID", tokenInfo.baseInfo.tokenID}, + {"tokenAttr", tokenInfo.baseInfo.tokenAttr}, + {"userID", tokenInfo.baseInfo.userID}, + {"bundleName", tokenInfo.baseInfo.bundleName}, + {"instIndex", tokenInfo.baseInfo.instIndex}, + {"dlpType", tokenInfo.baseInfo.dlpType}, + {"appID", tokenInfo.baseInfo.appID}, + {"deviceID", tokenInfo.baseInfo.deviceID}, + {"apl", tokenInfo.baseInfo.apl}, + {"permState", permStatesJson} + }; + return hapTokensJson; +} + +void BaseRemoteCommand::FromHapTokenBasicInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfo& hapTokenBasicInfo) +{ + if (hapTokenJson.find("version") != hapTokenJson.end() && hapTokenJson.at("version").is_number()) { + hapTokenJson.at("version").get_to(hapTokenBasicInfo.ver); + } + if (hapTokenJson.find("tokenID") != hapTokenJson.end() && hapTokenJson.at("tokenID").is_number()) { + hapTokenJson.at("tokenID").get_to(hapTokenBasicInfo.tokenID); + } + if (hapTokenJson.find("tokenAttr") != hapTokenJson.end() && hapTokenJson.at("tokenAttr").is_number()) { + hapTokenJson.at("tokenAttr").get_to(hapTokenBasicInfo.tokenAttr); + } + if (hapTokenJson.find("userID") != hapTokenJson.end() && hapTokenJson.at("userID").is_number()) { + hapTokenJson.at("userID").get_to(hapTokenBasicInfo.userID); + } + if (hapTokenJson.find("bundleName") != hapTokenJson.end() && hapTokenJson.at("bundleName").is_string()) { + hapTokenJson.at("bundleName").get_to(hapTokenBasicInfo.bundleName); + } + if (hapTokenJson.find("instIndex") != hapTokenJson.end() && hapTokenJson.at("instIndex").is_number()) { + hapTokenJson.at("instIndex").get_to(hapTokenBasicInfo.instIndex); + } + if (hapTokenJson.find("dlpType") != hapTokenJson.end() && hapTokenJson.at("dlpType").is_number()) { + hapTokenJson.at("dlpType").get_to(hapTokenBasicInfo.dlpType); + } + if (hapTokenJson.find("appID") != hapTokenJson.end() && hapTokenJson.at("appID").is_string()) { + hapTokenJson.at("appID").get_to(hapTokenBasicInfo.appID); + } + if (hapTokenJson.find("deviceID") != hapTokenJson.end() && hapTokenJson.at("deviceID").is_string()) { + hapTokenJson.at("deviceID").get_to(hapTokenBasicInfo.deviceID); + } + if (hapTokenJson.find("apl") != hapTokenJson.end() && hapTokenJson.at("apl").is_number()) { + int apl = hapTokenJson.at("apl").get(); + if (DataValidator::IsAplNumValid(apl)) { + hapTokenBasicInfo.apl = (ATokenAplEnum)apl; + } + } +} + +void BaseRemoteCommand::FromPermStateListJson(const nlohmann::json& hapTokenJson, + std::vector& permStateList) +{ + if (hapTokenJson.find("permState") != hapTokenJson.end() + && hapTokenJson.at("permState").is_array() + && !hapTokenJson.at("permState").empty()) { + nlohmann::json permissionsJson = hapTokenJson.at("permState").get(); + for (const auto& permissionJson : permissionsJson) { + PermissionStateFull permission; + if (permissionJson.find("permissionName") == permissionJson.end() || + !permissionJson.at("permissionName").is_string() || + permissionJson.find("isGeneral") == permissionJson.end() || + !permissionJson.at("isGeneral").is_boolean() || + permissionJson.find("grantConfig") == permissionJson.end() || + !permissionJson.at("grantConfig").is_array() || + permissionJson.at("grantConfig").empty()) { + continue; + } + permissionJson.at("permissionName").get_to(permission.permissionName); + permissionJson.at("isGeneral").get_to(permission.isGeneral); + nlohmann::json grantConfigsJson = permissionJson.at("grantConfig").get(); + for (const auto& grantConfigJson :grantConfigsJson) { + if (grantConfigJson.find("resDeviceID") == grantConfigJson.end() || + !grantConfigJson.at("resDeviceID").is_string() || + grantConfigJson.find("grantStatus") == grantConfigJson.end() || + !grantConfigJson.at("grantStatus").is_number() || + grantConfigJson.find("grantFlags") == grantConfigJson.end() || + !grantConfigJson.at("grantFlags").is_number()) { + continue; + } + std::string deviceID; + grantConfigJson.at("resDeviceID").get_to(deviceID); + int grantStatus; + grantConfigJson.at("grantStatus").get_to(grantStatus); + int grantFlags; + grantConfigJson.at("grantFlags").get_to(grantFlags); + permission.resDeviceID.emplace_back(deviceID); + permission.grantStatus.emplace_back(grantStatus); + permission.grantFlags.emplace_back(grantFlags); + } + permStateList.emplace_back(permission); + } + } +} + +void BaseRemoteCommand::FromHapTokenInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfoForSync& hapTokenInfo) +{ + FromHapTokenBasicInfoJson(hapTokenJson, hapTokenInfo.baseInfo); + if (hapTokenInfo.baseInfo.tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Hap token basic info is error."); + return; + } + FromPermStateListJson(hapTokenJson, hapTokenInfo.permStateList); +} + +void BaseRemoteCommand::FromNativeTokenInfoJson(const nlohmann::json& nativeTokenJson, + NativeTokenInfoForSync& nativeTokenInfo) +{ + if (nativeTokenJson.find("processName") != nativeTokenJson.end() && nativeTokenJson.at("processName").is_string()) { + nativeTokenInfo.baseInfo.processName = nativeTokenJson.at("processName").get(); + } + if (nativeTokenJson.find("apl") != nativeTokenJson.end() && nativeTokenJson.at("apl").is_number()) { + int apl = nativeTokenJson.at("apl").get(); + if (DataValidator::IsAplNumValid(apl)) { + nativeTokenInfo.baseInfo.apl = (ATokenAplEnum)apl; + } + } + if (nativeTokenJson.find("version") != nativeTokenJson.end() && nativeTokenJson.at("version").is_number()) { + nativeTokenInfo.baseInfo.ver = (unsigned)nativeTokenJson.at("version").get(); + } + if (nativeTokenJson.find("tokenId") != nativeTokenJson.end() && nativeTokenJson.at("tokenId").is_number()) { + nativeTokenInfo.baseInfo.tokenID = (unsigned)nativeTokenJson.at("tokenId").get(); + } + if (nativeTokenJson.find("tokenAttr") != nativeTokenJson.end() && nativeTokenJson.at("tokenAttr").is_number()) { + nativeTokenInfo.baseInfo.tokenAttr = (unsigned)nativeTokenJson.at("tokenAttr").get(); + } + if (nativeTokenJson.find("dcaps") != nativeTokenJson.end() && nativeTokenJson.at("dcaps").is_array() + && !nativeTokenJson.at("dcaps").empty() && (nativeTokenJson.at("dcaps"))[0].is_string()) { + nativeTokenInfo.baseInfo.dcap = nativeTokenJson.at("dcaps").get>(); + } + if (nativeTokenJson.find("nativeAcls") != nativeTokenJson.end() && nativeTokenJson.at("nativeAcls").is_array() + && !nativeTokenJson.at("nativeAcls").empty() && (nativeTokenJson.at("nativeAcls"))[0].is_string()) { + nativeTokenInfo.baseInfo.nativeAcls = nativeTokenJson.at("nativeAcls").get>(); + } + + FromPermStateListJson(nativeTokenJson, nativeTokenInfo.permStateList); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/command/delete_remote_token_command.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/command/delete_remote_token_command.cpp new file mode 100644 index 000000000..d659b1c80 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/command/delete_remote_token_command.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "delete_remote_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant_common.h" +#include "device_info.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DeleteRemoteTokenCommand"}; +} + +DeleteRemoteTokenCommand::DeleteRemoteTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID deleteID) + : deleteTokenId_(deleteID) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +DeleteRemoteTokenCommand::DeleteRemoteTokenCommand(const std::string& json) +{ + deleteTokenId_ = 0; + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("tokenId") != jsonObject.end() && jsonObject.at("tokenId").is_number()) { + deleteTokenId_ = (AccessTokenID)jsonObject.at("tokenId").get(); + } +} + +std::string DeleteRemoteTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + if (j.is_discarded()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "j is invalid."); + return ""; + } + j["tokenId"] = deleteTokenId_; + return j.dump(); +} + +void DeleteRemoteTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "end as: DeleteRemoteTokenCommand"); +} + +void DeleteRemoteTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: DeleteRemoteTokenCommand"); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.srcDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "error: get remote uniqueDeviceId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + + std::string uniqueDeviceId = devInfo.deviceId.uniqueDeviceId; + int ret = AccessTokenKit::DeleteRemoteToken(uniqueDeviceId, deleteTokenId_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: DeleteRemoteTokenCommand"); +} + +void DeleteRemoteTokenCommand::Finish() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: DeleteUidPermissionCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp new file mode 100644 index 000000000..c7f065cc4 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sync_remote_hap_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "constant_common.h" +#include "base_remote_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SyncRemoteHapTokenCommand"}; +} + +SyncRemoteHapTokenCommand::SyncRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID id) : requestTokenId_(id) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + hapTokenInfo_.baseInfo.apl = APL_NORMAL; + hapTokenInfo_.baseInfo.appID = ""; + hapTokenInfo_.baseInfo.bundleName = ""; + hapTokenInfo_.baseInfo.deviceID = ""; + hapTokenInfo_.baseInfo.instIndex = 0; + hapTokenInfo_.baseInfo.dlpType = 0; + hapTokenInfo_.baseInfo.tokenAttr = 0; + hapTokenInfo_.baseInfo.tokenID = 0; + hapTokenInfo_.baseInfo.userID = 0; + hapTokenInfo_.baseInfo.ver = DEFAULT_TOKEN_VERSION; +} + +SyncRemoteHapTokenCommand::SyncRemoteHapTokenCommand(const std::string &json) +{ + requestTokenId_ = 0; + hapTokenInfo_.baseInfo.apl = APL_INVALID; + hapTokenInfo_.baseInfo.appID = ""; + hapTokenInfo_.baseInfo.bundleName = ""; + hapTokenInfo_.baseInfo.deviceID = ""; + hapTokenInfo_.baseInfo.instIndex = 0; + hapTokenInfo_.baseInfo.dlpType = 0; + hapTokenInfo_.baseInfo.tokenAttr = 0; + hapTokenInfo_.baseInfo.tokenID = 0; + hapTokenInfo_.baseInfo.userID = 0; + hapTokenInfo_.baseInfo.ver = DEFAULT_TOKEN_VERSION; + + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + if (jsonObject.find("requestTokenId") != jsonObject.end() && jsonObject.at("requestTokenId").is_number()) { + jsonObject.at("requestTokenId").get_to(requestTokenId_); + } + + if (jsonObject.find("HapTokenInfo") != jsonObject.end()) { + nlohmann::json hapTokenJson = jsonObject.at("HapTokenInfo").get(); + BaseRemoteCommand::FromHapTokenInfoJson(hapTokenJson, hapTokenInfo_); + } +} + +std::string SyncRemoteHapTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + j["requestTokenId"] = requestTokenId_; + j["HapTokenInfo"] = BaseRemoteCommand::ToHapTokenInfosJson(hapTokenInfo_); + return j.dump(); +} + +void SyncRemoteHapTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, " end as: SyncRemoteHapTokenCommand"); +} + +void SyncRemoteHapTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteHapTokenCommand"); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + int ret = AccessTokenKit::GetHapTokenInfoFromRemote(requestTokenId_, hapTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: SyncRemoteHapTokenCommand"); +} + +void SyncRemoteHapTokenCommand::Finish() +{ + if (remoteProtocol_.statusCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Finish: end as: SyncRemoteHapTokenCommand get remote result error."); + return; + } + AccessTokenKit::SetRemoteHapTokenInfo(remoteProtocol_.dstDeviceId, hapTokenInfo_); + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: SyncRemoteHapTokenCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp new file mode 100644 index 000000000..a60338aab --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sync_remote_native_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant_common.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SyncRemoteNativeTokenCommand"}; +} + +SyncRemoteNativeTokenCommand::SyncRemoteNativeTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +SyncRemoteNativeTokenCommand::SyncRemoteNativeTokenCommand(const std::string &json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("NativeTokenInfos") != jsonObject.end() && jsonObject.at("NativeTokenInfos").is_array()) { + nlohmann::json nativeTokenListJson = jsonObject.at("NativeTokenInfos"); + for (const auto& tokenJson : nativeTokenListJson) { + NativeTokenInfoForSync token; + BaseRemoteCommand::FromNativeTokenInfoJson(tokenJson, token); + nativeTokenInfo_.emplace_back(token); + } + } +} + +std::string SyncRemoteNativeTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + nlohmann::json nativeTokensJson; + for (const auto& token : nativeTokenInfo_) { + nlohmann::json tokenJson = BaseRemoteCommand::ToNativeTokenInfoJson(token); + nativeTokensJson.emplace_back(tokenJson); + } + j["NativeTokenInfos"] = nativeTokensJson; + return j.dump(); +} + +void SyncRemoteNativeTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, "end as: SyncRemoteNativeTokenCommand"); +} + +void SyncRemoteNativeTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteNativeTokenCommand"); + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + int ret = AccessTokenKit::GetAllNativeTokenInfo(nativeTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: SyncRemoteNativeTokenCommand"); +} + +void SyncRemoteNativeTokenCommand::Finish() +{ + if (remoteProtocol_.statusCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Finish: end as: SyncRemoteHapTokenCommand get remote result error."); + return; + } + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.dstDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_ERROR(LABEL, "SyncRemoteNativeTokenCommand: get remote uniqueDeviceId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + int ret = AccessTokenKit::SetRemoteNativeTokenInfo(devInfo.deviceId.uniqueDeviceId, nativeTokenInfo_); + if (ret == RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::SUCCESS; + } else { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: SyncRemoteNativeTokenCommand ret %{public}d", ret); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp new file mode 100644 index 000000000..62f7ad830 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "update_remote_hap_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant_common.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "UpdateRemoteHapTokenCommand"}; +} + +UpdateRemoteHapTokenCommand::UpdateRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo) + : updateTokenInfo_(tokenInfo) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +UpdateRemoteHapTokenCommand::UpdateRemoteHapTokenCommand(const std::string &json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("HapTokenInfos") != jsonObject.end()) { + nlohmann::json hapTokenJson = jsonObject.at("HapTokenInfos").get(); + BaseRemoteCommand::FromHapTokenInfoJson(hapTokenJson, updateTokenInfo_); + } +} + +std::string UpdateRemoteHapTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + j["HapTokenInfos"] = BaseRemoteCommand::ToHapTokenInfosJson(updateTokenInfo_); + return j.dump(); +} + +void UpdateRemoteHapTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, "end as: UpdateRemoteHapTokenCommand"); +} + +void UpdateRemoteHapTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: UpdateRemoteHapTokenCommand"); + + remoteProtocol_.responseDeviceId = ConstantCommon::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.srcDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "UpdateRemoteHapTokenCommand: get remote uniqueDeviceId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + + std::string uniqueDeviceId = devInfo.deviceId.uniqueDeviceId; + int ret = AccessTokenKit::SetRemoteHapTokenInfo(uniqueDeviceId, updateTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: UpdateRemoteHapTokenCommand"); +} + +void UpdateRemoteHapTokenCommand::Finish() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: DeleteUidPermissionCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/common/constant.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/common/constant.cpp new file mode 100644 index 000000000..7de4ff187 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/common/constant.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "constant.h" +#include "parameter.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static const std::string REPLACE_TARGET = "****"; +} // namespace +const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; +const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_manager.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_manager.cpp new file mode 100644 index 000000000..9c6723618 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_manager.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_info_manager.h" +#include "constant_common.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DeviceInfoManager"}; +} +DeviceInfoManager &DeviceInfoManager::GetInstance() +{ + static DeviceInfoManager instance; + return instance; +} + +bool DeviceInfoManager::GetDeviceInfo( + const std::string &nodeId, DeviceIdType deviceIdType, DeviceInfo &deviceInfo) const +{ + return DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo); +} + +bool DeviceInfoManager::ExistDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) const +{ + DeviceInfo deviceInfo; + return DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo); +} + +void DeviceInfoManager::AddDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDeviceId, const std::string &deviceName, const std::string &deviceType) +{ + if (!DataValidator::IsDeviceIdValid(networkId) || + !DataValidator::IsDeviceIdValid(universallyUniqueId) || + !DataValidator::IsDeviceIdValid(uniqueDeviceId) || deviceName.empty() || deviceType.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "addDeviceInfo: input param is invalid"); + return; + } + DeviceInfoRepository::GetInstance().SaveDeviceInfo( + networkId, universallyUniqueId, uniqueDeviceId, deviceName, deviceType); +} + +void DeviceInfoManager::RemoveAllRemoteDeviceInfo() +{ + std::string localDevice = ConstantCommon::GetLocalDeviceId(); + + DeviceInfo localDeviceInfoOpt; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo( + localDevice, DeviceIdType::UNIQUE_DISABILITY_ID, localDeviceInfoOpt)) { + DeviceInfoRepository::GetInstance().DeleteAllDeviceInfoExceptOne(localDeviceInfoOpt); + } +} + +void DeviceInfoManager::RemoveRemoteDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "removeDeviceInfoByNetworkId: nodeId is invalid"); + } else { + DeviceInfo deviceInfo; + std::string localDevice = ConstantCommon::GetLocalDeviceId(); + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo)) { + if (deviceInfo.deviceId.uniqueDeviceId != localDevice) { + DeviceInfoRepository::GetInstance().DeleteDeviceInfo(nodeId, deviceIdType); + } + } + } +} + +std::string DeviceInfoManager::ConvertToUniversallyUniqueIdOrFetch(const std::string &nodeId) const +{ + std::string result; + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertToUniversallyUniqueIdOrFetch: nodeId is invalid."); + return result; + } + DeviceInfo deviceInfo; + if (!(DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNKNOWN, deviceInfo))) { + return result; + } + std::string universallyUniqueId = deviceInfo.deviceId.universallyUniqueId; + if (!universallyUniqueId.empty()) { + result = universallyUniqueId; + return result; + } + std::string udid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(nodeId); + if (!udid.empty()) { + result = udid; + } + return result; +} + +std::string DeviceInfoManager::ConvertToUniqueDeviceIdOrFetch(const std::string &nodeId) const +{ + std::string result; + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertToUniqueDeviceIdOrFetch: nodeId is invalid."); + return result; + } + DeviceInfo deviceInfo; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNKNOWN, deviceInfo)) { + std::string uniqueDeviceId = deviceInfo.deviceId.uniqueDeviceId; + if (uniqueDeviceId.empty()) { + std::string udid = SoftBusManager::GetInstance().GetUniqueDeviceIdByNodeId(nodeId); + if (!udid.empty()) { + result = udid; + } else { + ACCESSTOKEN_LOG_DEBUG(LABEL, + "FindDeviceInfo succeed, udid and local udid is empty, nodeId(%{public}s)", + ConstantCommon::EncryptDevId(nodeId).c_str()); + } + } else { + ACCESSTOKEN_LOG_DEBUG(LABEL, + "FindDeviceInfo succeed, udid is empty, nodeId(%{public}s) ", + ConstantCommon::EncryptDevId(nodeId).c_str()); + result = uniqueDeviceId; + } + } else { + ACCESSTOKEN_LOG_DEBUG( + LABEL, "FindDeviceInfo failed, nodeId(%{public}s)", + ConstantCommon::EncryptDevId(nodeId).c_str()); + auto list = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + auto iter = list.begin(); + for (; iter != list.end(); iter++) { + DeviceInfo info = (*iter); + ACCESSTOKEN_LOG_DEBUG( + LABEL, ">>> DeviceInfoRepository device name: %{public}s", info.deviceName.c_str()); + ACCESSTOKEN_LOG_DEBUG( + LABEL, ">>> DeviceInfoRepository device type: %{public}s", info.deviceType.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, + ">>> DeviceInfoRepository device network id: %{public}s", + ConstantCommon::EncryptDevId(info.deviceId.networkId).c_str()); + } + } + return result; +} + +bool DeviceInfoManager::IsDeviceUniversallyUniqueId(const std::string &nodeId) const +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "IsDeviceUniversallyUniqueId: nodeId is invalid"); + return false; + } + DeviceInfo deviceInfo; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNIVERSALLY_UNIQUE_ID, deviceInfo)) { + return deviceInfo.deviceId.universallyUniqueId == nodeId; + } + return false; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_repository.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_repository.cpp new file mode 100644 index 000000000..7af7614da --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/device/device_info_repository.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_info_repository.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +DeviceInfoRepository &DeviceInfoRepository::GetInstance() +{ + static DeviceInfoRepository instance; + return instance; +} + +std::vector DeviceInfoRepository::ListDeviceInfo() +{ + std::lock_guard guard(stackLock_); + std::vector deviceInfo; + + std::map::iterator it; + std::map::iterator itEnd; + it = deviceInfoMap_.begin(); + itEnd = deviceInfoMap_.end(); + while (it != itEnd) { + deviceInfo.push_back(it->second); + it++; + } + return deviceInfo; +} + +bool DeviceInfoRepository::FindDeviceInfo(const std::string &nodeId, DeviceIdType type, DeviceInfo &deviceInfo) +{ + std::lock_guard guard(stackLock_); + DeviceId deviceId; + if (FindDeviceIdByNodeIdLocked(nodeId, type, deviceId)) { + return FindDeviceInfoByDeviceIdLocked(deviceId, deviceInfo); + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByNodeIdLocked( + const std::string &nodeId, const DeviceIdType type, DeviceId &deviceId) const +{ + if (type == DeviceIdType::NETWORK_ID) { + return FindDeviceIdByNetworkIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNIVERSALLY_UNIQUE_ID) { + return FindDeviceIdByUniversallyUniqueIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNIQUE_DISABILITY_ID) { + return FindDeviceIdByUniqueDeviceIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNKNOWN) { + if (FindDeviceIdByNetworkIdLocked(nodeId, deviceId)) { + return true; + } else if (FindDeviceIdByUniversallyUniqueIdLocked(nodeId, deviceId)) { + return true; + } else if (FindDeviceIdByUniqueDeviceIdLocked(nodeId, deviceId)) { + return true; + } + return false; + } else { + return false; + } +} + +bool DeviceInfoRepository::FindDeviceInfoByDeviceIdLocked(const DeviceId deviceId, DeviceInfo &deviceInfo) const +{ + std::string deviceInfoKey = deviceId.networkId + deviceId.universallyUniqueId + deviceId.uniqueDeviceId; + if (deviceInfoMap_.count(deviceInfoKey) > 0) { + deviceInfo = deviceInfoMap_.at(deviceInfoKey); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByNetworkIdLocked(const std::string &networkId, DeviceId &deviceId) const +{ + if (deviceIdMapByNetworkId_.count(networkId) > 0) { + deviceId = deviceIdMapByNetworkId_.at(networkId); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByUniversallyUniqueIdLocked( + const std::string &universallyUniqueId, DeviceId &deviceId) const +{ + if (deviceIdMapByUniversallyUniqueId_.count(universallyUniqueId) > 0) { + deviceId = deviceIdMapByUniversallyUniqueId_.at(universallyUniqueId); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByUniqueDeviceIdLocked( + const std::string &uniqueDeviceId, DeviceId &deviceId) const +{ + if (deviceIdMapByUniqueDeviceId_.count(uniqueDeviceId) > 0) { + deviceId = deviceIdMapByUniqueDeviceId_.at(uniqueDeviceId); + return true; + } + return false; +} + +void DeviceInfoRepository::DeleteAllDeviceInfoExceptOne(const DeviceInfo deviceInfo) +{ + std::lock_guard guard(stackLock_); + deviceIdMapByNetworkId_.clear(); + deviceIdMapByUniversallyUniqueId_.clear(); + deviceIdMapByUniqueDeviceId_.clear(); + deviceInfoMap_.clear(); + SaveDeviceInfo(deviceInfo); +} + +void DeviceInfoRepository::SaveDeviceInfo(const DeviceInfo deviceInfo) +{ + SaveDeviceInfo(deviceInfo.deviceId, deviceInfo.deviceName, deviceInfo.deviceType); +} + +void DeviceInfoRepository::SaveDeviceInfo( + const DeviceId deviceId, const std::string &deviceName, const std::string &deviceType) +{ + SaveDeviceInfo( + deviceId.networkId, deviceId.universallyUniqueId, deviceId.uniqueDeviceId, deviceName, deviceType); +} + +void DeviceInfoRepository::SaveDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDeviceId, const std::string &deviceName, const std::string &deviceType) +{ + std::lock_guard guard(stackLock_); + + DeleteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + DeleteDeviceInfo(universallyUniqueId, DeviceIdType::UNIVERSALLY_UNIQUE_ID); + DeleteDeviceInfo(uniqueDeviceId, DeviceIdType::UNIQUE_DISABILITY_ID); + + DeviceId deviceId; + deviceId.networkId = networkId; + deviceId.universallyUniqueId = universallyUniqueId; + deviceId.uniqueDeviceId = uniqueDeviceId; + + DeviceInfo deviceInfo; + deviceInfo.deviceId = deviceId; + deviceInfo.deviceName = deviceName; + deviceInfo.deviceType = deviceType; + + const std::string deviceInfoKey = networkId + universallyUniqueId + uniqueDeviceId; + deviceIdMapByNetworkId_.insert(std::pair(networkId, deviceId)); + deviceIdMapByUniversallyUniqueId_.insert(std::pair(universallyUniqueId, deviceId)); + deviceIdMapByUniqueDeviceId_.insert(std::pair(uniqueDeviceId, deviceId)); + deviceInfoMap_.insert(std::pair(deviceInfoKey, deviceInfo)); +} + +void DeviceInfoRepository::DeleteDeviceInfo(const std::string &nodeId, const DeviceIdType type) +{ + std::lock_guard guard(stackLock_); + DeviceId deviceId; + if (FindDeviceIdByNodeIdLocked(nodeId, type, deviceId)) { + DeleteDeviceInfoByDeviceIdLocked(deviceId); + } +} + +void DeviceInfoRepository::DeleteDeviceInfoByDeviceIdLocked(const DeviceId deviceId) +{ + deviceIdMapByNetworkId_.erase(deviceId.networkId); + deviceIdMapByUniversallyUniqueId_.erase(deviceId.universallyUniqueId); + deviceIdMapByUniqueDeviceId_.erase(deviceId.uniqueDeviceId); + const std::string deviceInfoKey = deviceId.networkId + deviceId.universallyUniqueId + deviceId.uniqueDeviceId; + deviceInfoMap_.erase(deviceInfoKey); +} + +void DeviceInfoRepository::Clear() +{ + std::lock_guard guard(stackLock_); + deviceIdMapByNetworkId_.clear(); + deviceIdMapByUniversallyUniqueId_.clear(); + deviceIdMapByUniqueDeviceId_.clear(); + deviceInfoMap_.clear(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_executor.cpp new file mode 100644 index 000000000..4960feec7 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "remote_command_executor.h" +#include "constant_common.h" +#include "device_info_manager.h" +#include "parameter.h" +#include "singleton.h" +#include "soft_bus_channel.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandExecutor"}; +static const std::string TASK_NAME = "RemoteCommandExecutor::ProcessBufferedCommandsWithThread"; +} // namespace +RemoteCommandExecutor::RemoteCommandExecutor(const std::string &targetNodeId) + : targetNodeId_(targetNodeId), ptrChannel_(nullptr), mutex_(), commands_(), running_(false) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandExecutor()"); +} + +RemoteCommandExecutor::~RemoteCommandExecutor() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() begin"); + running_ = false; +} + +const std::shared_ptr RemoteCommandExecutor::CreateChannel(const std::string &targetNodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "CreateChannel: targetNodeId=%{public}s", targetNodeId.c_str()); + // only consider SoftBusChannel + std::shared_ptr ptrChannel = std::make_shared(targetNodeId); + if (ptrChannel == nullptr) { + ACCESSTOKEN_LOG_INFO( + LABEL, "CreateChannel: create channel failed, targetNodeId=%{public}s", targetNodeId.c_str()); + } + return ptrChannel; +} + +/* + * called by RemoteCommandExecutor, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessOneCommand(const std::shared_ptr& ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_WARN( + LABEL, "targetNodeId %{public}s, attempt to process on null command.", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, process one command start, uniqueId: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str()); + + ptrCommand->Prepare(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, process one command error, uniqueId: %{public}s, message: " + "prepare failure code %{public}d", + targetNodeId_.c_str(), + uniqueId.c_str(), + status); + return status; + } + + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + if (targetNodeId_ == localUdid) { + return ExecuteRemoteCommand(ptrCommand, false); + } + + // otherwise a remote device + CreateChannelIfNeeded(); + if (ptrChannel_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is null.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + if (ptrChannel_->BuildConnection() != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is not ready.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + + return ExecuteRemoteCommand(ptrCommand, true); +} + +/* + * called by RemoteCommandManager + */ +int RemoteCommandExecutor::AddCommand(const std::shared_ptr& ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, attempt to add an empty command.", + targetNodeId_.c_str()); + return Constant::INVALID_COMMAND; + } + + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_DEBUG( + LABEL, "targetNodeId %{public}s, add uniqueId %{public}s", targetNodeId_.c_str(), uniqueId.c_str()); + + std::unique_lock lock(mutex_); + + // make sure do not have the same command in the command buffer + for (const auto& bufferedCommand : commands_) { + if (bufferedCommand->remoteProtocol_.uniqueId == uniqueId) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::SUCCESS; + } + } + + commands_.push_back(ptrCommand); + return Constant::SUCCESS; +} + +/* + * called by RemoteCommandExecutor.ProcessCommandThread, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessBufferedCommands(bool standalone) +{ + ACCESSTOKEN_LOG_INFO( + LABEL, "begin, targetNodeId: %{public}s, standalone: %{public}d", targetNodeId_.c_str(), standalone); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, "no command, targetNodeId %{public}s", targetNodeId_.c_str()); + running_ = false; + return Constant::SUCCESS; + } + + running_ = true; + while (true) { + // interrupt + if (!running_) { + ACCESSTOKEN_LOG_INFO( + LABEL, "end with running flag == false, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::FAILURE; + } + // end + if (commands_.empty()) { + running_ = false; + ACCESSTOKEN_LOG_INFO(LABEL, "end, no command left, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + + // consume queue to execute + const std::shared_ptr bufferedCommand = commands_.front(); + int status = ProcessOneCommand(bufferedCommand); + if (status == Constant::SUCCESS) { + commands_.pop_front(); + continue; + } else if (status == Constant::FAILURE_BUT_CAN_RETRY) { + ACCESSTOKEN_LOG_WARN(LABEL, + "execute failed and wait to retry, targetNodeId: %{public}s, message: %{public}s, and will retry ", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + + // now, the retry at once will have no effective because the network problem + // so if the before the step, one command is added, and run this function + // it should also not need to restart to process the commands buffer at once. + running_ = false; + return Constant::FAILURE; + } else { + // this command failed, move on to execute next command + commands_.pop_front(); + ACCESSTOKEN_LOG_ERROR(LABEL, + "execute failed, targetNodeId: %{public}s, commandName: %{public}s, message: %{public}s", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.commandName.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + } + } +} + +/* + * called by RemoteCommandManager + */ +void RemoteCommandExecutor::ProcessBufferedCommandsWithThread() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s", targetNodeId_.c_str()); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_INFO(LABEL, "No buffered commands. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + if (running_) { + // task is running, do not need to start one more + ACCESSTOKEN_LOG_WARN(LABEL, "task busy. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + + running_ = true; + const std::function runner = std::bind(&RemoteCommandExecutor::ProcessBufferedCommands, this, true); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + bool result = handler->ProxyPostTask(runner, TASK_NAME); + if (!result) { + ACCESSTOKEN_LOG_ERROR(LABEL, "post task failed, targetNodeId: %{public}s", targetNodeId_.c_str()); + } + ACCESSTOKEN_LOG_INFO(LABEL, + "post task succeed, targetNodeId: %{public}s, taskName: %{public}s", + targetNodeId_.c_str(), + TASK_NAME.c_str()); +} + +int RemoteCommandExecutor::ExecuteRemoteCommand( + const std::shared_ptr& ptrCommand, const bool isRemote) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, remote %{public}d: start to execute", + targetNodeId_.c_str(), + uniqueId.c_str(), + isRemote); + + ptrCommand->remoteProtocol_.statusCode = Constant::STATUS_CODE_BEFORE_RPC; + + if (!isRemote) { + // Local device, play myself. + ptrCommand->Execute(); + int code = ClientProcessResult(ptrCommand); + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrCommand->remoteProtocol_.statusCode, + ptrCommand->remoteProtocol_.message.c_str()); + return code; + } + + std::string responseString = + ptrChannel_->ExecuteCommand(ptrCommand->remoteProtocol_.commandName, ptrCommand->ToJsonPayload()); + ACCESSTOKEN_LOG_INFO(LABEL, "command executed uniqueId %{public}s", uniqueId.c_str()); + if (responseString.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.", + targetNodeId_.c_str(), + uniqueId.c_str()); + // if command send failed, also try to close session + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } + return Constant::FAILURE; + } + + std::shared_ptr ptrResponseCommand = + RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson( + ptrCommand->remoteProtocol_.commandName, responseString); + if (ptrResponseCommand == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, get null response command!", targetNodeId_.c_str()); + return Constant::FAILURE; + } + int32_t result = ClientProcessResult(ptrResponseCommand); + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrResponseCommand->remoteProtocol_.statusCode, + ptrResponseCommand->remoteProtocol_.message.c_str()); + return result; +} + +void RemoteCommandExecutor::CreateChannelIfNeeded() +{ + std::unique_lock lock(mutex_); + if (ptrChannel_ != nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, channel is exist.", targetNodeId_.c_str()); + return; + } + + ptrChannel_ = CreateChannel(targetNodeId_); +} + +int RemoteCommandExecutor::ClientProcessResult(const std::shared_ptr& ptrCommand) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + if (ptrCommand->remoteProtocol_.statusCode == Constant::STATUS_CODE_BEFORE_RPC) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, status code after RPC is same as before, the remote side " + "may not " + "support this command", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::FAILURE; + } + + ptrCommand->Finish(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute failed, message: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str(), + ptrCommand->remoteProtocol_.message.c_str()); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute succeed.", + targetNodeId_.c_str(), + uniqueId.c_str()); + } + return status; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_factory.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_factory.cpp new file mode 100644 index 000000000..49f928041 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_factory.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "remote_command_factory.h" + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Security { +namespace AccessToken { +RemoteCommandFactory &RemoteCommandFactory::GetInstance() +{ + static RemoteCommandFactory instance; + return instance; +} + +std::shared_ptr RemoteCommandFactory::NewSyncRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID tokenID) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenID); +} + +std::shared_ptr RemoteCommandFactory::NewDeleteRemoteTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID tokenID) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenID); +} + +std::shared_ptr RemoteCommandFactory::NewUpdateRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenInfo); +} + +std::shared_ptr RemoteCommandFactory::NewSyncRemoteNativeTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId) +{ + return std::make_shared(srcDeviceId, dstDeviceId); +} + +std::shared_ptr RemoteCommandFactory::NewRemoteCommandFromJson( + const std::string &commandName, const std::string &commandJsonString) +{ + const std::string SYNC_HAP_COMMAND_NAME = "SyncRemoteHapTokenCommand"; + const std::string DELETE_TOKEN_COMMAND_NAME = "DeleteRemoteTokenCommand"; + const std::string UPDATE_HAP_COMMAND_NAME = "UpdateRemoteHapTokenCommand"; + const std::string SYNC_NATIVE_COMMAND_NAME = "SyncRemoteNativeTokenCommand"; + + if (commandName == SYNC_HAP_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } + if (commandName == DELETE_TOKEN_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } + if (commandName == UPDATE_HAP_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } + if (commandName == SYNC_NATIVE_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } + return nullptr; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_manager.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_manager.cpp new file mode 100644 index 000000000..c9d41f27f --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/remote_command_manager.cpp @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "remote_command_manager.h" +#include +#include "device_info_manager.h" +#include "sync_remote_native_token_command.h" +#include "remote_command_factory.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" +#include "accesstoken_kit.h" +#include "constant_common.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandManager"}; +} +RemoteCommandManager::RemoteCommandManager() : executors_(), mutex_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandManager()"); +} + +RemoteCommandManager::~RemoteCommandManager() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandManager()"); +} + +RemoteCommandManager &RemoteCommandManager::GetInstance() +{ + static RemoteCommandManager instance; + return instance; +} + +void RemoteCommandManager::Init() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Init()"); +} + +int RemoteCommandManager::AddCommand(const std::string &udid, const std::shared_ptr& command) +{ + if (udid.empty() || command == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid, or null command"); + return Constant::FAILURE; + } + std::string uniqueId = command->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, "add uniqueId"); + + std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + int result = executor->AddCommand(command); + ACCESSTOKEN_LOG_INFO(LABEL, "add command result: %{public}d ", result); + return result; +} + +void RemoteCommandManager::RemoveCommand(const std::string &udid) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "remove command"); + executors_.erase(udid); +} + +int RemoteCommandManager::ExecuteCommand(const std::string &udid, const std::shared_ptr& command) +{ + if (udid.empty() || command == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s, or null command", + ConstantCommon::EncryptDevId(udid).c_str()); + return Constant::FAILURE; + } + std::string uniqueId = command->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid: %{public}s , uniqueId: %{public}s ", + ConstantCommon::EncryptDevId(udid).c_str(), uniqueId.c_str()); + + std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + int result = executor->ProcessOneCommand(command); + ACCESSTOKEN_LOG_INFO(LABEL, "remoteCommandExecutor processOneCommand result:%{public}d ", result); + return result; +} + +int RemoteCommandManager::ProcessDeviceCommandImmediately(const std::string &udid) +{ + if (udid.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s", ConstantCommon::EncryptDevId(udid).c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid:%{public}s ", ConstantCommon::EncryptDevId(udid).c_str()); + auto executorIt = executors_.find(udid); + if (executorIt == executors_.end()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no executor found, udid:%{public}s", ConstantCommon::EncryptDevId(udid).c_str()); + return Constant::FAILURE; + } + + auto executor = executorIt->second; + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "RemoteCommandExecutor is null for udid %{public}s ", + ConstantCommon::EncryptDevId(udid).c_str()); + return Constant::FAILURE; + } + + int result = executor->ProcessBufferedCommands(); + ACCESSTOKEN_LOG_INFO(LABEL, "processBufferedCommands result: %{public}d", result); + return result; +} + +int RemoteCommandManager::Loop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "start"); + for (auto it = executors_.begin(); it != executors_.end(); it++) { + ACCESSTOKEN_LOG_INFO(LABEL, "udid:%{public}s", it->first.c_str()); + (*it).second->ProcessBufferedCommandsWithThread(); + } + return Constant::SUCCESS; +} + +/** + * caller: service connection listener + */ +void RemoteCommandManager::Clear() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "remove all remote command executors."); + + std::map> dummy; + executors_.swap(dummy); + executors_.clear(); +} + +/** + * caller: device listener + */ +int RemoteCommandManager::NotifyDeviceOnline(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_INFO(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "operation start with nodeId: %{public}s", nodeId.c_str()); + + auto executor = GetOrCreateRemoteCommandExecutor(nodeId); + std::unique_lock lock(mutex_); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + if (executor->GetChannel() == nullptr) { + auto channel = RemoteCommandExecutor::CreateChannel(nodeId); + if (channel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "create channel failed."); + return Constant::FAILURE; + } + executor->SetChannel(channel); + } + + lock.unlock(); + + std::function delayed = ([=]() { + const std::shared_ptr syncRemoteNativeTokenCommand = + RemoteCommandFactory::GetInstance().NewSyncRemoteNativeTokenCommand(ConstantCommon::GetLocalDeviceId(), + nodeId); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + nodeId, syncRemoteNativeTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s: RemoteExecutorManager executeCommand syncRemoteNativeTokenCommand failed, return %d", + __func__, resultCode); + return; + } + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return Constant::FAILURE; + } + handler->ProxyPostTask(delayed, "HandleDeviceOnline", Constant::DELAY_SYNC_TOKEN_MS); + + return Constant::SUCCESS; +} + +/** + * caller: device listener + */ +int RemoteCommandManager::NotifyDeviceOffline(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_INFO(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "operation start with nodeId: %{public}s", nodeId.c_str()); + + auto channel = GetExecutorChannel(nodeId); + if (channel != nullptr) { + channel->Release(); + } + + std::unique_lock lock(mutex_); + RemoveCommand(nodeId); + lock.unlock(); + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(nodeId, DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "get remote networkId failed"); + return Constant::FAILURE; + } + std::string uniqueDeviceId = devInfo.deviceId.uniqueDeviceId; + std::function delayed = ([=]() { + AccessTokenKit::DeleteRemoteDeviceTokens(uniqueDeviceId); + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return Constant::FAILURE; + } + handler->ProxyPostTask(delayed, "HandleDeviceOffline"); + + ACCESSTOKEN_LOG_INFO(LABEL, "complete"); + return Constant::SUCCESS; +} + +std::shared_ptr RemoteCommandManager::GetOrCreateRemoteCommandExecutor(const std::string &nodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "begin, nodeId %{public}s", nodeId.c_str()); + + std::unique_lock lock(mutex_); + auto executorIter = executors_.find(nodeId); + if (executorIter != executors_.end()) { + return executorIter->second; + } + + auto executor = std::make_shared(nodeId); + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "cannot create remote command executor, nodeId: %{public}s", nodeId.c_str()); + return nullptr; + } + + executors_.insert(std::pair>(nodeId, executor)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "executor added, nodeId: %{public}s", nodeId.c_str()); + return executor; +} + +/** + * caller: session listener(onBytesReceived), device listener(offline) + */ +std::shared_ptr RemoteCommandManager::GetExecutorChannel(const std::string &nodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "convert udid start, nodeId:%{public}s", nodeId.c_str()); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDeviceIdOrFetch(nodeId); + if (!DataValidator::IsDeviceIdValid(udid)) { + ACCESSTOKEN_LOG_WARN( + LABEL, "converted udid is invalid, nodeId:%{public}s", nodeId.c_str()); + return nullptr; + } + std::map>::iterator iter = executors_.find(udid); + if (iter == executors_.end()) { + ACCESSTOKEN_LOG_INFO(LABEL, "executor not found"); + return nullptr; + } + std::shared_ptr executor = iter->second; + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "executor is null"); + return nullptr; + } + return executor->GetChannel(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_channel.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_channel.cpp new file mode 100644 index 000000000..d4cdeb052 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_channel.cpp @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "soft_bus_channel.h" + +#include + +#include "device_info_manager.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" +#include "singleton.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusChannel"}; +} +namespace { +static const std::string REQUEST_TYPE = "request"; +static const std::string RESPONSE_TYPE = "response"; +static const std::string TASK_NAME_CLOSE_SESSION = "atm_soft_bus_channel_close_session"; +static const int32_t EXECUTE_COMMAND_TIME_OUT = 3000; +static const int32_t WAIT_SESSION_CLOSE_MILLISECONDS = 5 * 1000; +// send buf size for header +static const int RPC_TRANSFER_HEAD_BYTES_LENGTH = 1024 * 256; +// decompress buf size +static const int RPC_TRANSFER_BYTES_MAX_LENGTH = 1024 * 1024; +} // namespace +SoftBusChannel::SoftBusChannel(const std::string &deviceId) + : deviceId_(deviceId), mutex_(), callbacks_(), responseResult_(""), loadedCond_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusChannel(deviceId)"); + isDelayClosing_ = false; + session_ = Constant::INVALID_SESSION; + isSessionUsing_ = false; +} + +SoftBusChannel::~SoftBusChannel() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusChannel()"); +} + +int SoftBusChannel::BuildConnection() +{ + CancelCloseConnectionIfNeeded(); + if (session_ != Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_INFO(LABEL, "session is exist, no need open again."); + return Constant::SUCCESS; + } + + std::unique_lock lock(sessionMutex_); + if (session_ == Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_INFO(LABEL, "open session with device: %{public}s", (deviceId_.c_str())); + int session = SoftBusManager::GetInstance().OpenSession(deviceId_); + if (session == Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, "open session failed."); + return Constant::FAILURE; + } + session_ = session; + } + return Constant::SUCCESS; +} + +void SoftBusChannel::CloseConnection() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "close connection"); + std::unique_lock lock(mutex_); + if (isDelayClosing_) { + return; + } + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + auto thisPtr = shared_from_this(); + std::function delayed = ([thisPtr]() { + std::unique_lock lock(thisPtr->sessionMutex_); + if (thisPtr->isSessionUsing_) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "session is in using, cancel close session"); + } else { + SoftBusManager::GetInstance().CloseSession(thisPtr->session_); + thisPtr->session_ = Constant::INVALID_SESSION; + ACCESSTOKEN_LOG_INFO(LABEL, "close session for device: %{public}s", thisPtr->deviceId_.c_str()); + } + thisPtr->isDelayClosing_ = false; + }); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "close session after %{public}d ms", WAIT_SESSION_CLOSE_MILLISECONDS); + handler->ProxyPostTask(delayed, TASK_NAME_CLOSE_SESSION, WAIT_SESSION_CLOSE_MILLISECONDS); + + isDelayClosing_ = true; +} + +void SoftBusChannel::Release() +{ + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + handler->ProxyRemoveTask(TASK_NAME_CLOSE_SESSION); +} + +std::string SoftBusChannel::ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) +{ + if (commandName.empty() || jsonPayload.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params, commandName: %{public}s, jsonPayload: %{public}s", + commandName.c_str(), jsonPayload.c_str()); + return ""; + } + + // to use a lib like libuuid + int uuidStrLen = 37; // 32+4+1 + char uuidbuf[uuidStrLen]; + random_uuid(uuidbuf, uuidStrLen); + std::string uuid(uuidbuf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "generated message uuid: %{public}s", uuid.c_str()); + + int len = (signed)(RPC_TRANSFER_HEAD_BYTES_LENGTH + jsonPayload.length()); + unsigned char *buf = new unsigned char[len + 1]; + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", len); + return ""; + } + (void)memset_s(buf, len + 1, 0, len + 1); + int result = PrepareBytes(REQUEST_TYPE, uuid, commandName, jsonPayload, buf, len); + if (result != Constant::SUCCESS) { + delete[] buf; + return ""; + } + + std::unique_lock lock(sessionMutex_); + std::function callback = [&](const std::string &result) { + ACCESSTOKEN_LOG_INFO(LABEL, "onResponse called, data: %{public}s", result.c_str()); + responseResult_ = std::string(result); + loadedCond_.notify_all(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "onResponse called end"); + }; + callbacks_.insert(std::pair>(uuid, callback)); + + isSessionUsing_ = true; + lock.unlock(); + + int retCode = SendRequestBytes(buf, len); + delete[] buf; + + std::unique_lock lock2(sessionMutex_); + if (retCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request data failed: %{public}d ", retCode); + callbacks_.erase(uuid); + isSessionUsing_ = false; + return ""; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "wait command response"); + if (loadedCond_.wait_for(lock2, std::chrono::milliseconds(EXECUTE_COMMAND_TIME_OUT)) == std::cv_status::timeout) { + ACCESSTOKEN_LOG_WARN(LABEL, "time out to wait response."); + callbacks_.erase(uuid); + isSessionUsing_ = false; + return ""; + } + + isSessionUsing_ = false; + return responseResult_; +} + +void SoftBusChannel::HandleDataReceived(int session, const unsigned char *bytes, int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "HandleDataReceived"); +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:recieve message from softbus"); +#endif + if (session <= 0 || length <= 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params: session: %{public}d, data length: %{public}d", session, length); + return; + } + std::string receiveData = Decompress(bytes, length); + if (receiveData.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid parameter bytes"); + return; + } + std::shared_ptr message = SoftBusMessage::FromJson(receiveData); + if (message == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "invalid json string: %{public}s", receiveData.c_str()); + return; + } + if (!message->IsValid()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "invalid data, has empty field: %{public}s", receiveData.c_str()); + return; + } + + std::string type = message->GetType(); + if (REQUEST_TYPE == (type)) { + std::function delayed = ([=]() { + HandleRequest(session, message->GetId(), message->GetCommandName(), message->GetJsonPayload()); + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetRecvEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + handler->ProxyPostTask(delayed, "HandleDataReceived_HandleRequest"); + } else if (RESPONSE_TYPE == (type)) { + HandleResponse(message->GetId(), message->GetJsonPayload()); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid type: %{public}s ", type.c_str()); + } +} + +int SoftBusChannel::PrepareBytes(const std::string &type, const std::string &id, const std::string &commandName, + const std::string &jsonPayload, const unsigned char *bytes, int &bytesLength) +{ + SoftBusMessage messageEntity(type, id, commandName, jsonPayload); + std::string json = messageEntity.ToJson(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "softbus message json: %{public}s", json.c_str()); + return Compress(json, bytes, bytesLength); +} + +int SoftBusChannel::Compress(const std::string &json, const unsigned char *compressedBytes, int &compressedLength) +{ + uLong len = compressBound(json.size()); + // length will not so that long + if (compressedLength > 0 && (int) len > compressedLength) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "compress error. data length overflow, bound length: %{public}d, buffer length: %{public}d", (int) len, + compressedLength); + return Constant::FAILURE; + } + + int result = compress((Byte *) compressedBytes, &len, (unsigned char *) json.c_str(), json.size() + 1); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "compress failed! error code: %{public}d", result); + return result; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "compress complete. compress %{public}d bytes to %{public}d", compressedLength, + (int)len); + compressedLength = (signed)len; + return Constant::SUCCESS; +} + +std::string SoftBusChannel::Decompress(const unsigned char *bytes, const int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "input length: %{public}d", length); + uLong len = RPC_TRANSFER_BYTES_MAX_LENGTH; + unsigned char *buf = new unsigned char[len + 1]; + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory!"); + return ""; + } + (void)memset_s(buf, len + 1, 0, len + 1); + int result = uncompress(buf, &len, (unsigned char *) bytes, length); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "uncompress failed, error code: %{public}d, bound length: %{public}d, buffer length: %{public}d", result, + (int)len, length); + delete[] buf; + return ""; + } + buf[len] = '\0'; + std::string str(reinterpret_cast(buf)); + delete[] buf; + ACCESSTOKEN_LOG_DEBUG(LABEL, "done, output: %{public}s", str.c_str()); + return str; +} + +int SoftBusChannel::SendRequestBytes(const unsigned char *bytes, const int bytesLength) +{ + if (bytesLength == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "bytes data is invalid."); + return Constant::FAILURE; + } + + std::unique_lock lock(sessionMutex_); + if (CheckSessionMayReopenLocked() != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "session invalid and reopen failed!"); + return Constant::FAILURE; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "send len (after compress len)= %{public}d", bytesLength); +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:send command to softbus"); +#endif + int result = ::SendBytes(session_, bytes, bytesLength); + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to send! result= %{public}d", result); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "send successfully."); + return Constant::SUCCESS; +} + +int SoftBusChannel::CheckSessionMayReopenLocked() +{ + // when session is opened, we got a valid sessionid, when session closed, we will reset sessionid. + if (IsSessionAvailable()) { + return Constant::SUCCESS; + } + int session = SoftBusManager::GetInstance().OpenSession(deviceId_); + if (session != Constant::INVALID_SESSION) { + session_ = session; + return Constant::SUCCESS; + } + return Constant::FAILURE; +} + +bool SoftBusChannel::IsSessionAvailable() +{ + return session_ > Constant::INVALID_SESSION; +} + +void SoftBusChannel::CancelCloseConnectionIfNeeded() +{ + std::unique_lock lock(mutex_); + if (!isDelayClosing_) { + return; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "cancel close connection"); + + Release(); + isDelayClosing_ = false; +} + +void SoftBusChannel::HandleRequest(int session, const std::string &id, const std::string &commandName, + const std::string &jsonPayload) +{ + std::shared_ptr command = + RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson(commandName, jsonPayload); + if (command == nullptr) { + // send result back directly + ACCESSTOKEN_LOG_WARN(LABEL, "command %{public}s cannot get from json %{public}s", commandName.c_str(), + jsonPayload.c_str()); + + int sendlen = (signed)(RPC_TRANSFER_HEAD_BYTES_LENGTH + jsonPayload.length()); + unsigned char *sendbuf = new unsigned char[sendlen + 1]; + if (sendbuf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", sendlen); + return; + } + (void)memset_s(sendbuf, sendlen + 1, 0, sendlen + 1); + int sendResult = PrepareBytes(RESPONSE_TYPE, id, commandName, jsonPayload, sendbuf, sendlen); + if (sendResult != Constant::SUCCESS) { + delete[] sendbuf; + return; + } + int sendResultCode = SendResponseBytes(session, sendbuf, sendlen); + delete[] sendbuf; + ACCESSTOKEN_LOG_DEBUG(LABEL, "send response result= %{public}d ", sendResultCode); + return; + } + + // execute command + command->Execute(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "command uniqueId: %{public}s, finish with status: %{public}d, message: %{public}s", + command->remoteProtocol_.uniqueId.c_str(), command->remoteProtocol_.statusCode, + command->remoteProtocol_.message.c_str()); + + // send result back + std::string resultJsonPayload = command->ToJsonPayload(); + int len = (signed)(RPC_TRANSFER_HEAD_BYTES_LENGTH + resultJsonPayload.length()); + unsigned char *buf = new unsigned char[len + 1]; + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", len); + return; + } + (void)memset_s(buf, len + 1, 0, len + 1); + int result = PrepareBytes(RESPONSE_TYPE, id, commandName, resultJsonPayload, buf, len); + if (result != Constant::SUCCESS) { + delete[] buf; + return; + } + int retCode = SendResponseBytes(session, buf, len); + delete[] buf; + ACCESSTOKEN_LOG_DEBUG(LABEL, "send response result= %{public}d", retCode); +} + +void SoftBusChannel::HandleResponse(const std::string &id, const std::string &jsonPayload) +{ + std::unique_lock lock(sessionMutex_); + auto callback = callbacks_.find(id); + if (callback != callbacks_.end()) { + (callback->second)(jsonPayload); + callbacks_.erase(callback); + } +} + +int SoftBusChannel::SendResponseBytes(int session, const unsigned char *bytes, const int bytesLength) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "send len (after compress len)= %{public}d", bytesLength); + int result = ::SendBytes(session, bytes, bytesLength); + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to send! result= %{public}d", result); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "send successfully."); + return Constant::SUCCESS; +} + +std::shared_ptr SoftBusMessage::FromJson(const std::string &jsonString) +{ + nlohmann::json json; + if (!json.accept(jsonString)) { + return nullptr; + } + json = json.parse(jsonString, nullptr, false); + if (json.is_discarded() || (!json.is_object())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to parse jsonString"); + return nullptr; + } + + std::string type; + std::string id; + std::string commandName; + std::string jsonPayload; + if (json.find("type") != json.end() && json.at("type").is_string()) { + json.at("type").get_to(type); + } + if (json.find("id") != json.end() && json.at("id").is_string()) { + json.at("id").get_to(id); + } + if (json.find("commandName") != json.end() && json.at("commandName").is_string()) { + json.at("commandName").get_to(commandName); + } + if (json.find("jsonPayload") != json.end() && json.at("jsonPayload").is_string()) { + json.at("jsonPayload").get_to(jsonPayload); + } + if (type.empty() || id.empty() || commandName.empty() || jsonPayload.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to get json string(json format error)"); + return nullptr; + } + std::shared_ptr message = std::make_shared(type, id, commandName, jsonPayload); + return message; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp new file mode 100644 index 000000000..5b2581ec6 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "soft_bus_device_connection_listener.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" +#include "device_info_manager.h" +#include "softbus_bus_center.h" +#include "constant_common.h" +#include "device_manager.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +using OHOS::DistributedHardware::DeviceStateCallback; +using OHOS::DistributedHardware::DmDeviceInfo; +using OHOS::DistributedHardware::DmInitCallback; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusDeviceConnectionListener"}; +} + +const std::string ACCESSTOKEN_PACKAGE_NAME = "ohos.security.distributed_access_token"; + +SoftBusDeviceConnectionListener::SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusDeviceConnectionListener()"); +} +SoftBusDeviceConnectionListener::~SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusDeviceConnectionListener()"); +} + +void SoftBusDeviceConnectionListener::OnDeviceOnline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(networkId); + std::string udid = SoftBusManager::GetInstance().GetUniqueDeviceIdByNodeId(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + ConstantCommon::EncryptDevId(udid).c_str()); + + if (uuid != "" && udid != "") { + DeviceInfoManager::GetInstance().AddDeviceInfo( + networkId, uuid, udid, info.deviceName, std::to_string(info.deviceTypeId)); + RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, online failed."); + } + // no need to load local permissions by now. +} + +void SoftBusDeviceConnectionListener::OnDeviceOffline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = DeviceInfoManager::GetInstance().ConvertToUniversallyUniqueIdOrFetch(networkId); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDeviceIdOrFetch(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + ConstantCommon::EncryptDevId(udid).c_str()); + + if (uuid != "" && udid != "") { + RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid); + RemoteCommandManager::GetInstance().NotifyDeviceOffline(udid); + DeviceInfoManager::GetInstance().RemoveRemoteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + + std::string packageName = ACCESSTOKEN_PACKAGE_NAME; + std::string extra = ""; + std::vector deviceList; + + int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, + extra, deviceList); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetTrustedDeviceList error, result: %{public}d", ret); + return; + } + + if (deviceList.empty()) { + ACCESSTOKEN_LOG_INFO(LABEL, "there is no remote decice online, exit tokensync process"); + + exit(0); + } + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, offline failed."); + } +} + +void SoftBusDeviceConnectionListener::OnDeviceReady(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} + +void SoftBusDeviceConnectionListener::OnDeviceChanged(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_manager.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_manager.cpp new file mode 100644 index 000000000..7e736fb9b --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_manager.cpp @@ -0,0 +1,410 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "soft_bus_manager.h" + +#include +#include "constant_common.h" +#include "device_info_manager.h" +#include "parameter.h" +#include "softbus_bus_center.h" +#include "dm_device_info.h" +#include "remote_command_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusManager"}; +} +namespace { +static const std::string SESSION_GROUP_ID = "atm_dsoftbus_session_group_id"; +static const SessionAttribute SESSION_ATTR = {.dataType = TYPE_BYTES}; + +static const int REASON_EXIST = -3; +static const int OPENSESSION_RETRY_TIMES = 10 * 3; +static const int OPENSESSION_RETRY_INTERVAL_MS = 100; +static const int UDID_MAX_LENGTH = 128; // udid/uuid max length +} // namespace + +const std::string SoftBusManager::TOKEN_SYNC_PACKAGE_NAME = "ohos.security.distributed_access_token"; +const std::string SoftBusManager::SESSION_NAME = "ohos.security.atm_channel"; + +SoftBusManager::SoftBusManager() : isSoftBusServiceBindSuccess_(false), inited_(false), mutex_(), fulfillMutex_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusManager()"); +} + +SoftBusManager::~SoftBusManager() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusManager()"); +} + +SoftBusManager &SoftBusManager::GetInstance() +{ + static SoftBusManager instance; + return instance; +} + +int SoftBusManager::AddTrustedDeviceInfo() +{ + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + std::string extra = ""; + std::vector deviceList; + + int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(packageName, + extra, deviceList); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "AddTrustedDeviceInfo: GetTrustedDeviceList error, result: %{public}d", ret); + return Constant::FAILURE; + } + + for (const DistributedHardware::DmDeviceInfo& device : deviceList) { + std::string uuid = GetUuidByNodeId(device.networkId); + std::string udid = GetUdidByNodeId(device.networkId); + if (uuid.empty() || udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid = %{public}s, udid = %{public}s, uuid or udid is empty, abort.", + uuid.c_str(), ConstantCommon::EncryptDevId(udid).c_str()); + continue; + } + + DeviceInfoManager::GetInstance().AddDeviceInfo(device.networkId, uuid, udid, device.deviceName, + std::to_string(device.deviceTypeId)); + RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); + } + + return Constant::SUCCESS; +} + +int SoftBusManager::DeviceInit() +{ + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + std::shared_ptr ptrDmInitCallback = std::make_shared(); + + int ret = DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(packageName, ptrDmInitCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret); + return ret; + } + + ret = AddTrustedDeviceInfo(); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: AddTrustedDeviceInfo error, result: %{public}d", ret); + return ret; + } + + std::string extra = ""; + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + ret = DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(packageName, extra, + ptrDeviceStateCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: RegisterDevStateCallback error, result: %{public}d", ret); + return ret; + } + + return ERR_OK; +} + +int SoftBusManager::SessionInit() +{ + // register session listener + ISessionListener sessionListener; + sessionListener.OnSessionOpened = SoftBusSessionListener::OnSessionOpened; + sessionListener.OnSessionClosed = SoftBusSessionListener::OnSessionClosed; + sessionListener.OnBytesReceived = SoftBusSessionListener::OnBytesReceived; + sessionListener.OnMessageReceived = SoftBusSessionListener::OnMessageReceived; + + int ret = ::CreateSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str(), &sessionListener); + ACCESSTOKEN_LOG_INFO(LABEL, "Initialize: createSessionServer, result: %{public}d", ret); + // REASON_EXIST + if ((ret != Constant::SUCCESS) && (ret != REASON_EXIST)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: CreateSessionServer error, result: %{public}d", ret); + return ret; + } + + return ERR_OK; +} + +void SoftBusManager::Initialize() +{ + bool inited = false; + // cas failed means already inited. + if (!inited_.compare_exchange_strong(inited, true)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "already initialized, skip"); + return; + } + + std::function runner = [&]() { + auto sleepTime = std::chrono::milliseconds(1000); + while (1) { + std::unique_lock lock(mutex_); + + int ret = DeviceInit(); + if (ret != ERR_OK) { + std::this_thread::sleep_for(sleepTime); + continue; + } + + ret = SessionInit(); + if (ret != ERR_OK) { + std::this_thread::sleep_for(sleepTime); + continue; + } + + isSoftBusServiceBindSuccess_ = true; + this->FulfillLocalDeviceInfo(); + return; + } + }; + + std::thread initThread(runner); + initThread.detach(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Initialize thread started"); +} + +void SoftBusManager::Destroy() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, init: %{public}d, isSoftBusServiceBindSuccess: %{public}d", inited_.load(), + isSoftBusServiceBindSuccess_); + + if (!inited_.load()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); + return; + } + + std::unique_lock lock(mutex_); + if (!inited_.load()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); + return; + } + + if (isSoftBusServiceBindSuccess_) { + int32_t ret = ::RemoveSessionServer(TOKEN_SYNC_PACKAGE_NAME.c_str(), SESSION_NAME.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, RemoveSessionServer: %{public}d", ret); + isSoftBusServiceBindSuccess_ = false; + } + + std::string packageName = TOKEN_SYNC_PACKAGE_NAME; + int ret = DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnRegisterDevStateCallback failed, code: %{public}d", ret); + } + ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret); + } + + inited_.store(false); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, done"); +} + +int32_t SoftBusManager::OpenSession(const std::string &deviceId) +{ +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session"); +#endif + + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(deviceId, DeviceIdType::UNKNOWN, info); + if (!result) { + ACCESSTOKEN_LOG_WARN(LABEL, "device info notfound for deviceId %{public}s", + ConstantCommon::EncryptDevId(deviceId).c_str()); + return Constant::FAILURE; + } + std::string networkId = info.deviceId.networkId; + ACCESSTOKEN_LOG_INFO(LABEL, "openSession, networkId: %{public}s", networkId.c_str()); + + // async open session, should waitting for OnSessionOpened event. + int sessionId = ::OpenSession(SESSION_NAME.c_str(), SESSION_NAME.c_str(), networkId.c_str(), + SESSION_GROUP_ID.c_str(), &SESSION_ATTR); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "async open session"); + + // wait session opening + int retryTimes = 0; + int logSpan = 10; + auto sleepTime = std::chrono::milliseconds(OPENSESSION_RETRY_INTERVAL_MS); + while (retryTimes++ < OPENSESSION_RETRY_TIMES) { + if (SoftBusSessionListener::GetSessionState(sessionId) < 0) { + std::this_thread::sleep_for(sleepTime); + if (retryTimes % logSpan == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "openSession, waitting for: %{public}d ms", + retryTimes * OPENSESSION_RETRY_INTERVAL_MS); + } + continue; + } + break; + } +#ifdef DEBUG_API_PERFORMANCE + ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start open session success"); +#endif + int64_t state = SoftBusSessionListener::GetSessionState(sessionId); + if (state < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "openSession, timeout, session: %{public}" PRId64, state); + return Constant::FAILURE; + } + + SoftBusSessionListener::DeleteSessionIdFromMap(sessionId); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "openSession, succeed, session: %{public}" PRId64, state); + return sessionId; +} + +int SoftBusManager::CloseSession(int sessionId) +{ + if (sessionId < 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession: session is invalid"); + return Constant::FAILURE; + } + + ::CloseSession(sessionId); + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession "); + return Constant::SUCCESS; +} + +std::string SoftBusManager::GetUniversallyUniqueIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + + std::string uuid = GetUuidByNodeId(nodeId); + if (uuid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string [%{public}s]", uuid.c_str()); + return ""; + } + + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(uuid, DeviceIdType::UNIVERSALLY_UNIQUE_ID, info); + if (!result) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "local device info not found for uuid %{public}s", uuid.c_str()); + } else { + std::string dimUuid = info.deviceId.universallyUniqueId; + if (uuid == dimUuid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + } + + return uuid; +} + +std::string SoftBusManager::GetUniqueDeviceIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + std::string udid = GetUdidByNodeId(nodeId); + if (udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string: %{public}s", + ConstantCommon::EncryptDevId(udid).c_str()); + return ""; + } + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + if (udid == localUdid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + return udid; +} + +std::string SoftBusManager::GetUuidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), + NodeDeviceInfoKey::NODE_KEY_UUID, info, UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + delete[] info; + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, return code: %{public}d", ret); + return ""; + } + std::string uuid(reinterpret_cast(info)); + delete[] info; + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished. nodeId(in): %{public}s, uuid: %{public}s", nodeId.c_str(), + uuid.c_str()); + return uuid; +} + +std::string SoftBusManager::GetUdidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = new uint8_t[UDID_MAX_LENGTH + 1]; + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + (void)memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), nodeId.c_str(), + NodeDeviceInfoKey::NODE_KEY_UDID, info, UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + delete[] info; + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret); + return ""; + } + std::string udid(reinterpret_cast(info)); + delete[] info; + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished: nodeId(in): %{public}s", nodeId.c_str()); + return udid; +} + +int SoftBusManager::FulfillLocalDeviceInfo() +{ + // repeated task will just skip + if (!fulfillMutex_.try_lock()) { + ACCESSTOKEN_LOG_INFO(LABEL, "FulfillLocalDeviceInfo already running, skip."); + return Constant::SUCCESS; + } + + NodeBasicInfo info; + int32_t ret = ::GetLocalNodeDeviceInfo(TOKEN_SYNC_PACKAGE_NAME.c_str(), &info); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetLocalNodeDeviceInfo error"); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished, networkId:%{public}s, name:%{public}s, type:%{public}d", + info.networkId, info.deviceName, info.deviceTypeId); + + std::string uuid = GetUuidByNodeId(info.networkId); + std::string udid = GetUdidByNodeId(info.networkId); + if (uuid.empty() || udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FulfillLocalDeviceInfo: uuid or udid is empty, abort."); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + DeviceInfoManager::GetInstance().AddDeviceInfo(info.networkId, uuid, udid, info.deviceName, + std::to_string(info.deviceTypeId)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddDeviceInfo finished, networkId:%{public}s", + info.networkId); + + fulfillMutex_.unlock(); + return Constant::SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp new file mode 100644 index 000000000..fb8829eca --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "soft_bus_session_listener.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusSessionListener"}; +} +namespace { +// Indicates the pointer to the session name, which is the unique ID of the session server. The value cannot be empty +// and can contain a maximum of 64 characters. +static const int32_t SESSION_NAME_MAXLENGTH = 64; +static const int32_t SESSION_ACCEPTED = 0; +static const int32_t SESSION_REFUSED = -1; +} // namespace + +std::mutex SoftBusSessionListener::g_SessionMutex_; +std::map SoftBusSessionListener::g_SessionOpenedMap_; + +int32_t SoftBusSessionListener::OnSessionOpened(int32_t session, int32_t result) +{ + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, result: %{public}d", result); + return SESSION_REFUSED; + } + + int32_t len = SESSION_NAME_MAXLENGTH + 1; + char contents[len]; + int32_t resultCode = ::GetPeerSessionName(session, contents, len); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, GetPeerSessionName failed, result: %{public}d", resultCode); + return SESSION_REFUSED; + } + std::string peerSessionName(contents); + if (SoftBusManager::SESSION_NAME != peerSessionName) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, unknown session name."); + return SESSION_REFUSED; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "OnSessionOpened, id = %{public}d", session); + + // store session state: opening + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(session); + if (iter == g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.insert(std::pair(session, (int64_t) 1)); + } else { + iter->second = iter->second + 1; + } + + return SESSION_ACCEPTED; +} + +void SoftBusSessionListener::OnSessionClosed(int32_t session) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnSessionClosed"); + + // clear session state + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(session); + if (iter != g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.erase(iter); + } +} + +void SoftBusSessionListener::OnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + (void)data; + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnMessageReceived: data length = %{public}u", dataLen); +} + +void SoftBusSessionListener::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + if ((sessionId == Constant::INVALID_SESSION) || (dataLen == 0) || + (dataLen > MAX_ONBYTES_RECEIVED_DATA_LEN) || (data == nullptr)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "params invalid, data length: %{public}u", dataLen); + return; + } + + int32_t len = SESSION_NAME_MAXLENGTH + 1; + char contents[len]; + int32_t resultCode = ::GetPeerDeviceId(sessionId, contents, len); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetPeerDeviceId, failed, result: %{public}d", resultCode); + return; + } + std::string networkId(contents); + ACCESSTOKEN_LOG_INFO(LABEL, "networkId = %{public}s, data length = %{public}u", contents, dataLen); + auto channel = RemoteCommandManager::GetInstance().GetExecutorChannel(networkId); + if (channel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetExecutorChannel, failed, networkId: %{public}s", contents); + return; + } + channel->HandleDataReceived(sessionId, (unsigned char *) data, dataLen); +} + +int64_t SoftBusSessionListener::GetSessionState(int32_t sessionId) +{ + // get session state + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(sessionId); + if (iter == g_SessionOpenedMap_.end()) { + return STATE_NOTFOUND; + } + return iter->second; +} + +void SoftBusSessionListener::DeleteSessionIdFromMap(int32_t sessionID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "DeleteSessionIdFromMap"); + // delete sessionId in map + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(sessionID); + if (iter != g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.erase(iter); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_event_handler.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_event_handler.cpp new file mode 100644 index 000000000..e98947ddd --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_event_handler.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_event_handler.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncEventHandler"}; +} +TokenSyncEventHandler::TokenSyncEventHandler( + const std::shared_ptr& runner) + : AppExecFwk::EventHandler(runner) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "enter"); +} +TokenSyncEventHandler::~TokenSyncEventHandler() = default; + +bool TokenSyncEventHandler::ProxyPostTask(const Callback &callback, int64_t delayTime) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "PostTask without name"); + return AppExecFwk::EventHandler::PostTask(callback, delayTime); +} + +bool TokenSyncEventHandler::ProxyPostTask( + const Callback &callback, const std::string &name, int64_t delayTime) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "PostTask with name"); + return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); +} + +void TokenSyncEventHandler::ProxyRemoveTask(const std::string &name) +{ + AppExecFwk::EventHandler::RemoveTask(name); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_service.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_service.cpp new file mode 100644 index 000000000..87b44e760 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_service.cpp @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_manager_service.h" + +#include + +#include "accesstoken_log.h" +#include "constant_common.h" +#include "device_info_repository.h" +#include "device_info.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerService"}; +} + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +TokenSyncManagerService::TokenSyncManagerService() + : SystemAbility(SA_ID_TOKENSYNC_MANAGER_SERVICE, false), state_(ServiceRunningState::STATE_NOT_START) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService()"); +} + +TokenSyncManagerService::~TokenSyncManagerService() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "~TokenSyncManagerService()"); +} + +void TokenSyncManagerService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService has already started!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "TokenSyncManagerService is starting"); + if (!Initialize()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to publish service!"); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Congratulations, TokenSyncManagerService start successfully!"); +} + +void TokenSyncManagerService::OnStop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "stop service"); + state_ = ServiceRunningState::STATE_NOT_START; + SoftBusManager::GetInstance().Destroy(); +} + +std::shared_ptr TokenSyncManagerService::GetSendEventHandler() const +{ + return sendHandler_; +} + +std::shared_ptr TokenSyncManagerService::GetRecvEventHandler() const +{ + return recvHandler_; +} + +int TokenSyncManagerService::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || tokenID == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "Params is wrong."); + return RET_FAILED; + } + DeviceInfo devInfo; + bool result = DeviceInfoRepository::GetInstance().FindDeviceInfo(deviceID, DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "FindDeviceInfo failed"); + return Constant::FAILURE; + } + std::string udid = devInfo.deviceId.uniqueDeviceId; + const std::shared_ptr syncRemoteHapTokenCommand = + RemoteCommandFactory::GetInstance().NewSyncRemoteHapTokenCommand(ConstantCommon::GetLocalDeviceId(), + deviceID, tokenID); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand(udid, syncRemoteHapTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand SyncRemoteHapTokenCommand failed, return %{public}d", resultCode); + return resultCode; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); + return RET_SUCCESS; +} + +int TokenSyncManagerService::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + if (tokenID == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "Params is wrong, token id is invalid."); + return RET_FAILED; + } + + std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + for (const DeviceInfo& device : devices) { + if (device.deviceId.uniqueDeviceId == localUdid) { + ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); + continue; + } + const std::shared_ptr deleteRemoteTokenCommand = + RemoteCommandFactory::GetInstance().NewDeleteRemoteTokenCommand(ConstantCommon::GetLocalDeviceId(), + device.deviceId.uniqueDeviceId, tokenID); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + device.deviceId.uniqueDeviceId, deleteRemoteTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand DeleteRemoteTokenCommand failed, return %{public}d", resultCode); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); + } + return RET_SUCCESS; +} + +int TokenSyncManagerService::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + std::string localUdid = ConstantCommon::GetLocalDeviceId(); + for (const DeviceInfo& device : devices) { + if (device.deviceId.uniqueDeviceId == localUdid) { + ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); + continue; + } + + const std::shared_ptr updateRemoteHapTokenCommand = + RemoteCommandFactory::GetInstance().NewUpdateRemoteHapTokenCommand(ConstantCommon::GetLocalDeviceId(), + device.deviceId.uniqueDeviceId, tokenInfo); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + device.deviceId.uniqueDeviceId, updateRemoteHapTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand updateRemoteHapTokenCommand failed, return %{public}d", + resultCode); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %{public}d", resultCode); + } + + return RET_SUCCESS; +} + +bool TokenSyncManagerService::Initialize() +{ + sendRunner_ = AppExecFwk::EventRunner::Create(true); + if (!sendRunner_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to create a sendRunner."); + return false; + } + + sendHandler_ = std::make_shared(sendRunner_); + if (!sendHandler_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "sendHandler_ is nullptr."); + return false; + } + + recvRunner_ = AppExecFwk::EventRunner::Create(true); + if (!recvRunner_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to create a recvRunner."); + return false; + } + + recvHandler_ = std::make_shared(recvRunner_); + if (!recvHandler_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "recvHandler_ is nullptr."); + return false; + } + + SoftBusManager::GetInstance().Initialize(); + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp new file mode 100644 index 000000000..727b2f6c2 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_sync_manager_stub.h" + +#include "accesstoken_log.h" +#include "hap_token_info_for_sync_parcel.h" +#include "ipc_skeleton.h" +#include "native_token_info_for_sync_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncManagerStub"}; +} + +int32_t TokenSyncManagerStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, code: %{public}d", __func__, code); + std::u16string descriptor = data.ReadInterfaceToken(); + if (descriptor != ITokenSyncManager::GetDescriptor()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str()); + return -1; + } + switch (code) { + case static_cast(ITokenSyncManager::InterfaceCode::GET_REMOTE_HAP_TOKEN_INFO): + GetRemoteHapTokenInfoInner(data, reply); + break; + case static_cast(ITokenSyncManager::InterfaceCode::DELETE_REMOTE_HAP_TOKEN_INFO): + DeleteRemoteHapTokenInfoInner(data, reply); + break; + case static_cast(ITokenSyncManager::InterfaceCode::UPDATE_REMOTE_HAP_TOKEN_INFO): + UpdateRemoteHapTokenInfoInner(data, reply); + break; + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return NO_ERROR; +} + +void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + + HapTokenInfoForSync tokenInfo; + int result = this->GetRemoteHapTokenInfo(deviceID, tokenID); + reply.WriteInt32(result); +} + +void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + int result = this->DeleteRemoteHapTokenInfo(tokenID); + reply.WriteInt32(result); +} + +void TokenSyncManagerStub::UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + sptr tokenInfoParcelPtr = data.ReadParcelable(); + int result = RET_FAILED; + if (tokenInfoParcelPtr != nullptr) { + result = this->UpdateRemoteHapTokenInfo(tokenInfoParcelPtr->hapTokenInfoForSyncParams); + } + reply.WriteInt32(result); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/mock_parameter.h b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/mock_parameter.h new file mode 100644 index 000000000..969e19745 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/mock_parameter.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STARTUP_SYSPARAM_PARAMETER_API_H +#define STARTUP_SYSPARAM_PARAMETER_API_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int GetDevUdid(char *udid, int size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_SYSPARAM_PARAMETER_API_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/session.h b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/session.h new file mode 100644 index 000000000..a0b9d5d04 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/include/session.h @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Softbus + * @{ + * + * @brief Provides high-speed, secure communication between devices. + * + * This module implements unified distributed communication capability management between + * nearby devices, and provides link-independent device discovery and transmission interfaces + * to support service publishing and data transmission. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file session.h + * + * @brief Declares unified data transmission interfaces. + * + * This file provides data transmission capabilities, including creating and removing a session server, + * opening and closing sessions, receiving data, and querying basic session information. \n + * After multiple nearby devices are discovered and networked, these interfaces can be used to + * transmit data across devices. \n + * + * @since 1.0 + * @version 1.0 + */ +#ifndef SESSION_H +#define SESSION_H + +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +/** + * @brief bussiness type of session + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + TYPE_MESSAGE = 1, + TYPE_BYTES, + TYPE_FILE, + TYPE_STREAM, + TYPE_BUTT, +} SessionType; + +typedef enum { + INVALID = -1, + /* + * Send any segment of a frame each time. + */ + RAW_STREAM, + /* + * Send a whole video frame each time. + */ + COMMON_VIDEO_STREAM, + /* + * Send a whole audio frame each time. + */ + COMMON_AUDIO_STREAM, + /* + * Slice frame mode. + */ + VIDEO_SLICE_STREAM, +} StreamType; + +typedef enum { + LINK_TYPE_WIFI_WLAN_5G = 1, + LINK_TYPE_WIFI_WLAN_2G = 2, + LINK_TYPE_WIFI_P2P = 3, + LINK_TYPE_BR = 4, + LINK_TYPE_MAX = 4, +} LinkType; + +/** + * @brief session attribute. + * + * control the attribute of session。 + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** @brief dataType{@link SessionType} */ + int dataType; + int linkTypeNum; + LinkType linkType[LINK_TYPE_MAX]; + union { + struct StreamAttr { + int streamType; + } streamAttr; + } attr; +} SessionAttribute; + +typedef struct { + char *buf; + int bufLen; +} StreamData; + +typedef struct { + int type; + int64_t value; +} TV; + +typedef struct { + int frameType; + int64_t timeStamp; + int seqNum; + int seqSubNum; + int level; + int bitMap; + int tvCount; + TV *tvList; +} FrameInfo; + +/** + * @brief Defines session callbacks. + * + * When a session is opened or closed, or there is data to process, the related callback is invoked. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** + * @brief Called when a session is opened. + * + * This function can be used to verify the session or initialize resources related to the session. + * + * @param sessionId Indicates the session ID. + * @param result 0 if the session is opened successfully, returns an error code otherwise. + * @return Returns 0 if the session connection is accepted; returns a non-zero value + * otherwise (you do not need to call {@link CloseSession} to close the session). + * @since 1.0 + * @version 1.0 + */ + int (*OnSessionOpened)(int sessionId, int result); + + /** + * @brief Called when a session is closed. + * + * This function can be used to release resources related to the session. + * You do not need to call {@link CloseSession}. + * + * @param sessionId Indicates the session ID. + * @since 1.0 + * @version 1.0 + */ + void (*OnSessionClosed)(int sessionId); + + /** + * @brief Called when data is received. + * + * This function is used to notify that data is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data received. + * @param dataLen Indicates the length of the data received. + * @since 1.0 + * @version 1.0 + */ + void (*OnBytesReceived)(int sessionId, const void *data, unsigned int dataLen); + + /** + * @brief Called when message is received. + * + * This function is used to notify that message is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data received. + * @param dataLen Indicates the length of the message received. + * @since 1.0 + * @version 1.0 + */ + void (*OnMessageReceived)(int sessionId, const void *data, unsigned int dataLen); + + void (*OnStreamReceived)(int sessionId, const StreamData *data, const StreamData *ext, const FrameInfo *param); +} ISessionListener; + +typedef struct { + int (*OnReceiveFileStarted)(int sessionId, const char *files, int fileCnt); + int (*OnReceiveFileProcess)(int sessionId, const char *firstFile, uint64_t bytesUpload, uint64_t bytesTotal); + void (*OnReceiveFileFinished)(int sessionId, const char *files, int fileCnt); + void (*OnFileTransError)(int sessionId); +} IFileReceiveListener; + +typedef struct { + int (*OnSendFileProcess)(int sessionId, uint64_t bytesUpload, uint64_t bytesTotal); + int (*OnSendFileFinished)(int sessionId, const char *firstFile); + void (*OnFileTransError)(int sessionId); +} IFileSendListener; + +/** + * @brief Creates a session server based on a package name and session name. + * + * A maximum of 18 session servers can be created. + * + * @param pkgName Indicates the pointer to the package name, which can be used to check whether the + * session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name, which is the unique ID of the session server. + * The value cannot be empty and can contain a maximum of 64 characters. + * @param listener Indicates the pointer to the session callback structure, which cannot be empty. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @see RemoveSessionServer + * @since 1.0 + * @version 1.0 + */ +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener); + +/** + * @brief Removes a session server based on a package name and session name. + * + * @param pkgName Indicates the pointer to the name of the registered package, which can be used to check + * whether the session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name. The value cannot be empty and can contain + * a maximum of 64 characters. + * @return Returns 0 if the operation is successful, returns -1 otherwise. + * @see CreateSessionServer + * @since 1.0 + * @version 1.0 + */ +int RemoveSessionServer(const char *pkgName, const char *sessionName); + +/** + * @brief Initiate a session open request, which is an asynchronous process. + * + * The session connection is opened based on the service name to trigger the first packet interaction process. + * According to the {@link OnSessionOpened} Notify the user whether the session is successfully opened. + * Data can be transmitted only after the session is successfully opened. + * + * @param mySessionName local session name. + * @param peerSessionName remote session name. + * @param peerDeviceId remote device id. + * @param groupId group id. + * @param attr session attribute {@link SessionAttribute}. + * @return return sessionId if the session is opened successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, + const SessionAttribute *attr); + +/** + * @brief Closes a connected session based on a session ID. + * + * @param sessionId Indicates the session ID. + * @return no return value. + * @since 1.0 + * @version 1.0 + */ +void CloseSession(int sessionId); + +/** + * @brief Sends data based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data to send, which cannot be NULL. + * @param len Indicates the length of the data to send. The maximum length cannot exceed 984 characters. + * @return Returns 0 if the function is called successfully; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendBytes(int sessionId, const void *data, unsigned int len); + +/** + * @brief Sends message based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data to send, which cannot be NULL. + * @param len Indicates the length of the message to send. + * @return Returns 0 if the function is called successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendMessage(int sessionId, const void *data, unsigned int len); + +int SendStream(int sessionId, const StreamData *data, const StreamData *ext, const FrameInfo *param); + +/** + * @brief Obtains the session name registered by the local device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetMySessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the session name registered by the peer device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the peer device ID based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param devId Indicates the pointer to the buffer for storing the device ID. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len); + +int GetSessionSide(int sessionId); + +int SetFileReceiveListener(const char *pkgName, const char *sessionName, const IFileReceiveListener *recvListener, + const char *rootDir); + +int SetFileSendListener(const char *pkgName, const char *sessionName, const IFileSendListener *sendListener); + +int SendFile(int sessionId, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); + +void DecompressMock(const unsigned char *bytes, const int length); + + +#ifdef __cplusplus +} + +void CompressMock(const std::string &json, const unsigned char *compressedBytes, int &compressedLength); +std::string GetUuidMock(); +bool GetSendMessFlagMock(); +void ResetSendMessFlagMock(); + +#endif +#endif // SESSION_H diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/constant_mock.cpp b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/constant_mock.cpp new file mode 100644 index 000000000..fef282afc --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/constant_mock.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "constant_common.h" +#include "constant.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static const std::string REPLACE_TARGET = "****"; +} // namespace +const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; +const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; +std::string ConstantCommon::EncryptDevId(std::string deviceId) +{ + std::string result = deviceId; + if (deviceId.size() > MINDEVICEIDLEN) { + result.replace(ENCRYPTBEGIN + ENCRYPTLEN, deviceId.size() - MINDEVICEIDLEN, REPLACE_TARGET); + } else { + result.replace(ENCRYPTBEGIN, deviceId.size(), REPLACE_TARGET); + } + return result; +} + +std::string ConstantCommon::GetLocalDeviceId() +{ + return "local:udid-001"; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/mock_parameter.c b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/mock_parameter.c new file mode 100644 index 000000000..98483045a --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/mock_parameter.c @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mock_parameter.h" +#include + +int GetDevUdid(char *udid, int size) +{ + if (strcpy_s(udid, size, "ohos.deviceId.test") != EOK) { + return 1; + } else { + return 0; + } +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp new file mode 100644 index 000000000..42045285b --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "constant.h" +#include "accesstoken_log.h" +#include "softbus_bus_center.h" + +using namespace OHOS::Security::AccessToken; +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusCenterMock"}; +static const int REG_COUNT_LIMIT = 10; +} // namespace +static int regCount_ = -1; +static INodeStateCb *callback_ = nullptr; + +bool IsRegCountOK() +{ + return regCount_ >= 0 && regCount_ < REG_COUNT_LIMIT; +} + +int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback) +{ + regCount_++; + // reg:0-9 + if (IsRegCountOK()) { + callback_ = const_cast(callback); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, pkg:%{public}s, count: %{public}d", pkgName, regCount_); + return Constant::SUCCESS; + } + + // count 10 above alway return failure for retry. + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); + return Constant::FAILURE; +} + +int32_t UnregNodeDeviceStateCb(INodeStateCb *callback) +{ + // unreg: 0-9 + if (IsRegCountOK()) { + regCount_--; + callback_ = nullptr; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d", regCount_); + return Constant::SUCCESS; + } + + if (regCount_ >= 0) { + regCount_--; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); + return Constant::SUCCESS; +} + +int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) +{ + strcpy_s(info->deviceName, sizeof(info->deviceName), "local"); + strcpy_s(info->networkId, sizeof(info->networkId), "local"); + info->deviceTypeId = 1; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d", regCount_); + return Constant::SUCCESS; +} + +int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, NodeDeviceInfoKey key, uint8_t *info, + int32_t infoLen) +{ + if (networkId == nullptr || networkId[0] == '\0') { + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, invalid networkId, pkg name: %{public}s", pkgName); + return Constant::FAILURE; + } + + if (key == NodeDeviceInfoKey::NODE_KEY_UDID) { + std::string temp = networkId; + temp += ":udid-001"; + strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + infoLen = temp.length(); + } + if (key == NodeDeviceInfoKey::NODE_KEY_UUID) { + std::string temp = networkId; + temp += ":uuid-001"; + strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d, id: %{public}s", regCount_, info); + return Constant::SUCCESS; +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp new file mode 100644 index 000000000..6cb349e4d --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "session.h" +#include "constant.h" +#include "soft_bus_manager.h" +#include "accesstoken_log.h" +#include "soft_bus_session_listener.h" +#include "soft_bus_channel.h" + +using namespace OHOS::Security::AccessToken; +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusSenssionMock"}; +static const int SESSION_COUNT_LIMIT = 20; +static const int SERVER_COUNT_LIMIT = 10; +} // namespace + +#define MIN_(x, y) ((x) < (y)) ? (x) : (y) + +static int serverCount_ = -1; +bool IsServerCountOK() +{ + return serverCount_ >= 0 && serverCount_ < SERVER_COUNT_LIMIT; +} + +static ISessionListener *listener_ = nullptr; +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "pkg name: %{public}s", pkgName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionName: %{public}s", sessionName); + serverCount_++; + if (IsServerCountOK()) { + listener_ = const_cast(listener); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, server count: %{public}d", serverCount_); + return Constant::SUCCESS; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, server count: %{public}d", serverCount_); + return Constant::FAILURE; +} +int RemoveSessionServer(const char *pkgName, const char *sessionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "pkg name: %{public}s", pkgName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionName: %{public}s", sessionName); + if (IsServerCountOK()) { + serverCount_--; + listener_ = nullptr; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, server count: %{public}d", serverCount_); + return Constant::SUCCESS; + } + + if (serverCount_ >= 0) { + serverCount_--; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, server count: %{public}d", serverCount_); + return Constant::FAILURE; +} + +static int sessionCount_ = -1; +bool IsSessionCountOK() +{ + return sessionCount_ >= 0 && sessionCount_ < SESSION_COUNT_LIMIT; + ACCESSTOKEN_LOG_DEBUG(LABEL, "SESSION_COUNT_LIMIT: %{public}d", SESSION_COUNT_LIMIT); +} + +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, + const SessionAttribute *attr) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "mySessionName: %{public}s", mySessionName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "peerSessionName: %{public}s", peerSessionName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "peerDeviceId: %{public}s", peerDeviceId); + ACCESSTOKEN_LOG_DEBUG(LABEL, "groupId: %{public}s", groupId); + + sessionCount_++; + SoftBusSessionListener::OnSessionOpened(1, Constant::SUCCESS); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session count: %{public}d", sessionCount_); + return 1; +} +void CloseSession(int sessionId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionId: %{public}d", sessionId); + if (sessionCount_ >= 0) { + sessionCount_--; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session count: %{public}d", sessionCount_); + } +} + +static bool g_sendMessFlag = false; +int SendBytes(int sessionId, const void *data, unsigned int len) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "len: %{public}d", len); + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + DecompressMock((unsigned char *) data, len); + g_sendMessFlag = true; + return Constant::SUCCESS; +} + +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len) +{ + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + std::string x; + if (sessionId < SERVER_COUNT_LIMIT) { + x = SoftBusManager::SESSION_NAME; + } else { + x = "sessionid-" + std::to_string(sessionId); + } + if (len < x.length()) { + return Constant::FAILURE; + } + if (memcpy_s(sessionName, x.length(), x.c_str(), x.length()) != EOK) { + return Constant::FAILURE; + } + sessionName[x.length()] = '\0'; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session name: %{public}s", sessionName); + + return 0; +} + +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len) +{ + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + + std::string x = "deviceid-" + std::to_string(sessionId); + if (len < x.length()) { + return Constant::FAILURE; + } + + if (memcpy_s(devId, x.length(), x.c_str(), x.length()) != EOK) { + return Constant::FAILURE; + } + devId[x.length()] = '\0'; + return 0; +} + +static std::string uuid = ""; +void DecompressMock(const unsigned char *bytes, const int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "input length: %{public}d", length); + uLong len = 1048576; + unsigned char *buf = (unsigned char *) malloc(len + 1); + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory!"); + return; + } + (void)memset_s(buf, len + 1, 0, len + 1); + int result = uncompress(buf, &len, (unsigned char *) bytes, length); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "uncompress failed, error code: %{public}d, bound length: %{public}d, buffer length: %{public}d", result, + (int) len, length); + free(buf); + return; + } + buf[len] = '\0'; + std::string str((char *) buf); + free(buf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "done, output: %{public}s", str.c_str()); + + int id_post = str.find("\"id\":"); + + std::string id_string = str.substr(id_post + 6, 9); + uuid = id_string; + ACCESSTOKEN_LOG_DEBUG(LABEL, "id_string: %{public}s", id_string.c_str()); + return; +} + + +void CompressMock(const std::string &json, const unsigned char *compressedBytes, int &compressedLength) +{ + uLong len = compressBound(json.size()); + // length will not so that long + if (compressedLength > 0 && (int) len > compressedLength) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "compress error. data length overflow, bound length: %{public}d, buffer length: %{public}d", (int) len, + compressedLength); + return ; + } + + int result = compress((Byte *) compressedBytes, &len, (unsigned char *) json.c_str(), json.size() + 1); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "compress failed! error code: %{public}d", result); + return; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "compress complete. compress %{public}d bytes to %{public}d", compressedLength, + (int) len); + compressedLength = len; + return ; +} + +std::string GetUuidMock() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetUuidMock called uuid: %{public}s", uuid.c_str()); + return uuid; +} + + +bool GetSendMessFlagMock() +{ + return g_sendMessFlag; +} + +void ResetSendMessFlagMock() +{ + g_sendMessFlag = false; +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn new file mode 100644 index 000000000..e452ec6c3 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn @@ -0,0 +1,100 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/security/access_token/access_token.gni") +import("//build/test.gni") + +ohos_unittest("libtoken_sync_service_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ + #"//base/security/access_token/services/tokensyncmanager/src/common/constant.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/base_remote_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/delete_remote_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/device/device_info_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/device/device_info_repository.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_executor.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_factory.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_channel.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_event_handler.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_manager_service.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/constant_mock.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp", + + #"//base/security/access_token/services/tokensyncmanager/test/mock/src/mock_parameter.c", + "//base/security/access_token/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp", + ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/services/tokensyncmanager/include/service", + "//base/security/access_token/services/tokensyncmanager/include/remote", + "//base/security/access_token/services/tokensyncmanager/include/command", + "//base/security/access_token/services/tokensyncmanager/include/common", + "//base/security/access_token/services/tokensyncmanager/include/device", + "//base/security/access_token/services/tokensyncmanager/include/protocol", + "//base/security/access_token/services/tokensyncmanager/test/mock/include", + "//third_party/json/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + "//base/security/access_token/frameworks/common/include", + "//foundation/communication/dsoftbus/interfaces/kits/transport", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", + ] + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//third_party/zlib:libz", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + if (token_sync_enable == true) { + cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] + } + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libtoken_sync_service_sdk_test" ] +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp new file mode 100644 index 000000000..722c97a0b --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp @@ -0,0 +1,684 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "token_sync_service_test.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant_common.h" +#include "session.h" +#include "soft_bus_device_connection_listener.h" +#include "soft_bus_session_listener.h" +#include "device_info_manager.h" + +#define private public +#include "token_sync_manager_service.h" +#undef private + +using namespace std; +using namespace OHOS::Security::AccessToken; +using namespace testing::ext; +static std::vector threads_; +static std::shared_ptr g_ptrDeviceStateCallback = + std::make_shared(); +static std::string g_networkID = "deviceid-1"; +static std::string g_UDID = "deviceid-1:udid-001"; +static DmDeviceInfo g_devInfo = { + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + .deviceId = "deviceid-1", + .deviceName = "remote_mock", + .deviceTypeId = 1 +}; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKitTest"}; +} + +TokenSyncServiceTest::TokenSyncServiceTest() +{ + DelayedSingleton::GetInstance()->Initialize(); +} +TokenSyncServiceTest::~TokenSyncServiceTest() +{} +void TokenSyncServiceTest::SetUpTestCase() +{} +void TokenSyncServiceTest::TearDownTestCase() +{} +void TokenSyncServiceTest::SetUp() +{ +} +void TokenSyncServiceTest::TearDown() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "TearDown start."); + for (auto it = threads_.begin(); it != threads_.end(); it++) { + it->join(); + } + threads_.clear(); + + if (g_ptrDeviceStateCallback != nullptr) { + OnDeviceOffline(g_devInfo); + sleep(1); + } +} + +void TokenSyncServiceTest::OnDeviceOffline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = DeviceInfoManager::GetInstance().ConvertToUniversallyUniqueIdOrFetch(networkId); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDeviceIdOrFetch(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + ConstantCommon::EncryptDevId(udid).c_str()); + + if (uuid != "" && udid != "") { + RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid); + RemoteCommandManager::GetInstance().NotifyDeviceOffline(udid); + DeviceInfoManager::GetInstance().RemoveRemoteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, offline failed."); + } +} + +namespace { + std::string g_jsonBefore; + std::string g_jsonAfter; +} + +void SendTaskThread() +{ + while (!GetSendMessFlagMock()) { + sleep(1); + } + + ResetSendMessFlagMock(); + + std::string uuidMessage = GetUuidMock(); + std::string sendJson = g_jsonBefore + uuidMessage + g_jsonAfter; + + unsigned char *sendBuffer = (unsigned char *)malloc(0x1000); + if (sendBuffer == nullptr) { + return; + } + int sendLen = 0x1000; + CompressMock(sendJson, sendBuffer, sendLen); + + SoftBusSessionListener::OnBytesReceived(1, sendBuffer, sendLen); + free(sendBuffer); +} + +static PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "ohos.permission.test1", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +static PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "ohos.permission.test2", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +static PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "ohos.permission.test2", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {PermissionState::PERMISSION_GRANTED, PermissionState::PERMISSION_GRANTED}, + .resDeviceID = {"device 1", "device 2"} +}; + +static HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +static HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; + +/** + * @tc.name: GetRemoteHapTokenInfo002 + * @tc.desc: test remote hap recv func + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo002 start."); + // create local token + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + std::string jsonBefore = + "{\"commandName\":\"SyncRemoteHapTokenCommand\",\"id\":\"0065e65f-\",\"jsonPayload\":" + "\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":\\\"\\\",\\\"bundleName\\\":\\\"\\\"," + "\\\"deviceID\\\":\\\"\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":0,\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"local:udid-001\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":"; + std::string tokenJsonStr = std::to_string(tokenIdEx.tokenIdExStruct.tokenID); + std::string jsonAfter = ",\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"\\\",\\\"responseVersion\\\":2," + "\\\"srcDeviceId\\\":\\\"deviceid-1:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":100001," + "\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"request\"}"; + + std::string recvJson = jsonBefore + tokenJsonStr + jsonAfter; + + unsigned char *recvBuffer = (unsigned char *)malloc(0x1000); + int recvLen = 0x1000; + CompressMock(recvJson, recvBuffer, recvLen); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + SoftBusSessionListener::OnBytesReceived(1, recvBuffer, recvLen); + + int count = 0; + while (!GetSendMessFlagMock() && count < 10) { + sleep(1); + count ++; + } + free(recvBuffer); + + ResetSendMessFlagMock(); + std::string uuidMessage = GetUuidMock(); + ASSERT_EQ(uuidMessage, "0065e65f-"); +} + +/** + * @tc.name: GetRemoteHapTokenInfo003 + * @tc.desc: test remote hap send func, but get tokenInfo is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo003 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // apl is error + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":11,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0,\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + g_UDID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(g_UDID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: GetRemoteHapTokenInfo004 + * @tc.desc: test remote hap send func, but json payload lost parameter + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo004, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo004 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // lost tokenID + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + g_UDID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(g_UDID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: GetRemoteHapTokenInfo005 + * @tc.desc: test remote hap send func, but json payload parameter type is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo005, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo005 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // instIndex is not number + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":\\\"aaa\\\"," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + g_UDID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(g_UDID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: GetRemoteHapTokenInfo006 + * @tc.desc: test remote hap send func, but json payload parameter format is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo006, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo006 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // mock_token_sync lost \\\" + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync,\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + g_UDID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(g_UDID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: GetRemoteHapTokenInfo007 + * @tc.desc: test remote hap send func, statusCode is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo007, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo007 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // statusCode error + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":11,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":-2,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + g_UDID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(g_UDID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: GetRemoteHapTokenInfo008 + * @tc.desc: test remote hap recv func, tokenID is not exist + * @tc.type: FUNC + * @tc.require:AR000GK6T5 AR000GK6T9 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo008, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo008 start."); + // create local token + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + // tokenID is not exist + std::string jsonBefore = + "{\"commandName\":\"SyncRemoteHapTokenCommand\",\"id\":\"0065e65f-\",\"jsonPayload\":" + "\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":\\\"\\\",\\\"bundleName\\\":\\\"\\\"," + "\\\"deviceID\\\":\\\"\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":0,\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"local:udid-001\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":"; + std::string tokenJsonStr = std::to_string(tokenID); + std::string jsonAfter = ",\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"\\\",\\\"responseVersion\\\":2," + "\\\"srcDeviceId\\\":\\\"deviceid-1:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":100001," + "\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"request\"}"; + + // create recv message + std::string recvJson = jsonBefore + tokenJsonStr + jsonAfter; + unsigned char *recvBuffer = (unsigned char *)malloc(0x1000); + int recvLen = 0x1000; + CompressMock(recvJson, recvBuffer, recvLen); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + SoftBusSessionListener::OnBytesReceived(1, recvBuffer, recvLen); + + int count = 0; + while (!GetSendMessFlagMock() && count < 10) { + sleep(1); + count ++; + } + free(recvBuffer); + + ResetSendMessFlagMock(); + std::string uuidMessage = GetUuidMock(); + ASSERT_EQ(uuidMessage, "0065e65f-"); +} + +/** + * @tc.name: SyncNativeTokens001 + * @tc.desc: when device is online, sync remote nativetokens which have dcap + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens001 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteNativeTokenCommand\", \"id\":\""; + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"NativeTokenInfos\\\":[{\\\"apl\\\":3,\\\"processName\\\":\\\"attest\\\"," + "\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088640,\\\"version\\\":1," + "\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}," + "{\\\"apl\\\":3,\\\"processName\\\":\\\"attest1\\\",\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088641," + "\\\"version\\\":1,\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}]," + "\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\"," + "\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + sleep(6); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000000); + ASSERT_NE(mapID, (AccessTokenID)0); + int ret = AccessTokenKit::CheckNativeDCap(mapID, "SYSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenKit::CheckNativeDCap(mapID, "DMSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + + mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000001); + ASSERT_NE(mapID, (AccessTokenID)0); + ret = AccessTokenKit::CheckNativeDCap(mapID, "SYSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenKit::CheckNativeDCap(mapID, "DMSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); +} + +/** + * @tc.name: SyncNativeTokens002 + * @tc.desc: when device is online, sync remote nativetoken which has no dcaps + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens002 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteNativeTokenCommand\", \"id\":\""; + // 0x28000001 token has no dcaps + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"NativeTokenInfos\\\":[{\\\"apl\\\":3,\\\"processName\\\":\\\"attest\\\"," + "\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088640,\\\"version\\\":1," + "\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}," + "{\\\"apl\\\":3,\\\"processName\\\":\\\"attest1\\\",\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088641," + "\\\"version\\\":1,\\\"dcaps\\\":[]}]," + "\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\"," + "\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + sleep(6); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000000); + ASSERT_NE(mapID, (AccessTokenID)0); + int ret = AccessTokenKit::CheckNativeDCap(mapID, "SYSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenKit::CheckNativeDCap(mapID, "DMSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + + mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000001); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: SyncNativeTokens003 + * @tc.desc: when device is online, sync remote nativetokens status failed + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens003 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteNativeTokenCommand\", \"id\":\""; + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"NativeTokenInfos\\\":[{\\\"apl\\\":3,\\\"processName\\\":\\\"attest\\\"," + "\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088640,\\\"version\\\":1," + "\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}," + "{\\\"apl\\\":3,\\\"processName\\\":\\\"attest1\\\",\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088641," + "\\\"version\\\":1,\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}]," + "\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\"," + "\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":-2," + "\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\",\"type\":\"response\"}"; + + + threads_.emplace_back(std::thread(SendTaskThread)); + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + sleep(6); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000001); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: SyncNativeTokens004 + * @tc.desc: when device is online, sync remote nativetokens which parameter is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens004, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens004 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteNativeTokenCommand\", \"id\":\""; + // apl is error + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"NativeTokenInfos\\\":[{\\\"apl\\\":11,\\\"processName\\\":\\\"attest\\\"," + "\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088640,\\\"version\\\":1," + "\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}," + "{\\\"apl\\\":11,\\\"processName\\\":\\\"attest1\\\",\\\"tokenAttr\\\":0,\\\"tokenId\\\":671088641," + "\\\"version\\\":1,\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}]," + "\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\"," + "\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + + sleep(6); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + mapID = AccessTokenKit::GetRemoteNativeTokenID(g_UDID, 0x28000001); + ASSERT_EQ(mapID, (AccessTokenID)0); +} + +/** + * @tc.name: SyncNativeTokens005 + * @tc.desc: test remote hap recv func + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens005, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens005 start."); + + std::string recvJson = + "{\"commandName\":\"SyncRemoteNativeTokenCommand\",\"id\":\"ec23cd2d-\",\"jsonPayload\":" + "\"{\\\"NativeTokenInfos\\\":null,\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"local:udid-001\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"\\\",\\\"responseVersion\\\":2," + "\\\"srcDeviceId\\\":\\\"deviceid-1\\\",\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":100001," + "\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\",\"type\":\"request\"}"; + + unsigned char *recvBuffer = (unsigned char *)malloc(0x1000); + int recvLen = 0x1000; + CompressMock(recvJson, recvBuffer, recvLen); + + g_ptrDeviceStateCallback->OnDeviceOnline(g_devInfo); + SoftBusSessionListener::OnBytesReceived(1, recvBuffer, recvLen); + + int count = 0; + while (!GetSendMessFlagMock() && count < 10) { + sleep(1); + count ++; + } + free(recvBuffer); + + ResetSendMessFlagMock(); + std::string uuidMessage = GetUuidMock(); + ASSERT_EQ(uuidMessage, "ec23cd2d-"); +} + +namespace { +PermissionStateFull g_infoManagerTestUpdateState1 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .isGeneral = true, + .permissionName = "ohos.permission.CAMERA", + .resDeviceID = {"local"} +}; + +PermissionStateFull g_infoManagerTestUpdateState2 = { + .permissionName = "ohos.permission.ANSWER_CALL", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {PermissionState::PERMISSION_DENIED, PermissionState::PERMISSION_DENIED}, + .resDeviceID = {"device 1", "device 2"} +}; + +HapTokenInfo g_remoteHapInfoBasic = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "accesstoken_test", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = "0", + .tokenID = 0x20000001, + .tokenAttr = 0 +}; + +HapTokenInfoForSync g_remoteHapInfo = { + .baseInfo = g_remoteHapInfoBasic, + .permStateList = {g_infoManagerTestUpdateState1, g_infoManagerTestUpdateState2} +}; +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h new file mode 100644 index 000000000..37e27cc3a --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_SERVICE_TEST_H +#define TOKEN_SYNC_SERVICE_TEST_H + +#include +#include "device_info_manager.h" +#include "device_manager_callback.h" +#include "dm_device_info.h" +#include "remote_command_manager.h" +#include "softbus_bus_center.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +using OHOS::DistributedHardware::DeviceStateCallback; +using OHOS::DistributedHardware::DmDeviceInfo; +using OHOS::DistributedHardware::DmInitCallback; +class TokenSyncServiceTest : public testing::Test { +public: + TokenSyncServiceTest(); + ~TokenSyncServiceTest(); + static void SetUpTestCase(); + static void TearDownTestCase(); + void OnDeviceOffline(const DmDeviceInfo &info); + void SetUp(); + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_SERVICE_TEST_H \ No newline at end of file diff --git a/security_access_token-yl_0822/services/tokensyncmanager/token_sync.cfg b/security_access_token-yl_0822/services/tokensyncmanager/token_sync.cfg new file mode 100644 index 000000000..534b5bf11 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/token_sync.cfg @@ -0,0 +1,13 @@ +{ + "services" : [{ + "name" : "token_sync_service", + "path" : ["/system/bin/sa_main", "/system/profile/token_sync_service.xml"], + "ondemand" : true, + "start-mode" : "condition", + "uid" : "access_token", + "gid" : ["access_token"], + "permission" : ["ohos.permission.DISTRIBUTED_DATASYNC"], + "secon" : "u:r:token_sync_service:s0" + } + ] +} diff --git a/security_access_token-yl_0822/services/tokensyncmanager/token_sync.rc b/security_access_token-yl_0822/services/tokensyncmanager/token_sync.rc new file mode 100644 index 000000000..04ffbeb26 --- /dev/null +++ b/security_access_token-yl_0822/services/tokensyncmanager/token_sync.rc @@ -0,0 +1,22 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +on late-fs + start token_sync_service + +service token_sync_service /system/bin/sa_main /system/profile/token_sync_service.xml + class token_sync_service + priority -20 + user access_token + group access_token + seclabel u:r:token_sync_service:s0 diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/BUILD.gn new file mode 100644 index 000000000..e37d93e7f --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("fuzztest") { + testonly = true + deps = [] + + deps += [ + # deps file + "allochaptoken_fuzzer:AllocHapTokenFuzzTest", + "alloclocaltokenid_fuzzer:AllocLocalTokenIDFuzzTest", + "checknativedcap_fuzzer:CheckNativeDCapFuzzTest", + "clearusergrantedpermissionstate_fuzzer:ClearUserGrantedPermissionStateFuzzTest", + "deleteremotedevicetokens_fuzzer:DeleteRemoteDeviceTokensFuzzTest", + "deleteremotetoken_fuzzer:DeleteRemoteTokenFuzzTest", + "deletetoken_fuzzer:DeleteTokenFuzzTest", + "getdefpermission_fuzzer:GetDefPermissionFuzzTest", + "getpermissionflags_fuzzer:GetPermissionFlagsFuzzTest", + "grantpermission_fuzzer:GrantPermissionFuzzTest", + "revokeusergrantedpermission_fuzzer:RevokeUserGrantedPermissionFuzzTest", + "setremotehaptokeninfo_fuzzer:SetRemoteHapTokenInfoFuzzTest", + "setremotenativetokeninfo_fuzzer:SetRemoteNativeTokenInfoFuzzTest", + "updatehaptoken_fuzzer:UpdateHapTokenFuzzTest", + "verifyaccesstoken001_fuzzer:VerifyAccessToken001FuzzTest", + "verifyaccesstoken_fuzzer:VerifyAccessTokenFuzzTest", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn new file mode 100644 index 000000000..7f773f0c8 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("AllocHapTokenFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/allochaptoken_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "allochaptoken_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp new file mode 100644 index 000000000..094fa5d6e --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "allochaptoken_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool AllocHapTokenFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + std::string testdata; + AccessTokenIDEx tokenIdEx = {0}; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + testdata = reinterpret_cast(data); + PermissionDef TestPermDef = { + .permissionName = testdata, + .bundleName = testdata, + .grantMode = 1, + .availableLevel = APL_NORMAL, + .label = testdata, + .labelId = 1, + .description = testdata, + .descriptionId = 1 + }; + PermissionStateFull TestState = { + .permissionName = testdata, + .isGeneral = true, + .resDeviceID = {testdata}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1}, + }; + HapInfoParams TestInfoParms = { + .userID = 1, + .bundleName = testdata, + .instIndex = 0, + .appIDDesc = testdata + }; + HapPolicyParams TestPolicyPrams = { + .apl = APL_NORMAL, + .domain = testdata, + .permList = {TestPermDef}, + .permStateList = {TestState} + }; + + tokenIdEx = AccessTokenKit::AllocHapToken(TestInfoParms, TestPolicyPrams); + } + return tokenIdEx.tokenIdExStruct.tokenID != 0; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AllocHapTokenFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.h new file mode 100644 index 000000000..e2ceda0b5 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ALLOCHAPTOKEN_FUZZER_H +#define TEST_FUZZTEST_ALLOCHAPTOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "allochaptoken_fuzzer" + +#endif // TEST_FUZZTEST_ALLOCHAPTOKEN_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/allochaptoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn new file mode 100644 index 000000000..87ddbd2a1 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("AllocLocalTokenIDFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/alloclocaltokenid_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "alloclocaltokenid_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp new file mode 100644 index 000000000..993f3a079 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "alloclocaltokenid_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool AllocLocalTokenIDFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + AccessTokenID TOKENID = 0; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID REMOTETOKENID = static_cast(size); + TOKENID = AccessTokenKit::AllocLocalTokenID(reinterpret_cast(data), REMOTETOKENID); + } + return TOKENID != 0; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::AllocLocalTokenIDFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.h new file mode 100644 index 000000000..24cc37870 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_ALLOCLOCALTOKENID_FUZZER_H +#define TEST_FUZZTEST_ALLOCLOCALTOKENID_FUZZER_H + +#define FUZZ_PROJECT_NAME "alloclocaltokenid_fuzzer" + +#endif // TEST_FUZZTEST_ALLOCLOCALTOKENID_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/alloclocaltokenid_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn new file mode 100644 index 000000000..38d3c8425 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("CheckNativeDCapFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/checknativedcap_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "checknativedcap_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp new file mode 100644 index 000000000..7b22eff36 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "checknativedcap_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool CheckNativeDCapFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::CheckNativeDCap(TOKENID, reinterpret_cast(data)); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::CheckNativeDCapFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.h new file mode 100644 index 000000000..4da892de7 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_CHECKNATIVEDCAP_FUZZER_H +#define TEST_FUZZTEST_CHECKNATIVEDCAP_FUZZER_H + +#define FUZZ_PROJECT_NAME "checknativedcap_fuzzer" + +#endif // TEST_FUZZTEST_CHECKNATIVEDCAP_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/checknativedcap_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn new file mode 100644 index 000000000..32f153f3f --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("ClearUserGrantedPermissionStateFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "clearusergrantedpermissionstate_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.cpp new file mode 100644 index 000000000..18f55fbd2 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "clearusergrantedpermissionstate_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool ClearUserGrantedPermissionStateFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::ClearUserGrantedPermissionState(TOKENID); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::ClearUserGrantedPermissionStateFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.h new file mode 100644 index 000000000..042746200 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/clearusergrantedpermissionstate_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_CLEARUSERGRANTEDPERMISSIONSTATE_FUZZER_H +#define TEST_FUZZTEST_CLEARUSERGRANTEDPERMISSIONSTATE_FUZZER_H + +#define FUZZ_PROJECT_NAME "clearusergrantedpermissionstate_fuzzer" + +#endif // TEST_FUZZTEST_CLEARUSERGRANTEDPERMISSIONSTATE_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn new file mode 100644 index 000000000..6d69bec75 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("DeleteRemoteDeviceTokensFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "deleteremotedevicetokens_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp new file mode 100644 index 000000000..3350c7640 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "deleteremotedevicetokens_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + + +namespace OHOS { + bool DeleteRemoteDeviceTokensFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + +#ifdef TOKEN_SYNC_ENABLE + + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + result = AccessTokenKit::DeleteRemoteDeviceTokens(reinterpret_cast(data)); + } + +#endif + + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + + OHOS::DeleteRemoteDeviceTokensFuzzTest(data, size); + return 0; +} + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.h new file mode 100644 index 000000000..efd039c24 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_DELETEREMOTEDEVICETOKENS_FUZZER_H +#define TEST_FUZZTEST_DELETEREMOTEDEVICETOKENS_FUZZER_H + +#define FUZZ_PROJECT_NAME "deleteremotedevicetokens_fuzzer" + +#endif // TEST_FUZZTEST_DELETEREMOTEDEVICETOKENS_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn new file mode 100644 index 000000000..5b686f792 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("DeleteRemoteTokenFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/deleteremotetoken_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "deleteremotetoken_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp new file mode 100644 index 000000000..bcd031a6b --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "deleteremotetoken_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool DeleteRemoteTokenFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + +#ifdef TOKEN_SYNC_ENABLE + + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::DeleteRemoteToken(reinterpret_cast(data), TOKENID); + } + +#endif + + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DeleteRemoteTokenFuzzTest(data, size); + return 0; +} + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.h new file mode 100644 index 000000000..594034594 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_DELETEREMOTETOKEN_FUZZER_H +#define TEST_FUZZTEST_DELETEREMOTETOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "deleteremotetoken_fuzzer" + +#endif // TEST_FUZZTEST_DELETEREMOTETOKEN_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deleteremotetoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn new file mode 100644 index 000000000..f37c04746 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("DeleteTokenFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/deletetoken_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "deletetoken_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.cpp new file mode 100644 index 000000000..93cd4c843 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "deletetoken_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool DeleteTokenFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::DeleteToken(TOKENID); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DeleteTokenFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.h new file mode 100644 index 000000000..1f0a40115 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/deletetoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_DELETETOKEN_FUZZER_H +#define TEST_FUZZTEST_DELETETOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "deletetoken_fuzzer" + +#endif // TEST_FUZZTEST_DELETETOKEN_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/deletetoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn new file mode 100644 index 000000000..925202101 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetDefPermissionFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/getdefpermission_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/frameworks/common/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getdefpermission_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp new file mode 100644 index 000000000..38fbe3a3d --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getdefpermission_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" +#include "permission_def.h" + +using namespace std; +using namespace OHOS; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetDefPermissionFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + std::string testdata; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + testdata = reinterpret_cast(data); + PermissionDef PERMISSIONDEF = { + .permissionName = testdata, + .bundleName = testdata, + .grantMode = 1, + .label = testdata, + .labelId = 1, + .description = testdata, + .availableLevel = APL_NORMAL, + .descriptionId = 1 + }; + result = AccessTokenKit::GetDefPermission(testdata, PERMISSIONDEF); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetDefPermissionFuzzTest(data, size); + return 0; +} + \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.h new file mode 100644 index 000000000..5d8983a59 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETDEFPERMISSION_FUZZER_H +#define TEST_FUZZTEST_GETDEFPERMISSION_FUZZER_H + +#define FUZZ_PROJECT_NAME "getdefpermission_fuzzer" + +#endif // TEST_FUZZTEST_GETDEFPERMISSION_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getdefpermission_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn new file mode 100644 index 000000000..328246ace --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GetPermissionFlagsFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/getpermissionflags_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "getpermissionflags_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp new file mode 100644 index 000000000..9175d62dd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "getpermissionflags_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GetPermissionFlagsFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::GetPermissionFlag(TOKENID, reinterpret_cast(data)); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GetPermissionFlagsFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.h new file mode 100644 index 000000000..8d7b1d347 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GETPERMISSIONFLAGS_FUZZER_H +#define TEST_FUZZTEST_GETPERMISSIONFLAGS_FUZZER_H + +#define FUZZ_PROJECT_NAME "getpermissionflags_fuzzer" + +#endif // TEST_FUZZTEST_GETPERMISSIONFLAGS_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/getpermissionflags_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn new file mode 100644 index 000000000..bb588f85f --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("GrantPermissionFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/grantpermission_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "grantpermission_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp new file mode 100644 index 000000000..b821ba974 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "grantpermission_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool GrantPermissionFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::GrantPermission(TOKENID, reinterpret_cast(data), 0); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::GrantPermissionFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.h new file mode 100644 index 000000000..64a6c5498 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_GRANTPERMISSION_FUZZER_H +#define TEST_FUZZTEST_GRANTPERMISSION_FUZZER_H + +#define FUZZ_PROJECT_NAME "grantpermission_fuzzer" + +#endif // TEST_FUZZTEST_GRANTPERMISSION_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/grantpermission_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn new file mode 100644 index 000000000..94f45a419 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("RevokeUserGrantedPermissionFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "revokeusergrantedpermission_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp new file mode 100644 index 000000000..c2a1dc550 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "revokeusergrantedpermission_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool RevokeUserGrantedPermissionFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::RevokePermission(TOKENID, reinterpret_cast(data), 0); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::RevokeUserGrantedPermissionFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.h new file mode 100644 index 000000000..3324007c9 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_REVOKEUSERGRANTEDPERMISSION_FUZZER_H +#define TEST_FUZZTEST_REVOKEUSERGRANTEDPERMISSION_FUZZER_H + +#define FUZZ_PROJECT_NAME "revokeusergrantedpermission_fuzzer" + +#endif // TEST_FUZZTEST_REVOKEUSERGRANTEDPERMISSION_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn new file mode 100644 index 000000000..d9591910a --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("SetRemoteHapTokenInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "setremotehaptokeninfo_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp new file mode 100644 index 000000000..b4b69c86f --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setremotehaptokeninfo_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool SetRemoteHapTokenInfoFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; +#ifdef TOKEN_SYNC_ENABLE + std::string testdata; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + testdata = reinterpret_cast(data); + AccessTokenID TOKENID = static_cast(size); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = testdata, + .instIndex = 1, + .appID = testdata, + .deviceID = testdata, + .tokenID = TOKENID, + .tokenAttr = 0 + }; + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = testdata, + .resDeviceID = {testdata}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList = permStateList + }; + + result = AccessTokenKit::SetRemoteHapTokenInfo(reinterpret_cast(data), remoteTokenInfo); + } +#endif + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::SetRemoteHapTokenInfoFuzzTest(data, size); + return 0; +} + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.h new file mode 100644 index 000000000..2a06877e6 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_SETREMOTEHAPTOKENINFO_FUZZER_H +#define TEST_FUZZTEST_SETREMOTEHAPTOKENINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "setremotehaptokeninfo_fuzzer" + +#endif // TEST_FUZZTEST_SETREMOTEHAPTOKENINFO_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn new file mode 100644 index 000000000..fbfdebf50 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("SetRemoteNativeTokenInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "setremotenativetokeninfo_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp new file mode 100644 index 000000000..60f33a711 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "setremotenativetokeninfo_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool SetRemoteNativeTokenInfoFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + +#ifdef TOKEN_SYNC_ENABLE + + std::string testdata; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + testdata = reinterpret_cast(data); + AccessTokenID TOKENID = static_cast(size); + NativeTokenInfoForSync native1 = { + .baseInfo.apl = APL_NORMAL, + .baseInfo.ver = 1, + .baseInfo.processName = testdata, + .baseInfo.dcap = {testdata, testdata}, + .baseInfo.tokenID = TOKENID, + .baseInfo.tokenAttr = 0, + .baseInfo.nativeAcls = {testdata}, + }; + + std::vector nativeTokenInfoList; + nativeTokenInfoList.emplace_back(native1); + + result = AccessTokenKit::SetRemoteNativeTokenInfo(reinterpret_cast(data), nativeTokenInfoList); + } + +#endif + + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::SetRemoteNativeTokenInfoFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.h new file mode 100644 index 000000000..4c681fd78 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_SETREMOTENATIVETOKENINFO_FUZZER_H +#define TEST_FUZZTEST_SETREMOTENATIVETOKENINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "setremotenativetokeninfo_fuzzer" + +#endif // TEST_FUZZTEST_SETREMOTENATIVETOKENINFO_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn new file mode 100644 index 000000000..2ae1796e7 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("UpdateHapTokenFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/updatehaptoken_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "updatehaptoken_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp new file mode 100644 index 000000000..80a4cd472 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "updatehaptoken_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool UpdateHapTokenFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + std::string testdata; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + testdata = reinterpret_cast(data); + PermissionDef TestPermDef = { + .permissionName = testdata, + .bundleName = testdata, + .grantMode = 1, + .availableLevel = APL_NORMAL, + .label = testdata, + .labelId = 1, + .description = testdata, + .descriptionId = 1 + }; + PermissionStateFull TestState = { + .permissionName = testdata, + .isGeneral = true, + .resDeviceID = {testdata}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1}, + }; + HapPolicyParams TestPolicyPrams = { + .apl = APL_NORMAL, + .domain = testdata, + .permList = {TestPermDef}, + .permStateList = {TestState} + }; + constexpr int32_t DEFAULT_API_VERSION = 8; + result = AccessTokenKit::UpdateHapToken(TOKENID, testdata, DEFAULT_API_VERSION, TestPolicyPrams); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::UpdateHapTokenFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.h new file mode 100644 index 000000000..5eb0c5ea1 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_UPDATEHAPTOKEN_FUZZER_H +#define TEST_FUZZTEST_UPDATEHAPTOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "updatehaptoken_fuzzer" + +#endif // TEST_FUZZTEST_UPDATEHAPTOKEN_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn new file mode 100644 index 000000000..d373c8157 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("VerifyAccessToken001FuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/verifyaccesstoken001_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "verifyaccesstoken001_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp new file mode 100644 index 000000000..ec6ff9368 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "verifyaccesstoken001_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool VerifyAccessToken001FuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::VerifyAccessToken(TOKENID, TOKENID, reinterpret_cast(data)); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::VerifyAccessToken001FuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.h new file mode 100644 index 000000000..78473a298 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_VERIFYACCESSTOKEN001_FUZZER_H +#define TEST_FUZZTEST_VERIFYACCESSTOKEN001_FUZZER_H + +#define FUZZ_PROJECT_NAME "verifyaccesstoken001_fuzzer" + +#endif // TEST_FUZZTEST_VERIFYACCESSTOKEN001_FUZZER_H diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn new file mode 100644 index 000000000..961604817 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") + +module_output_path = "access_token/access_token" + +ohos_fuzztest("VerifyAccessTokenFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "//base/security/access_token/test/fuzztest/access_token/verifyaccesstoken_fuzzer" + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "verifyaccesstoken_fuzzer.cpp" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ + "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", + "LOG_DOMAIN = 0xD001B00", + ] +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/corpus/init b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/corpus/init new file mode 100644 index 000000000..bc977bd97 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FUZZ \ No newline at end of file diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/project.xml b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/project.xml new file mode 100644 index 000000000..6e8ad2cfd --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp new file mode 100644 index 000000000..de192b189 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "verifyaccesstoken_fuzzer.h" + +#include +#include +#include +#undef private +#include "accesstoken_kit.h" + +using namespace std; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { + bool VerifyAccessTokenFuzzTest(const uint8_t* data, size_t size) + { + bool result = false; + if ((data == nullptr) || (size <= 0)) { + return result; + } + if (size > 0) { + AccessTokenID TOKENID = static_cast(size); + result = AccessTokenKit::VerifyAccessToken(TOKENID, reinterpret_cast(data)); + } + return result; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::VerifyAccessTokenFuzzTest(data, size); + return 0; +} diff --git a/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.h b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.h new file mode 100644 index 000000000..c754140f2 --- /dev/null +++ b/security_access_token-yl_0822/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TEST_FUZZTEST_VERIFYACCESSTOKEN_FUZZER_H +#define TEST_FUZZTEST_VERIFYACCESSTOKEN_FUZZER_H + +#define FUZZ_PROJECT_NAME "verifyaccesstoken_fuzzer" + +#endif // TEST_FUZZTEST_VERIFYACCESSTOKEN_FUZZER_H diff --git a/security_access_token-yl_0822/tools/BUILD.gn b/security_access_token-yl_0822/tools/BUILD.gn new file mode 100644 index 000000000..86994d402 --- /dev/null +++ b/security_access_token-yl_0822/tools/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("tools_atm") { + deps = [] + if (support_jsapi) { + deps += [ "./accesstoken:atm" ] + } +} diff --git a/security_access_token-yl_0822/tools/accesstoken/BUILD.gn b/security_access_token-yl_0822/tools/accesstoken/BUILD.gn new file mode 100644 index 000000000..d5ef0095d --- /dev/null +++ b/security_access_token-yl_0822/tools/accesstoken/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_source_set("tools_atm_source_set") { + include_dirs = [ + "include", + "//base/security/access_token/frameworks/common/include", + "${ability_runtime_path}/tools/aa/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", + "//base/security/access_token/interfaces/innerkits/privacy/include", + "${ability_runtime_services_path}/common/include", + ] + + sources = [ + "${ability_runtime_path}/tools/aa/src/shell_command.cpp", + "src/atm_command.cpp", + "src/atm_receiver_impl.cpp", + "src/main.cpp", + ] + + deps = [ + "${ability_runtime_path}/tools/aa:aa", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/innerkits/privacy:libprivacy_sdk", + ] + + cflags = [ "-DHILOG_ENABLE" ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + external_deps = [ + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "security" + part_name = "access_token" +} + +ohos_executable("atm") { + deps = [ ":tools_atm_source_set" ] + + install_enable = true + subsystem_name = "security" + part_name = "access_token" +} diff --git a/security_access_token-yl_0822/tools/accesstoken/include/atm_command.h b/security_access_token-yl_0822/tools/accesstoken/include/atm_command.h new file mode 100644 index 000000000..ad69570c6 --- /dev/null +++ b/security_access_token-yl_0822/tools/accesstoken/include/atm_command.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ACCESSTOKENMANAGER_COMMAND_H +#define ACCESSTOKENMANAGER_COMMAND_H + +#include "shell_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef enum TypeOptType { + DEFAULT = 0, + DUMP_TOKEN, + DUMP_RECORD, + PERM_GRANT, + PERM_REVOKE, +} OptType; + +const std::string TOOLS_NAME = "atm"; +const std::string HELP_MSG = "usage: atm