From d88b3a43a09e8db6430e412d9c973c76721e5248 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 14 Apr 2025 15:07:35 +0800 Subject: [PATCH 01/38] =?UTF-8?q?DM=E7=BB=91=E5=AE=9A=E6=96=B0=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bundle.json | 14 +- common/include/dm_anonymous.h | 1 + common/include/dm_error_type.h | 15 +- common/src/dm_anonymous.cpp | 18 + commondependency/BUILD.gn | 4 +- .../include/deviceprofile_connector.h | 82 +- .../include/multiple_user_connector.h | 5 +- .../src/deviceprofile_connector.cpp | 917 +++++++++-- .../src/multiple_user_connector.cpp | 39 +- .../include/i_dm_bind_manager_ext_resident.h | 3 + .../include/i_dm_service_impl_ext.h | 4 + services/implementation/BUILD.gn | 15 + .../authentication/auth_message_processor.h | 21 - .../include/authentication/dm_auth_manager.h | 16 +- .../include/authentication_v2/auth_manager.h | 208 +++ .../authentication_v2/dm_auth_context.h | 250 +++ .../authentication_v2/dm_auth_manager_base.h | 255 +++ .../dm_auth_message_processor.h | 300 ++++ .../include/authentication_v2/dm_auth_state.h | 445 ++++++ .../authentication_v2/dm_auth_state_machine.h | 118 ++ .../authentication_v2/dm_negotiate_process.h | 192 +++ .../include/cryptomgr/crypto_mgr.h | 1 + .../hichain/hichain_auth_connector.h | 25 +- .../hichain/hichain_connector_callback.h | 3 +- .../dependency/softbus/softbus_connector.h | 20 +- .../dependency/softbus/softbus_session.h | 2 - .../include/device_manager_service_impl.h | 108 +- .../device_manager_service_impl_lite.h | 12 +- .../include/i18n/dm_language_manager.h | 2 + .../authentication/auth_message_processor.cpp | 22 - .../src/authentication/dm_auth_manager.cpp | 238 ++- .../src/authentication_v2/auth_manager.cpp | 1070 +++++++++++++ .../auth_stages/auth_acl.cpp | 146 ++ .../auth_stages/auth_confirm.cpp | 738 +++++++++ .../auth_stages/auth_credential.cpp | 532 +++++++ .../auth_stages/auth_negotiate.cpp | 512 ++++++ .../auth_stages/auth_pin_auth.cpp | 598 ++++++++ .../src/authentication_v2/dm_auth_context.cpp | 90 ++ .../dm_auth_manager_base.cpp | 491 ++++++ .../dm_auth_message_processor.cpp | 1366 +++++++++++++++++ .../src/authentication_v2/dm_auth_state.cpp | 374 +++++ .../dm_auth_state_machine.cpp | 354 +++++ .../dm_negotiate_process.cpp | 289 ++++ .../src/cryptomgr/crypto_mgr.cpp | 7 + .../hichain/hichain_auth_connector.cpp | 345 ++++- .../dependency/softbus/softbus_connector.cpp | 243 ++- .../dependency/softbus/softbus_session.cpp | 94 +- .../src/device_manager_service_impl.cpp | 1284 ++++++++++++++-- .../src/device_manager_service_impl_lite.cpp | 37 +- .../devicestate/dm_device_state_manager.cpp | 5 +- .../src/i18n/dm_language_manager.cpp | 50 + .../service/include/device_manager_service.h | 4 + .../include/idevice_manager_service_impl.h | 10 +- .../relationship_sync_mgr.h | 2 + .../include/softbus/softbus_listener.h | 4 + .../service/src/device_manager_service.cpp | 30 +- .../relationship_sync_mgr.cpp | 25 +- .../service/src/softbus/softbus_listener.cpp | 16 +- test/commonfuzztest/BUILD.gn | 2 + .../authenticatedeviceservice_fuzzer/BUILD.gn | 1 - .../BUILD.gn | 1 - .../dmauthmanager_fuzzer/BUILD.gn | 1 - .../dm_auth_manager_fuzzer.cpp | 3 +- .../dmauthmanagerv2_fuzzer/BUILD.gn | 79 + .../dmauthmanagerv2_fuzzer/corpus/init | 13 + .../dm_auth_manager_fuzzer.cpp | 122 ++ .../dm_auth_manager_fuzzer.h | 21 + .../dmauthmanagerv2_fuzzer/project.xml | 25 + .../hichainconnector_fuzzer/BUILD.gn | 1 - .../ondatareceived_fuzzer/BUILD.gn | 1 - .../ondatareceivedv2_fuzzer/BUILD.gn | 78 + .../ondatareceivedv2_fuzzer/corpus/init | 13 + .../on_data_received_fuzzer.cpp | 71 + .../on_data_received_fuzzer.h | 21 + .../ondatareceivedv2_fuzzer/project.xml | 25 + test/commonfuzztest/onerror_fuzzer/BUILD.gn | 1 - test/commonfuzztest/onfinish_fuzzer/BUILD.gn | 1 - test/commonfuzztest/onrequest_fuzzer/BUILD.gn | 1 - .../UTTest_dm_auth_manager_first.cpp | 50 +- .../UTTest_dm_auth_manager_second.cpp | 29 +- .../UTTest_dm_auth_manager_third.cpp | 2 +- .../UTTest_dm_deviceprofile_connector.cpp | 127 +- ...Test_dm_deviceprofile_connector_second.cpp | 17 +- .../UTTest_hichain_auth_connector.cpp | 113 +- .../UTTest_hichain_auth_connector.h | 3 +- .../devicemanagerservice_fuzzer/BUILD.gn | 1 - .../deviceprofileconnector_fuzzer/BUILD.gn | 1 - .../device_profile_connector_fuzzer.cpp | 2 +- .../BUILD.gn | 1 - .../shiftlnngeardeviceservice_fuzzer/BUILD.gn | 1 - .../on_bytes_received_fuzzer.cpp | 2 - .../onsessionopened_fuzzer/BUILD.gn | 1 - .../softbusconnector_fuzzer/BUILD.gn | 1 + .../softbusconnectorcommon_fuzzer/BUILD.gn | 1 + .../softbusconnectorpublish_fuzzer/BUILD.gn | 1 + .../softbusconnectorstate_fuzzer/BUILD.gn | 1 + .../softbusconnectorstatic_fuzzer/BUILD.gn | 1 + .../softbussession_fuzzer/BUILD.gn | 1 + .../softbus_session_fuzzer.cpp | 1 - .../softbussessionobject_fuzzer/BUILD.gn | 1 + .../softbus_session_object_fuzzer.cpp | 13 - .../UTTest_softbus_connector.cpp | 12 +- .../UTTest_softbus_session.cpp | 15 +- test/unittest/BUILD.gn | 97 +- .../unittest/UTTest_auth_credential_state.cpp | 1003 ++++++++++++ test/unittest/UTTest_auth_credential_state.h | 50 + test/unittest/UTTest_auth_negotiate_state.cpp | 106 ++ test/unittest/UTTest_auth_negotiate_state.h | 48 + test/unittest/UTTest_auth_pin_auth_state.cpp | 420 +++++ test/unittest/UTTest_auth_pin_auth_state.h | 46 + test/unittest/UTTest_device_manager_impl.cpp | 186 +-- test/unittest/UTTest_device_manager_impl.h | 1 + .../UTTest_device_manager_impl_three.cpp | 93 +- .../UTTest_device_manager_impl_two.cpp | 434 +----- .../UTTest_device_manager_service.cpp | 35 +- .../UTTest_device_manager_service_impl.cpp | 51 +- .../UTTest_device_manager_service_three.cpp | 8 +- .../UTTest_device_manager_service_two.cpp | 45 +- .../mock/deviceprofile_connector_mock.cpp | 9 +- .../mock/deviceprofile_connector_mock.h | 9 +- .../mock/dm_auth_message_processor_mock.cpp | 32 + .../mock/dm_auth_message_processor_mock.h | 34 + .../mock/dm_auth_state_machine_mock.cpp | 27 + .../mock/dm_auth_state_machine_mock.h | 33 + .../mock/hichain_auth_connector_mock.cpp | 48 +- .../mock/hichain_auth_connector_mock.h | 30 +- .../unittest/mock/os_account_manager_mock.cpp | 5 + test/unittest/mock/os_account_manager_mock.h | 2 + .../unittest/mock/permission_manager_mock.cpp | 6 + test/unittest/mock/permission_manager_mock.h | 2 + test/unittest/mock/softbus_connector_mock.cpp | 5 + test/unittest/mock/softbus_connector_mock.h | 2 + test/unittest/mock/softbus_session_mock.cpp | 15 + test/unittest/mock/softbus_session_mock.h | 7 + utils/src/crypto/dm_crypto.cpp | 6 +- 135 files changed, 14343 insertions(+), 1502 deletions(-) create mode 100644 services/implementation/include/authentication_v2/auth_manager.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_context.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_manager_base.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_message_processor.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_state.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_state_machine.h create mode 100644 services/implementation/include/authentication_v2/dm_negotiate_process.h create mode 100644 services/implementation/src/authentication_v2/auth_manager.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_context.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_manager_base.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_message_processor.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_state.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_state_machine.cpp create mode 100644 services/implementation/src/authentication_v2/dm_negotiate_process.cpp create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml create mode 100644 test/unittest/UTTest_auth_credential_state.cpp create mode 100644 test/unittest/UTTest_auth_credential_state.h create mode 100644 test/unittest/UTTest_auth_negotiate_state.cpp create mode 100644 test/unittest/UTTest_auth_negotiate_state.h create mode 100644 test/unittest/UTTest_auth_pin_auth_state.cpp create mode 100644 test/unittest/UTTest_auth_pin_auth_state.h create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.cpp create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.h create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.cpp create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.h diff --git a/bundle.json b/bundle.json index 769e15000..2f4868a16 100644 --- a/bundle.json +++ b/bundle.json @@ -59,7 +59,8 @@ "resource_management", "wifi", "screenlock_mgr", - "mbedtls" + "mbedtls", + "zlib" ], "third_party": [] }, @@ -98,8 +99,17 @@ ], "header_base": "//foundation/distributedhardware/device_manager/interfaces/mini_tools_kits/native_cpp/include" } - },{ + }, { "name": "//foundation/distributedhardware/device_manager/interfaces/cj/kits:cj_distributed_device_manager_ffi" + }, { + "type": "so", + "name": "//foundation/distributedhardware/device_manager/json:devicemanagerjson", + "header": { + "header_files": [ + "json_object.h" + ], + "header_base": "//foundation/distributedhardware/device_manager/json/include" + } }], "test": [ "//foundation/distributedhardware/device_manager:device_manager_test" diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index aa2c98547..5ba9498fd 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -47,6 +47,7 @@ int64_t StringToInt64(const std::string &str, int32_t base); void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); +bool GetVersionNumber(const std::string dmVersion, int32_t &versionNum); std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId); std::string GetCallerPkgName(const std::string &pkgName); uint16_t GetSubscribeId(const std::string &pkgName); diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 2d2b96fe2..2a7c075ae 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -22,7 +22,7 @@ enum { DM_OK = 0, SOFTBUS_OK = 0, STOP_BIND = 1, - + DM_ALREADY_AUTHED = 2, /* Transfer to the other end device, not define specification error code */ ERR_DM_NOT_SYSTEM_APP = 202, ERR_DM_TIME_OUT = -20001, @@ -121,6 +121,19 @@ enum { ERR_DM_PROCESS_SESSION_KEY_FAILED = 96929833, ERR_DM_HILINKSVC_SCAS_CHECK_FAILED = 96929834, ERR_DM_FIND_NETWORKID_LIST_EMPTY = 96929835, + ERR_DM_GET_SESSION_KEY_FAILED = 96929836, + ERR_DM_QUADRUPLE_NOT_SAME = 96929837, + ERR_DM_NEXT_STATE_INVALID = 96929838, + ERR_DM_LOGIC_SESSION_CREATE_FAILED = 96929839, + ERR_DM_SESSION_CLOSED = 96929840, + ERR_DM_GET_LOCAL_USERID_FAILED = 969298341, + ERR_DM_CAPABILITY_NEGOTIATE_FAILED = 969298342, + ERR_DM_BIND_TRUST_TARGET = 969298343, + ERR_DM_BINDTARGET_SCREEN_LOCK = 969298344, + ERR_DM_NO_REPLAY = 969298345, + ERR_DM_GET_TOKENID_FAILED = 969298346, + ERR_DM_SHOW_CONFIRM_FAILED = 969298347, + ERR_DM_PARSE_MESSAGE_FAILED = 969298348, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 15d940b42..e2ac8903f 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -299,6 +299,24 @@ bool CompareVersion(const std::string &remoteVersion, const std::string &oldVers return CompareVecNum(remoteVersionVec, oldVersionVec); } +bool GetVersionNumber(const std::string dmVersion, int32_t &versionNum) +{ + LOGI("dmVersion %{public}s,", dmVersion.c_str()); + std::string number = ""; + std::istringstream iss(dmVersion); + std::string item = ""; + while (getline(iss, item, '.')) { + number += item; + } + LOGI("number %{public}s,", number.c_str()); + versionNum = atoi(number.c_str()); + if (versionNum <= 0) { + LOGE("convert failed, number: %{public}s,", number.c_str()); + return false; + } + return true; +} + std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId) { std::string strTemp = pkgName + "#" + std::to_string(subscribeId); diff --git a/commondependency/BUILD.gn b/commondependency/BUILD.gn index ae610b2c7..4f6e88b55 100644 --- a/commondependency/BUILD.gn +++ b/commondependency/BUILD.gn @@ -72,6 +72,7 @@ ohos_shared_library("devicemanagerdependency") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${json_path}:devicemanagerjson", "${utils_path}:devicemanagerutils", ] @@ -81,7 +82,6 @@ ohos_shared_library("devicemanagerdependency") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_core", "os_account:libaccountkits", "samgr:samgr_proxy", @@ -141,6 +141,7 @@ ohos_shared_library("devicemanagerdependencytest") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${json_path}:devicemanagerjson", "${utils_path}:devicemanagerutils", ] @@ -150,7 +151,6 @@ ohos_shared_library("devicemanagerdependencytest") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_core", "os_account:libaccountkits", "samgr:samgr_proxy", diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index f0f697595..82470a301 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -22,7 +22,6 @@ #include "dm_single_instance.h" #include "i_dp_inited_callback.h" #include "local_service_info.h" -#include "parameter.h" #include "trusted_device_info.h" enum AllowAuthType { @@ -36,15 +35,23 @@ EXPORT extern const uint32_t APP_ACROSS_ACCOUNT_TYPE; EXPORT extern const uint32_t DEVICE_PEER_TO_PEER_TYPE; EXPORT extern const uint32_t DEVICE_ACROSS_ACCOUNT_TYPE; EXPORT extern const uint32_t IDENTICAL_ACCOUNT_TYPE; +EXPORT extern const uint32_t SERVICE_PEER_TO_PEER_TYPE; +EXPORT extern const uint32_t SERVICE_ACROSS_ACCOUNT_TYPE; -EXPORT extern const uint32_t DM_IDENTICAL_ACCOUNT; -EXPORT extern const uint32_t DM_POINT_TO_POINT; -EXPORT extern const uint32_t DM_ACROSS_ACCOUNT; -EXPORT extern const uint32_t DM_INVALIED_BINDTYPE; -EXPORT extern const uint32_t DEVICE; +EXPORT extern const uint32_t DM_INVALIED_TYPE; +EXPORT extern const uint32_t USER; EXPORT extern const uint32_t SERVICE; EXPORT extern const uint32_t APP; +extern const char* TAG_PEER_BUNDLE_NAME; +extern const char* TAG_PEER_TOKENID; + +const uint32_t DM_IDENTICAL_ACCOUNT = 1; +const uint32_t DM_SHARE = 2; +const uint32_t DM_LNN = 3; +const uint32_t DM_POINT_TO_POINT = 256; +const uint32_t DM_ACROSS_ACCOUNT = 1282; + enum ProfileState { INACTIVE = 0, ACTIVE = 1 @@ -90,8 +97,10 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; std::vector processVec; + std::vector credIdVec; + std::vector skIdVec; int32_t leftAclNumber; - int32_t peerUserId; + bool isLnnAcl = false; } DmOfflineParam; namespace OHOS { @@ -114,8 +123,12 @@ public: class DeviceProfileConnector : public IDeviceProfileConnector { DM_DECLARE_SINGLE_INSTANCE(DeviceProfileConnector); public: + EXPORT DmOfflineParam DeleteAccessControlListV2(uint32_t tokenId, const std::string &localDeviceId, + const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra); EXPORT std::vector GetAccessControlProfile(); + EXPORT DmOfflineParam HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId); std::vector GetAccessControlProfileByUserId(int32_t userId); std::vector GetAclProfileByDeviceIdAndUserId( const std::string &deviceId, int32_t userId); @@ -134,8 +147,7 @@ public: int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); EXPORT bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); - EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId, std::vector peerUdids, - std::multimap &peerUserIdMap); + EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); EXPORT void DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, std::vector &userIds); EXPORT DmOfflineParam DeleteAccessControlList(const std::string &pkgName, @@ -149,7 +161,7 @@ public: const std::string &deviceId); EXPORT bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); - EXPORT uint32_t DeleteTimeOutAcl(const std::string &deviceId, int32_t &peerUserId); + EXPORT uint32_t DeleteTimeOutAcl(const std::string &deviceId); EXPORT int32_t GetTrustNumber(const std::string &deviceId); bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); std::vector CompareBindType(std::vector profiles, @@ -167,13 +179,12 @@ public: int32_t userId, const std::string &accountId, const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); - EXPORT int32_t HandleDevUnBindEvent(int32_t remoteUserId, - const std::string &remoteUdid, const std::string &localUdid); - EXPORT DmOfflineParam HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid); - EXPORT DmOfflineParam HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, - int32_t peerTokenId); + EXPORT int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid, DmOfflineParam &offlineParam); + EXPORT DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid); + EXPORT DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid, int32_t peerTokenId); EXPORT std::vector GetAllAccessControlProfile(); EXPORT void DeleteAccessControlById(int64_t accessControlId); @@ -186,7 +197,8 @@ public: const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); EXPORT void HandleUserSwitched( const std::vector &activeProfiles, - const std::vector &inActiveProfiles); + const std::vector &inActiveProfiles, + const std::vector &delActiveProfiles); EXPORT void HandleSyncForegroundUserIdEvent( const std::vector &remoteUserIds, const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid); @@ -207,6 +219,7 @@ public: const std::vector &localUserIds, std::string &localUdid); EXPORT void HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); + EXPORT int32_t DeleteSessionKey(int32_t userId, int32_t sessionKeyId); EXPORT int32_t SubscribeDeviceProfileInited( sptr dpInitedCallback); EXPORT int32_t UnSubscribeDeviceProfileInited(); @@ -225,11 +238,25 @@ public: EXPORT int32_t GetLocalServiceInfoByBundleNameAndPinExchangeType( const std::string &bundleName, int32_t pinExchangeType, DistributedDeviceProfile::LocalServiceInfo &localServiceInfo); - EXPORT int32_t PutSessionKey(const std::vector &sessionKeyArray, + EXPORT int32_t PutSessionKey(int32_t userId, const std::vector &sessionKeyArray, int32_t &sessionKeyId); int32_t HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid); int32_t HandleUserStop(int32_t stopUserId, const std::string &localUdid, const std::vector &acceptEventUdids); + EXPORT std::string IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId); + std::vector GetAclProfileByDeviceIdAndUserId( + const std::string &deviceId, int32_t userId, const std::string &remoteDeviceId); + std::vector GetAclList(const std::string localUdid, + int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId); + bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &acLStrList); + std::string AccessToStr(DistributedDeviceProfile::AccessControlProfile acl); + int32_t GetAclListHashStr(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string dmVersion, std::string &aclList); + int32_t GetAclListHashStr(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); + bool IsLnnAcl(const DistributedDeviceProfile::AccessControlProfile &profile); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -269,6 +296,23 @@ private: bool CheckAclStatusNotMatch(const DistributedDeviceProfile::AccessControlProfile &profile, const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); + void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra); + void DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + std::string GetAppServiceAuthVersionInfo(std::string localUdid, std::string remoteUdid, int32_t tokenId, + int32_t userId, std::vector profiles); + std::string GetDeviceAuthVersionInfo(std::string localUdid, std::string remoteUdid, + std::vector profiles); + void DeleteDeviceBindLevelV2(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void ParseExtra(const std::string &extra, uint64_t &peerTokenId, std::string &peerBundleName); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index a96752c43..8d24824d9 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -83,7 +83,7 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountId(void); - + /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountName * @tc.desc: Set Switch Old AccountName of the Multiple User Connector @@ -108,6 +108,7 @@ public: EXPORT static void SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo); EXPORT static DMAccountInfo GetAccountInfoByUserId(int32_t userId); EXPORT static void DeleteAccountInfoByUserId(int32_t userId); + EXPORT static void GetTokenId(uint32_t &tokenId); EXPORT static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); EXPORT static void GetCallerUserId(int32_t &userId); @@ -121,6 +122,8 @@ public: EXPORT static void ClearLockedUser(std::vector &foregroundUserVec, std::vector &backgroundUserVec); EXPORT static DMAccountInfo GetCurrentDMAccountInfo(); + EXPORT static void GetCallingTokenId(uint32_t &tokenId); + EXPORT static int32_t GetUserIdByDisplayId(uint64_t displayId); private: static int32_t oldUserId_; static std::string accountId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index bb48d6c15..ac81fa165 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "deviceprofile_connector.h" #include "crypto_mgr.h" #include "dm_anonymous.h" @@ -31,19 +33,544 @@ const uint32_t APP_ACROSS_ACCOUNT_TYPE = 2; const uint32_t DEVICE_PEER_TO_PEER_TYPE = 3; const uint32_t DEVICE_ACROSS_ACCOUNT_TYPE = 4; const uint32_t IDENTICAL_ACCOUNT_TYPE = 5; +const uint32_t SERVICE_PEER_TO_PEER_TYPE = 6; +const uint32_t SERVICE_ACROSS_ACCOUNT_TYPE = 7; -const uint32_t DM_IDENTICAL_ACCOUNT = 1; -const uint32_t DM_POINT_TO_POINT = 256; -const uint32_t DM_ACROSS_ACCOUNT = 1282; -const uint32_t DM_INVALIED_BINDTYPE = 2048; -const uint32_t DEVICE = 1; +const uint32_t DM_INVALIED_TYPE = 2048; const uint32_t SERVICE = 2; const uint32_t APP = 3; +const uint32_t USER = 1; constexpr uint32_t MAX_SESSION_KEY_LENGTH = 512; +const char* TAG_PEER_BUNDLE_NAME = "peerBundleName"; +const char* TAG_PEER_TOKENID = "peerTokenId"; +constexpr const int32_t DM_HASH_LEN = 32; +const char* TAG_ACL = "accessControlTable"; +const char* TAG_DMVERSION = "dmVersion"; + +namespace { + // Accesser table content is used for ACL synchronization. + const char* TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; + const char* TAG_ACCESSER_USER_ID = "accesserUserId"; + const char* TAG_ACCESSER_ACOUNT_ID = "accesserAcountId"; + const char* TAG_ACCESSER_TOKEN_ID = "accesserTokenId"; + const char* TAG_ACCESSER_SERVICE_NAME = "accesserServiceName"; + const char* TAG_ACCESSER_BUNDLE_NAME = "accesserBundleName"; + const char* TAG_ACCESSER_HAP_SIGNATURE = "accesserHapSignature"; + const char* TAG_ACCESSER_BIND_LEVEL = "accesserBindLevel"; + const char* TAG_ACCESSER_CREDENTIAL_ID = "accesserCredetialId"; + const char* TAG_ACCESSER_STATUS = "accesserStatus"; + const char* TAG_ACCESSER_SK_ID = "accesserSessionKeyId"; + const char* TAG_ACCESSER_SK_TIMESTAMP = "accesserSKTimeStamp"; + + // Accessee table content is used for ACL synchronization. + const char* TAG_ACCESSEE_DEVICE_ID = "accesseeDeviceId"; + const char* TAG_ACCESSEE_USER_ID = "accesseeUserId"; + const char* TAG_ACCESSEE_ACOUNT_ID = "accesseeAcountId"; + const char* TAG_ACCESSEE_TOKEN_ID = "accesseeTokenId"; + const char* TAG_ACCESSEE_SERVICE_NAME = "accesseeServiceName"; + const char* TAG_ACCESSEE_BUNDLE_NAME = "accesseeBundleName"; + const char* TAG_ACCESSEE_HAP_SIGNATURE = "accesseeHapSignature"; + const char* TAG_ACCESSEE_BIND_LEVEL = "accesseeBindLevel"; + const char* TAG_ACCESSEE_CREDENTIAL_ID = "accesseeCredetialId"; + const char* TAG_ACCESSEE_STATUS = "accesseeStatus"; + const char* TAG_ACCESSEE_SK_ID = "accesseeSessionKeyId"; + const char* TAG_ACCESSEE_SK_TIMESTAMP = "accesseeSKTimeStamp"; +}; + namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceProfileConnector); +int32_t DeviceProfileConnector::GetAclListHashStr(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + std::string extraInfo = ""; + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == localUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + item.GetAccessee().GetAccesseeUserId() == remoteUserId) { + extraInfo = item.GetAccesser().GetAccesserExtraData(); + continue; + } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == localUserId) { + extraInfo = item.GetAccessee().GetAccesseeExtraData(); + continue; + } + } + JsonObject extraInfoJson(extraInfo); + if (extraInfoJson.IsDiscarded()) { + LOGE("GetAclListHashStr extraInfoJson error"); + return ERR_DM_FAILED; + } + if (!extraInfoJson[TAG_DMVERSION].IsString()) { + LOGE("GetAclListHashStr PARAM_KEY_OS_VERSION error"); + return ERR_DM_FAILED; + } + std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get(); + return GetAclListHashStr(localUdid, localUserId, remoteUdid, remoteUserId, dmVersion, aclList); +} + +int32_t DeviceProfileConnector::GetAclListHashStr(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string dmVersion, std::string &aclList) +{ + JsonObject jsonAclListObj; + jsonAclListObj[TAG_DMVERSION] = dmVersion; + + // Query ACL. + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + std::vector aclStrVec; + // Traverse the ACL table to find historical ACL records at both ends. + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == localUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + item.GetAccessee().GetAccesseeUserId() == remoteUserId) { + // Save the digest using SHA256. + uint8_t aclHash[DM_HASH_LEN + 1] = {0}; + std::string aclStr = AccessToStr(item); + Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), aclHash, DM_HASH_LEN, 0); + aclStrVec.push_back(reinterpret_cast(aclHash)); + continue; + } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == localUserId) { + uint8_t aclHash[DM_HASH_LEN + 1] = {0}; + std::string aclStr = AccessToStr(item); + Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), aclHash, DM_HASH_LEN, 0); + aclStrVec.push_back(reinterpret_cast(aclHash)); + continue; + } + } + if (aclStrVec.empty()) { + LOGI("DeviceProfileConnector:: acl list is empty"); + } + + jsonAclListObj[TAG_ACL] = aclStrVec; + aclList = jsonAclListObj.Dump(); + return DM_OK; +} + +bool DeviceProfileConnector::ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &acLStrList) +{ + uint8_t aclHash[DM_HASH_LEN + 1] = {0}; + std::string aclStr = AccessToStr(acl); + Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), aclHash, DM_HASH_LEN, 0); + std::vector aclStrVec; + aclStrVec.push_back(reinterpret_cast(aclHash)); + + JsonObject jsonAcl; + jsonAcl[TAG_ACL] = aclStrVec; + std::vector jsonAclStrVec; + jsonAcl[TAG_ACL].Get(jsonAclStrVec); + auto aclIter = find(acLStrList.begin(), acLStrList.end(), jsonAclStrVec[0]); + return (aclIter != acLStrList.end()); +} + +std::string DeviceProfileConnector::AccessToStr(DistributedDeviceProfile::AccessControlProfile acl) +{ + JsonObject jsonAcLObj; + DistributedDeviceProfile::Accesser accesser = acl.GetAccesser(); + jsonAcLObj[TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); + jsonAcLObj[TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); + jsonAcLObj[TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); + jsonAcLObj[TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); + jsonAcLObj[TAG_ACCESSER_SERVICE_NAME] = std::vector(); // Reserved field + jsonAcLObj[TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); + jsonAcLObj[TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); + jsonAcLObj[TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); + jsonAcLObj[TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserCredentialIdStr(); + jsonAcLObj[TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); + jsonAcLObj[TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); + jsonAcLObj[TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); + //TODO accessee + DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); + jsonAcLObj[TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); + jsonAcLObj[TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); + jsonAcLObj[TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); + jsonAcLObj[TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); + jsonAcLObj[TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // Reserved field + jsonAcLObj[TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); + jsonAcLObj[TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); + jsonAcLObj[TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); + jsonAcLObj[TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeCredentialIdStr(); + jsonAcLObj[TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); + jsonAcLObj[TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); + jsonAcLObj[TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); + + return jsonAcLObj.Dump(); +} + +std::vector DeviceProfileConnector::GetAclList( + const std::string localUdid, int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId) +{ + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector aclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == localUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + item.GetAccessee().GetAccesseeUserId() == remoteUserId) { + aclList.push_back(item); + continue; + } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == localUserId) { + aclList.push_back(item); + continue; + } + } + if (aclList.empty()) { + LOGI("DeviceProfileConnector::GetAclList acl is empty"); + } + return aclList; +} + +EXPORT std::string DeviceProfileConnector::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { + LOGE("Invalied bindlevel bindLevel=%{public}u.", bindLevel); + return ""; + } + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localUdid, userId); + if (profiles.empty()) { + LOGE("Acl is empty."); + return ""; + } + switch (bindLevel) { + case APP: + case SERVICE: + return GetAppServiceAuthVersionInfo(localUdid, remoteUdid, tokenId, userId, profiles); + case USER: + return GetDeviceAuthVersionInfo(localUdid, remoteUdid, profiles); + default: + break; + } + return ""; +} + +std::string DeviceProfileConnector::GetAppServiceAuthVersionInfo(std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId, std::vector profiles) +{ + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || + (item.GetBindLevel() != APP && item.GetBindLevel() != SERVICE)) { + continue; + } + int32_t acerUserId = item.GetAccesser().GetAccesserUserId(); + int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t acerTokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + int32_t aceeTokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); + if (acerUserId == userId && acerTokenId == tokenId && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + return item.GetAccesser().GetAccesserExtraData(); + } + if (aceeUserId == userId && aceeTokenId == tokenId && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + return item.GetAccessee().GetAccesseeExtraData(); + } + } + return ""; +} + +std::string DeviceProfileConnector::GetDeviceAuthVersionInfo(std::string localUdid, std::string remoteUdid, + std::vector profiles) +{ + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != USER || IsLnnAcl(item)) { + continue; + } + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if (acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + return item.GetAccesser().GetAccesserExtraData(); + } + if (aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + return item.GetAccessee().GetAccesseeExtraData(); + } + } + return ""; +} +EXPORT DmOfflineParam DeviceProfileConnector::DeleteAccessControlListV2(uint32_t tokenId, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra) +{ + LOGI("localDeviceId %{public}s, remoteDeviceId %{public}s, bindLevel %{public}d.", + GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); + DmOfflineParam offlineParam; + offlineParam.bindType = INVALIED_TYPE; + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { + LOGE("Invalied bindlevel."); + return offlineParam; + } + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + std::vector profiles = + GetAclProfileByDeviceIdAndUserId(localDeviceId, userId, remoteDeviceId); + if (profiles.empty()) { + LOGE("Acl is empty."); + return offlineParam; + } + switch (bindLevel) { + case APP: + if (extra == "") { + DeleteAppBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + } else { + DeleteAppBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId, extra); + } + break; + case SERVICE: + DeleteServiceBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + break; + case USER: + DeleteDeviceBindLevelV2(offlineParam, profiles, localDeviceId, remoteDeviceId); + break; + default: + LOGE("DeleteAccessControlListV2: Invalied bindlevel."); + break; + } + std::vector leftProfiles = + GetAclProfileByDeviceIdAndUserId(localDeviceId, userId, remoteDeviceId); + if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { + if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localDeviceId) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); + } + if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localDeviceId) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); + } + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); + offlineParam.isLnnAcl = true; + } + return offlineParam; +} + +void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + bindNums++; + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId)) && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId)) && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::ParseExtra(const std::string &extra, uint64_t &peerTokenId, std::string &peerBundleName) +{ + JsonObject extraInfoJson(extra); + if (extraInfoJson.IsDiscarded()) { + LOGE("ParseExtra extraInfoJson error"); + return; + } + if (!extraInfoJson[TAG_PEER_BUNDLE_NAME].IsString() || !extraInfoJson[TAG_PEER_TOKENID].IsString()) { + LOGE("ParseExtra TAG_PEER_BUNDLE_NAME or TAG_PEER_TOKENID error"); + return; + } + peerTokenId = extraInfoJson[TAG_PEER_TOKENID].Get(); + peerBundleName = extraInfoJson[TAG_PEER_BUNDLE_NAME].Get(); +} + +void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra) +{ + LOGI("DeviceProfileConnector::DeleteAppBindLevelV2 extra %{public}s", extra.c_str()); + int32_t bindNums = 0; + int32_t deleteNums = 0; + uint64_t peerTokenId = 0; + std::string peerBundleName; + ParseExtra(extra, peerTokenId, peerBundleName); + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + bindNums++; + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId)) && aceeDeviceId == remoteUdid && + (aceeTokenId == static_cast(peerTokenId)) && acerDeviceId == localUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId)) && acerDeviceId == remoteUdid && + (acerTokenId == static_cast(peerTokenId)) && aceeDeviceId == localUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + bindNums++; + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId)) && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId)) && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteDeviceBindLevelV2(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || IsLnnAcl(item)) { + continue; + } + bindNums++; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} EXPORT std::vector DeviceProfileConnector::GetAccessControlProfile() { @@ -90,6 +617,25 @@ std::vector DeviceProfileConnector::GetAclProfileByDeviceI return aclProfileVec; } +std::vector DeviceProfileConnector::GetAclProfileByDeviceIdAndUserId(const std::string &deviceId, + int32_t userId, const std::string &remoteDeviceId) +{ + + std::vector aclProfileVec; + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && + item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == remoteDeviceId) || + (item.GetAccessee().GetAccesseeDeviceId() == deviceId && + item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == remoteDeviceId)) { + aclProfileVec.push_back(item); + } + } + return aclProfileVec; +} + EXPORT std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList( const std::string &pkgName, const std::string &deviceId) { @@ -97,10 +643,10 @@ EXPORT std::unordered_map DeviceProfileConnector::GetAp std::vector profiles = GetAclProfileByDeviceIdAndUserId(deviceId, userId); std::vector profilesFilter = {}; for (auto &item : profiles) { - if ((item.GetAccesser().GetAccesserUserId() == userId && + if (!IsLnnAcl(item) && ((item.GetAccesser().GetAccesserUserId() == userId && item.GetAccesser().GetAccesserDeviceId() == deviceId) || (item.GetAccessee().GetAccesseeUserId() == userId && - item.GetAccessee().GetAccesseeDeviceId() == deviceId)) { + item.GetAccessee().GetAccesseeDeviceId() == deviceId))) { profilesFilter.push_back(item); } } @@ -146,7 +692,7 @@ int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceIdHash).c_str()); continue; } - if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || + if (IsLnnAcl(item) || static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || (discoveryInfo.localDeviceId == item.GetAccesser().GetAccesserDeviceId() && discoveryInfo.userId != item.GetAccesser().GetAccesserUserId()) || (discoveryInfo.localDeviceId == item.GetAccessee().GetAccesseeDeviceId() && @@ -184,10 +730,14 @@ int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, int32_t DeviceProfileConnector::CheckAuthForm(DmAuthForm form, AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo) { - if (profiles.GetBindLevel() == DEVICE || (profiles.GetBindLevel() == APP && discoveryInfo.pkgname == "")) { + if (IsLnnAcl(profiles)) { + return DmAuthForm::INVALID_TYPE; + } + if (profiles.GetBindLevel() == USER || ((profiles.GetBindLevel() == APP || profiles.GetBindLevel() == SERVICE) && + discoveryInfo.pkgname == "")) { return form; } - if (profiles.GetBindLevel() == APP) { + if (profiles.GetBindLevel() == APP || profiles.GetBindLevel() == SERVICE) { if (discoveryInfo.pkgname == profiles.GetAccesser().GetAccesserBundleName() && discoveryInfo.localDeviceId == profiles.GetAccesser().GetAccesserDeviceId()) { return form; @@ -222,7 +772,7 @@ EXPORT uint32_t DeviceProfileConnector::CheckBindType(std::string peerUdid, LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); uint32_t highestPriority = INVALIED_TYPE; for (auto &item : filterProfiles) { - if (peerUdid != item.GetTrustDeviceId()) { + if (IsLnnAcl(item) || peerUdid != item.GetTrustDeviceId()) { continue; } uint32_t priority = static_cast(GetAuthForm(item, peerUdid, localUdid)); @@ -240,21 +790,30 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont profiles.GetBindType(), profiles.GetBindLevel()); uint32_t priority = INVALIED_TYPE; uint32_t bindType = profiles.GetBindType(); + switch (bindType) { case DM_IDENTICAL_ACCOUNT: priority = IDENTICAL_ACCOUNT_TYPE; break; case DM_POINT_TO_POINT: - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP) { + } + if (profiles.GetBindLevel() == SERVICE) { + priority = SERVICE_PEER_TO_PEER_TYPE; + } + if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { priority = DEVICE_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP) { + } + if (profiles.GetBindLevel() == SERVICE) { + priority = SERVICE_ACROSS_ACCOUNT_TYPE; + } + if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; } break; @@ -279,7 +838,7 @@ EXPORT std::vector DeviceProfileConnector::GetBindTypeByPkgName( GetAccessControlProfileByUserId(MultipleUserConnector::GetFirstForegroundUserId()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { - if (trustUdid != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { + if (IsLnnAcl(item) || trustUdid != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { continue; } GetParamBindTypeVec(item, requestDeviceId, bindTypeVec, trustUdid); @@ -323,7 +882,7 @@ void DeviceProfileConnector::GetParamBindTypeVec(AccessControlProfile profile, s bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); break; case DM_POINT_TO_POINT: - if (profile.GetBindLevel() == DEVICE) { + if (profile.GetBindLevel() == USER) { bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); } if (profile.GetBindLevel() == APP) { @@ -331,7 +890,7 @@ void DeviceProfileConnector::GetParamBindTypeVec(AccessControlProfile profile, s } break; case DM_ACROSS_ACCOUNT: - if (profile.GetBindLevel() == DEVICE) { + if (profile.GetBindLevel() == USER) { bindTypeVec.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); } if (profile.GetBindLevel() == APP) { @@ -349,7 +908,8 @@ std::vector DeviceProfileConnector::CompareBindType(std::vector bindTypeIndex; for (uint32_t index = 0; index < profiles.size(); index++) { - if (profiles[index].GetTrustDeviceId() != targetDeviceId || profiles[index].GetStatus() != ACTIVE) { + if (IsLnnAcl(profiles[index]) || profiles[index].GetTrustDeviceId() != targetDeviceId || + profiles[index].GetStatus() != ACTIVE) { continue; } DmDiscoveryInfo paramInfo = { @@ -369,7 +929,7 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, std: bindTypeIndex.push_back(index); } if (profiles.GetBindType() == DM_POINT_TO_POINT) { - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { sinkBindType.push_back(DEVICE_PEER_TO_PEER_TYPE); bindTypeIndex.push_back(index); } @@ -387,7 +947,7 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, std: } } if (profiles.GetBindType() == DM_ACROSS_ACCOUNT) { - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { sinkBindType.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); bindTypeIndex.push_back(index); } @@ -434,7 +994,7 @@ EXPORT std::vector DeviceProfileConnector::SyncAclByBindType( return bindType; } -EXPORT +EXPORT std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { @@ -443,7 +1003,7 @@ std::vector DeviceProfileConnector::GetP LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); std::vector processInfoVec; for (auto &item : filterProfiles) { - if (item.GetTrustDeviceId() != targetDeviceId) { + if (IsLnnAcl(item) || item.GetTrustDeviceId() != targetDeviceId) { continue; } std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); @@ -546,31 +1106,18 @@ EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( } EXPORT void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, - int32_t userId, std::vector peerUdids, std::multimap &peerUserIdMap) + int32_t userId) { LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), userId); std::vector profiles = GetAccessControlProfileByUserId(userId); for (const auto &item : profiles) { - if (find(peerUdids.begin(), peerUdids.end(), item.GetTrustDeviceId()) == peerUdids.end()) { - continue; - } std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); - if (accesserUdid == localUdid && accesserUserId == userId) { + if ((accesserUdid == localUdid && accesserUserId == userId) || + (accesseeUdid == localUdid && accesseeUserId == userId)) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (!IsValueExist(peerUserIdMap, accesseeUdid, accesseeUserId)) { - peerUserIdMap.insert(std::pair(accesseeUdid, accesseeUserId)); - } - continue; - } - if (accesseeUdid == localUdid && accesseeUserId == userId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (!IsValueExist(peerUserIdMap, accesserUdid, accesserUserId)) { - peerUserIdMap.insert(std::pair(accesserUdid, accesserUserId)); - } - continue; } } } @@ -587,13 +1134,13 @@ EXPORT void DeviceProfileConnector::DeleteAclForRemoteUserRemoved( int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); if (accesserUdid == peerUdid && accesserUserId == peerUserId) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIds.push_back(accesseeUserId); } } if (accesseeUdid == peerUdid && accesseeUserId == peerUserId) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIds.push_back(accesserUserId); } } @@ -624,7 +1171,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; - if (static_cast(bindLevel) > APP || static_cast(bindLevel) < DEVICE) { + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { LOGE("Invalied bindlevel."); return offlineParam; } @@ -645,7 +1192,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string case SERVICE: DeleteServiceBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); break; - case DEVICE: + case USER: DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); break; default: @@ -675,7 +1222,6 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.peerUserId = item.GetAccessee().GetAccesseeUserId(); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -691,8 +1237,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.peerUserId = item.GetAccesser().GetAccesserUserId(); - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -708,7 +1253,9 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co LOGI("DeviceProfileConnector::DeleteAppBindLevel extra %{public}s", extra.c_str()); int32_t bindNums = 0; int32_t deleteNums = 0; - std::string peerBundleName = extra; + uint64_t peerTokenId = 0; + std::string peerBundleName; + ParseExtra(extra, peerTokenId, peerBundleName); for (auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -726,7 +1273,6 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.peerUserId = item.GetAccessee().GetAccesseeUserId(); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -743,8 +1289,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.peerUserId = item.GetAccesser().GetAccesserUserId(); - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -767,7 +1312,9 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; - offlineParam.bindType = DEVICE; + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -776,8 +1323,10 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; - offlineParam.bindType = DEVICE; - LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } @@ -813,7 +1362,7 @@ void DeviceProfileConnector::DeleteServiceBindLevel(DmOfflineParam &offlineParam DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -853,7 +1402,7 @@ EXPORT bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind( LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && (item.GetAccessee().GetAccesseeBundleName() == pkgName || + item.GetBindLevel() == USER && (item.GetAccessee().GetAccesseeBundleName() == pkgName || item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccessee().GetAccesseeUserId() == 0 && item.GetAccessee().GetAccesseeAccountId() == "") { return true; @@ -868,7 +1417,7 @@ bool DeviceProfileConnector::CheckSinkDevIdInAclForDevBind(const std::string &pk LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetBindLevel() == USER && (item.GetAccesser().GetAccesserBundleName() == pkgName || item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccesser().GetAccesserUserId() == 0 && item.GetAccesser().GetAccesserAccountId() == "") { return true; @@ -882,15 +1431,11 @@ bool DeviceProfileConnector::CheckDevIdInAclForDevBind(const std::string &pkgNam return (CheckSinkDevIdInAclForDevBind(pkgName, deviceId) || CheckSrcDevIdInAclForDevBind(pkgName, deviceId)); } -EXPORT uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId, int32_t &peerUserId) +EXPORT uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) { std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t res = 0; - int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localDeviceId); for (auto &item : profiles) { if (item.GetTrustDeviceId() != deviceId || item.GetStatus() != ACTIVE) { continue; @@ -899,16 +1444,6 @@ EXPORT uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &devi if (item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { res--; DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (item.GetAccesser().GetAccesserUserId() == currentUserId && - item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccessee().GetAccesseeDeviceId() == deviceId) { - peerUserId = item.GetAccessee().GetAccesseeUserId(); - } - if (item.GetAccessee().GetAccesseeUserId() == currentUserId && - item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccesser().GetAccesserDeviceId() == deviceId) { - peerUserId = item.GetAccesser().GetAccesserUserId(); - } } } return res; @@ -1049,18 +1584,18 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A ret = true; break; case DM_POINT_TO_POINT: - if (profile.GetBindLevel() == DEVICE || profile.GetBindLevel() == SERVICE) { + if (profile.GetBindLevel() == USER && !IsLnnAcl(profile)) { ret = true; - } else if (profile.GetBindLevel() == APP && + } else if ((profile.GetBindLevel() == APP || profile.GetBindLevel() == SERVICE) && (profile.GetAccesser().GetAccesserBundleName() == caller.pkgName || profile.GetAccessee().GetAccesseeBundleName() == caller.pkgName)) { ret = CheckAppLevelAccess(profile, caller, callee); } break; case DM_ACROSS_ACCOUNT: - if (profile.GetBindLevel() == DEVICE || profile.GetBindLevel() == SERVICE) { + if (profile.GetBindLevel() == USER && !IsLnnAcl(profile)) { ret = true; - } else if (profile.GetBindLevel() == APP && + } else if ((profile.GetBindLevel() == APP || profile.GetBindLevel() == SERVICE) && (profile.GetAccesser().GetAccesserBundleName() == caller.pkgName || profile.GetAccessee().GetAccesseeBundleName() == caller.pkgName)) { ret = CheckAppLevelAccess(profile, caller, callee); @@ -1150,6 +1685,9 @@ std::map DeviceProfileConnector::GetDeviceIdAndBindLevel(s std::vector profiles = GetAllAccessControlProfile(); std::map deviceIdMap; for (const auto &item : profiles) { + if (IsLnnAcl(item)) { + continue; + } if (find(userIds.begin(), userIds.end(), item.GetAccesser().GetAccesserUserId()) != userIds.end() && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Get Device Bind type localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); @@ -1212,7 +1750,7 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfileByUserId(remoteUserId); - int32_t bindType = DM_INVALIED_BINDTYPE; + int32_t bindType = DM_INVALIED_TYPE; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { continue; @@ -1235,13 +1773,13 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, return bindType; } -EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, - const std::string &remoteUdid, const std::string &localUdid) +EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid, DmOfflineParam &offlineParam) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); - int32_t bindType = DM_INVALIED_BINDTYPE; + int32_t bindType = DM_INVALIED_TYPE; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { continue; @@ -1250,18 +1788,38 @@ EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId bindType = DM_IDENTICAL_ACCOUNT; continue; } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - bindType = std::min(bindType, static_cast(item.GetBindType())); + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } } return bindType; } -EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) +EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); DmOfflineParam offlineParam; int32_t bindNums = 0; int32_t deleteNums = 0; @@ -1273,7 +1831,7 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( bindNums++; if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); @@ -1283,11 +1841,13 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); @@ -1297,20 +1857,35 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); continue; } } offlineParam.leftAclNumber = bindNums - deleteNums; + std::vector leftProfiles = + GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); + if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { + if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); + } + if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); + } + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); + offlineParam.isLnnAcl = true; + } return offlineParam; } -EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, - const std::string &localUdid, int32_t peerTokenId) +EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); DmOfflineParam offlineParam; int32_t bindNums = 0; int32_t deleteNums = 0; @@ -1320,38 +1895,114 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent( continue; } bindNums++; + int32_t acerUserId = item.GetAccesser().GetAccesserUserId(); + int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t acerTokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + int32_t aceeTokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); + if (acerUserId == remoteUserId && acerDeviceId == remoteUdid && aceeDeviceId == localUdid && + (acerTokenId == tokenId) && (aceeTokenId == peerTokenId)) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + continue; + } + if (aceeUserId == remoteUserId && aceeDeviceId == remoteUdid && acerDeviceId == localUdid && + (aceeTokenId == tokenId) && (acerTokenId == peerTokenId)) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; + std::vector leftProfiles = + GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); + if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { + if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); + } + if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); + } + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); + offlineParam.isLnnAcl = true; + } + return offlineParam; +} + +DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); + DmOfflineParam offlineParam; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == peerTokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - deleteNums++; - offlineParam.bindType = APP; + offlineParam.bindType = SERVICE; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && - static_cast(item.GetAccesser().GetAccesserTokenId()) == peerTokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - deleteNums++; - offlineParam.bindType = APP; + offlineParam.bindType = SERVICE; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); continue; } } - offlineParam.leftAclNumber = bindNums - deleteNums; + std::vector leftProfiles = + GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); + if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { + if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); + } + if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { + offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); + } + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); + offlineParam.isLnnAcl = true; + } return offlineParam; } @@ -1381,6 +2032,7 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( std::vector profiles = GetAllAccessControlProfile(); std::vector activeProfiles; std::vector inActiveProfiles; + std::vector delActiveProfiles; for (auto &item : profiles) { if (std::find(deviceVec.begin(), deviceVec.end(), item.GetTrustDeviceId()) == deviceVec.end()) { continue; @@ -1393,6 +2045,9 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( item.SetStatus(INACTIVE); inActiveProfiles.push_back(item); } + if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { + delActiveProfiles.push_back(item); + } continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -1404,17 +2059,21 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( continue; } } - HandleUserSwitched(activeProfiles, inActiveProfiles); + HandleUserSwitched(activeProfiles, inActiveProfiles, delActiveProfiles); return DM_OK; } EXPORT void DeviceProfileConnector::HandleUserSwitched( const std::vector &activeProfiles, - const std::vector &inActiveProfiles) + const std::vector &inActiveProfiles, + const std::vector &delActiveProfiles) { for (auto &item : inActiveProfiles) { DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } + for (auto &item : delActiveProfiles) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } for (auto &item : activeProfiles) { DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } @@ -1478,6 +2137,9 @@ std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::stri std::vector processInfos; int32_t bindLevel = 100; for (const auto &item : profiles) { + if (IsLnnAcl(item)) { + continue; + } ProcessInfo processInfo; std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); @@ -1501,7 +2163,7 @@ std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::stri processInfos.push_back(processInfo); } } - if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { + if (bindLevel == INVALIED_TYPE || bindLevel == USER) { processInfos.clear(); for (const auto &item : localUserIds) { ProcessInfo processInfo; @@ -1521,6 +2183,9 @@ EXPORT std::map DeviceProfileConnector::GetUserIdAndBindLevel( std::vector profiles = GetAllAccessControlProfile(); std::map userIdAndBindLevel; for (const auto &item : profiles) { + if (IsLnnAcl(item)) { + continue; + } std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); @@ -1695,6 +2360,9 @@ EXPORT void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent( item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } + if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } } else if ((accesseeDeviceId == localUdid && accesserDeviceId == remoteUdid) && (find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end() || find(localUserIds.begin(), localUserIds.end(), accesseeUserId) == localUserIds.end())) { @@ -1702,6 +2370,9 @@ EXPORT void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent( item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } + if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } } } } @@ -1778,15 +2449,17 @@ EXPORT int32_t DeviceProfileConnector::CheckDeviceInfoPermission( std::string localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(localUserId); std::vector profiles = GetAccessControlProfileByUserId(localUserId); for (auto &item : profiles) { + if (IsLnnAcl(item)) { + continue; + } if (item.GetTrustDeviceId() == peerDeviceId) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() == DEVICE) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() == USER) { return DM_OK; } } int32_t profileUserId = item.GetAccesser().GetAccesserUserId(); if (item.GetAccesser().GetAccesserDeviceId() == localUdid && (profileUserId == localUserId || profileUserId == -1 || profileUserId == 0) && - item.GetAccesser().GetAccesserAccountId() == localAccountId && item.GetAccesser().GetAccesserTokenId() == localTokenId && item.GetAccessee().GetAccesseeDeviceId() == peerDeviceId) { return DM_OK; @@ -1794,7 +2467,6 @@ EXPORT int32_t DeviceProfileConnector::CheckDeviceInfoPermission( profileUserId = item.GetAccessee().GetAccesseeUserId(); if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && (profileUserId == localUserId || profileUserId == -1 || profileUserId == 0) && - item.GetAccessee().GetAccesseeAccountId() == localAccountId && item.GetAccessee().GetAccesseeTokenId() == localTokenId && item.GetAccesser().GetAccesserDeviceId() == peerDeviceId) { return DM_OK; @@ -1870,14 +2542,26 @@ int32_t DeviceProfileConnector::GetLocalServiceInfoByBundleNameAndPinExchangeTyp return DM_OK; } -int32_t DeviceProfileConnector::PutSessionKey(const std::vector &sessionKeyArray, int32_t &sessionKeyId) +int32_t DeviceProfileConnector::PutSessionKey(int32_t userId, const std::vector &sessionKeyArray, + int32_t &sessionKeyId) { if (sessionKeyArray.empty() || sessionKeyArray.size() > MAX_SESSION_KEY_LENGTH) { LOGE("SessionKey size invalid"); return ERR_DM_FAILED; } - uint32_t userId = static_cast(MultipleUserConnector::GetCurrentAccountUserID()); - int32_t ret = DistributedDeviceProfileClient::GetInstance().PutSessionKey(userId, sessionKeyArray, sessionKeyId); + int32_t ret = DistributedDeviceProfileClient::GetInstance().PutSessionKey(static_cast(userId), + sessionKeyArray, sessionKeyId); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceProfileConnector::DeleteSessionKey(int32_t userId, int32_t sessionKeyId) +{ + int32_t ret = + DistributedDeviceProfileClient::GetInstance().DeleteSessionKey(static_cast(userId), sessionKeyId); if (ret != DM_OK) { LOGE("failed: %{public}d", ret); return ret; @@ -1935,6 +2619,7 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( std::vector profiles = GetAllAccessControlProfile(); std::vector activeProfiles; std::vector inActiveProfiles; + std::vector delActiveProfiles; for (auto &item : profiles) { if (std::find(deviceVec.begin(), deviceVec.end(), item.GetTrustDeviceId()) == deviceVec.end()) { continue; @@ -1949,6 +2634,9 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( item.SetStatus(INACTIVE); inActiveProfiles.push_back(item); } + if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { + delActiveProfiles.push_back(item); + } continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -1962,7 +2650,7 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( continue; } } - HandleUserSwitched(activeProfiles, inActiveProfiles); + HandleUserSwitched(activeProfiles, inActiveProfiles, delActiveProfiles); return DM_OK; } @@ -2005,6 +2693,17 @@ int32_t DeviceProfileConnector::HandleUserStop(int32_t stopUserId, const std::st return DM_OK; } +bool DeviceProfileConnector::IsLnnAcl(const DistributedDeviceProfile::AccessControlProfile &profile) +{ + if (profile.GetBindType() == DM_POINT_TO_POINT && profile.GetBindLevel() == USER && + profile.GetAccesser().GetAccesserTokenId() == 0 && profile.GetAccessee().GetAccesseeTokenId() == 0 && + profile.GetAccesser().GetAccesserBundleName().empty() && + profile.GetAccessee().GetAccesseeBundleName().empty()) { + return true; + } + return false; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 1bcaa8d8e..0b6949ea6 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -122,6 +122,15 @@ void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int userId = GetFirstForegroundUserId(); } +EXPORT void MultipleUserConnector::GetTokenId(uint32_t &tokenId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif +} + void MultipleUserConnector::GetCallerUserId(int32_t &userId) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -363,12 +372,40 @@ EXPORT void MultipleUserConnector::ClearLockedUser( } } -DMAccountInfo MultipleUserConnector::GetCurrentDMAccountInfo() +EXPORT DMAccountInfo MultipleUserConnector::GetCurrentDMAccountInfo() { DMAccountInfo dmAccountInfo; dmAccountInfo.accountId = GetOhosAccountId(); dmAccountInfo.accountName = GetOhosAccountName(); return dmAccountInfo; } + +EXPORT void MultipleUserConnector::GetCallingTokenId(uint32_t &tokenId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif +} + +EXPORT int32_t MultipleUserConnector::GetUserIdByDisplayId(uint64_t displayId) +{ + LOGI("displayId %{public}" PRIu64, displayId); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (displayId == -1) { + userId = GetFirstForegroundUserId(); + return userId; + } +#ifdef OS_ACCOUNT_PART_EXISTS + int32_t ret = OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("GetForegroundOsAccountLocalId failed ret %{public}d.", ret); + } +#endif // OS_ACCOUNT_PART_EXISTS +#endif + return userId; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/i_dm_bind_manager_ext_resident.h b/interfaces/inner_kits/native_cpp/include/i_dm_bind_manager_ext_resident.h index 4478d94cf..030248710 100644 --- a/interfaces/inner_kits/native_cpp/include/i_dm_bind_manager_ext_resident.h +++ b/interfaces/inner_kits/native_cpp/include/i_dm_bind_manager_ext_resident.h @@ -16,6 +16,9 @@ #ifndef OHOS_I_DM_BIND_MANAGER_EXT_RESIDENT_H #define OHOS_I_DM_BIND_MANAGER_EXT_RESIDENT_H +#include +#include + namespace OHOS { namespace DistributedHardware { class IDMBindManagerExtResident { diff --git a/interfaces/inner_kits/native_cpp/include/i_dm_service_impl_ext.h b/interfaces/inner_kits/native_cpp/include/i_dm_service_impl_ext.h index e2855531e..b93d073e4 100644 --- a/interfaces/inner_kits/native_cpp/include/i_dm_service_impl_ext.h +++ b/interfaces/inner_kits/native_cpp/include/i_dm_service_impl_ext.h @@ -16,8 +16,12 @@ #ifndef OHOS_I_DM_SERVICE_IMPL_EXT_H #define OHOS_I_DM_SERVICE_IMPL_EXT_H +#include "dm_device_info.h" +#include "idevice_manager_service_listener.h" #include "i_dm_bind_manager_ext_resident.h" +#include + namespace OHOS { namespace DistributedHardware { class IDMServiceImplExt { diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 6d32598ce..6ace5a13e 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -115,6 +115,7 @@ if (defined(ohos_lite)) { "include/config", "include/adapter", "include/authentication", + "include/authentication_v2", "include/authentication/showconfirm/standard", "include/ability", "include/credential", @@ -182,6 +183,18 @@ if (defined(ohos_lite)) { "src/authentication/auth_ui_state_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/authentication/showconfirm/standard/show_confirm.cpp", + "src/authentication_v2/auth_manager.cpp", + "src/authentication_v2/auth_stages/auth_acl.cpp", + "src/authentication_v2/auth_stages/auth_confirm.cpp", + "src/authentication_v2/auth_stages/auth_credential.cpp", + "src/authentication_v2/auth_stages/auth_negotiate.cpp", + "src/authentication_v2/auth_stages/auth_pin_auth.cpp", + "src/authentication_v2/dm_auth_context.cpp", + "src/authentication_v2/dm_auth_manager_base.cpp", + "src/authentication_v2/dm_auth_message_processor.cpp", + "src/authentication_v2/dm_auth_state.cpp", + "src/authentication_v2/dm_auth_state_machine.cpp", + "src/authentication_v2/dm_negotiate_process.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", @@ -236,8 +249,10 @@ if (defined(ohos_lite)) { "mbedtls:mbedtls_shared", "openssl:libcrypto_shared", "os_account:libaccountkits", + "os_account:os_account_innerkits", "resource_management:resmgr_napi_core", "samgr:samgr_proxy", + "zlib:shared_libz", ] if (support_screenlock && device_manager_feature_product == "default") { diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index dde7dbf83..294243d87 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -27,7 +27,6 @@ namespace OHOS { namespace DistributedHardware { -extern const char* TAG_REPLY; extern const char* TAG_NET_ID; extern const char* TAG_TARGET; extern const char* TAG_APP_OPERATION; @@ -37,7 +36,6 @@ extern const char* TAG_GROUPIDS; extern const char* TAG_CUSTOM_DESCRIPTION; extern const char* TAG_DEVICE_TYPE; extern const char* TAG_REQUESTER; -extern const char* TAG_LOCAL_DEVICE_ID; extern const char* TAG_LOCAL_DEVICE_TYPE; extern const char* TAG_INDEX; extern const char* TAG_SLICE_NUM; @@ -46,38 +44,19 @@ extern const char* TAG_IS_SHOW_DIALOG; extern const char* TAG_TOKEN; extern const char* TAG_CRYPTO_NAME; extern const char* TAG_CRYPTO_VERSION; -extern const char* TAG_IDENTICAL_ACCOUNT; -extern const char* TAG_ACCOUNT_GROUPID; -extern const char* APP_THUMBNAIL; extern const char* QR_CODE_KEY; extern const char* TAG_AUTH_TOKEN; extern const char* NFC_CODE_KEY; extern const char* OLD_VERSION_ACCOUNT; -extern const char* TAG_AUTH_FINISH; -extern const char* TAG_HAVE_CREDENTIAL; extern const char* TAG_PUBLICKEY; extern const char* TAG_SESSIONKEY; -extern const char* TAG_BIND_LEVEL; -extern const char* TAG_LOCAL_USERID; extern const char* TAG_BIND_TYPE_SIZE; -extern const char* TAG_ISONLINE; -extern const char* TAG_AUTHED; -extern const char* TAG_LOCAL_ACCOUNTID; -extern const char* TAG_DMVERSION; extern const char* TAG_HOST_PKGNAME; -extern const char* TAG_TOKENID; extern const char* TAG_HAVECREDENTIAL; extern const char* TAG_CONFIRM_OPERATION; -extern const char* TAG_DATA; -extern const char* TAG_DATA_LEN; extern const char* TAG_IMPORT_AUTH_CODE; -extern const char* TAG_HOST_PKGLABEL; -extern const char* TAG_EDITION; -extern const char* TAG_BUNDLE_NAME; extern const char* TAG_CRYPTIC_MSG; -extern const char* TAG_PEER_BUNDLE_NAME; -extern const char* TAG_REMOTE_DEVICE_NAME; extern const char* TAG_SESSIONKEY_ID; class DmAuthManager; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 3dee55dac..2811a2e5a 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -28,6 +28,7 @@ #include "deviceprofile_connector.h" #include "dm_ability_manager.h" #include "dm_adapter_manager.h" +#include "dm_auth_manager_base.h" #include "dm_constants.h" #include "dm_device_info.h" #include "dm_timer.h" @@ -203,10 +204,7 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; -class DmAuthManager final : public ISoftbusSessionCallback, - public ISoftbusConnectorCallback, - public IHiChainConnectorCallback, - public IDmDeviceAuthCallback, +class DmAuthManager final : public AuthManagerBase, public std::enable_shared_from_this { public: DmAuthManager(std::shared_ptr softbusConnector, @@ -483,7 +481,10 @@ public: * @tc.type: FUNC */ int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam); + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + void ClearSoftbusSessionCallback(); + void PrepareSoftbusSessionCallback(); void HandleSessionHeartbeat(std::string name); @@ -519,7 +520,6 @@ private: bool IsAuthTypeSupported(const int32_t &authType); bool IsAuthCodeReady(const std::string &pkgName); int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); - int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); std::string ParseExtraFromMap(const std::map &bindParam); std::string GenerateBindResultContent(); void InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, @@ -546,6 +546,7 @@ public: void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); int32_t GetSessionKeyIdSync(int64_t requestId); void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); void OnScreenLocked(); @@ -578,7 +579,6 @@ private: void SrcAuthenticateFinish(); std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); - std::string ConvertSrcVersion(const std::string &version, const std::string &edition); std::string ConvertSinkVersion(const std::string &version); void NegotiateRespMsg(const std::string &version); void SetAuthType(int32_t authType); @@ -597,6 +597,7 @@ private: void ProcessReqPublicKey(); int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); private: std::shared_ptr softbusConnector_; @@ -643,6 +644,7 @@ private: std::condition_variable sessionKeyIdCondition_; std::map> sessionKeyIdAsyncResult_; bool isWaitingJoinLnnCallback_ = false; + CleanNotifyCallback cleanNotifyCallback_{nullptr}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h new file mode 100644 index 000000000..4d1d45934 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_MANAGER_V2_H +#define OHOS_DM_AUTH_MANAGER_V2_H + +#include + +#include "auth_ui_state_manager.h" +#include "dm_auth_manager_base.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "json_object.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; + +class AuthManager : public AuthManagerBase, + public std::enable_shared_from_this { +public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthManager(); + + // External API begin + /** + * @tc.name: DmAuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; + + /** + * @tc.name: AuthManager::GeneratePincode + * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + /** + * @tc.name: AuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t GeneratePincode(); + + /** + * @tc.name: AuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); + + /** + * @tc.name: AuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param sessionName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &sessionName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + void HandleDeviceNotTrust(const std::string &udid); + + int32_t RegisterAuthenticationType(int32_t authenticationType); + void OnScreenLocked(); + int32_t StopAuthenticateDevice(const std::string &sessionName); + // External API begin end + + // Internal API begin + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + static bool IsHmlSessionType(const std::string &sessionType); + int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); + void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + void SetBindTargetParams(const PeerTargetId &targetId); + int32_t GetReason(); + + // Internal API end + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + void ClearSoftbusSessionCallback(); + void PrepareSoftbusSessionCallback(); +protected: + std::shared_ptr context_; + std::map bindParam_; + PeerTargetId targetId_; + + int32_t GetPinCode(int32_t &code); + void GetRemoteDeviceId(std::string &deviceId); +private: + void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); + void ParseJsonObject(const JsonObject &jsonObject); + void GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(const JsonObject &jsonObject); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &sessionName); + int32_t CheckAuthParamVaild(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); +}; + +class AuthSrcManager : public AuthManager { +public: + AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSrcManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnSessionDisable() override; + void OnDataReceived(int32_t sessionId, std::string message) override; + + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; + +class AuthSinkManager : public AuthManager { +public: + AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSinkManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h new file mode 100644 index 000000000..e744a4163 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_CONTEXT_V2_H +#define OHOS_DM_AUTH_CONTEXT_V2_H +#include +#include + +#include "access_control_profile.h" +#include "authentication.h" +#include "auth_ui_state_manager.h" +#include "dm_ability_manager.h" +#include "dm_anonymous.h" +#include "dm_auth_message_processor.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachine; +class DmAuthMessageProcessor; + +using CleanNotifyCallback = std::function; + +// PIN Code Authentication Type +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, + AUTH_TYPE_PIN, // Input PIN code + AUTH_TYPE_QR_CODE, // Not used in the new protocol + AUTH_TYPE_NFC, + AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol + AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code + AUTH_TYPE_UNKNOW, // Not used in the new protocol + AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code +}; + +enum DmAuthDirection { + DM_AUTH_SOURCE = 0, + DM_AUTH_SINK, +}; + +enum DmBindType { + DM_AUTH_USERID = 1, + DM_AUTH_SYSTEM_SERVICE, + DM_AUTH_APP_SERVICE, + DM_AUTH_DEVICEID, +}; + +enum DmAuthSide { + DM_AUTH_LOCAL_SIDE = 0, + DM_AUTH_REMOTE_SIDE, +}; + +enum DmAuthScope { + DM_AUTH_SCOPE_DEVICE = 1, + DM_AUTH_SCOPE_USER, + DM_AUTH_SCOPE_APP, +}; + +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_DEVICE = 1, + DM_ROLE_USER = 1, + DM_ROLE_SA, + DM_ROLE_FA, +}; + +enum { + DM_UNKNOWN_TYPE = 0, + DM_SAME_ACCOUNT_TYPE = 1, + DM_SHARE_TYPE = 2, + DM_POINT_TO_POINT_TYPE = 256, + DM_SAME_GROUP_TYPE = 3, +}; + +// Used for one-touch pairing +struct DmPeerTargetAddress { + // directly establish a Bluetooth connection + std::string peerBrMacAddress; + std::string peerBleMacAddress; + std::string peerWifiMacAddress; + std::string peerActionMacAddress; + + std::string peerWifiChannel; + std::string peerWifiIp; + uint16_t peerWifiPort; +}; + +struct DmPeerTarget { + DmBindType peerType; + std::string peerDeviceId; + int64_t peerServiceId; + int64_t peerSaTokenId; + std::string peerBundleName; + DmPeerTargetAddress peerTargetAddress; +}; + +struct DmAccess { + std::string deviceName; + int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. + std::string deviceId; + std::string deviceIdHash; + std::string addr; + int32_t userId{-1}; + int32_t displayId{-1}; // Logical screen ID, used for query userId + std::string accountId; + std::string accountIdHash; + int64_t tokenId; + std::string tokenIdHash; + std::string networkId; + std::string bundleName; // Stores the bundleName, HAP -> bundleName in BMS, SA -> process name + std::string pkgName; // store pkgName set by client + std::string language; + int64_t serviceId; // Reserved field, to be used in HM 6.0 + std::string accesserHapSignature; + int32_t bindLevel; + int32_t lnnBindType; + int32_t transmitBindType; + std::string lnnCredentialId; // User-level credential ID + std::string transmitCredentialId; // Application-level credential ID + std::string lnnPublicKey; // User-level public key + std::string transmitPublicKey; // Application-level public key + std::vector bindType; // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED + std::string publicKey; + int32_t status; // Indicates whether the service is in the foreground or background + int32_t sessionKeyId; // Used as key delivery material, retrieves the SK from the bus + int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging + int32_t lnnSessionKeyId{0}; // Permanent user SKID on this end, returned by DP for ACL updates and aging + int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp + int64_t lnnSkTimeStamp{0}; // Used for aging, time is 2 days, user-level credential timestamp + int64_t skTimeStamp; // Used for aging, time is 2 days + bool isAuthed; + bool isOnline; + bool isGenerateLnnCredential{true}; + bool isPutLnnAcl{true}; + std::string dmVersion; + std::string edition; // Used for compatibility before version 5.1.0, assists in version negotiation + std::string aclTypeList; // Trust relationship list, used for data aging, KV format + std::string credTypeList; + std::string aclStrList; + std::map credentialInfos; // map: , cred is string tranformed by json + std::map aclProfiles; + // construct for old version compatible start + // In the scenario of compatibility between the new and old protocols, it is necessary to + // send both the new and old protocol messages simultaneously in the 80 message when + // authType == import. Therefore, it is required to define these fields for compatibility processing. + std::string accountGroupIdHash; + int32_t oldBindLevel; + std::string oldBundleName; + // construct for old version compatible end + std::string extraInfo; // Expandable field, JSON format, KV structure +}; + +struct DmAuthContext { + bool isOnline; + uint64_t logicalSessionId; + DmMessageType msgType; + int32_t sessionId; + int64_t requestId; // HiChain authentication ID + int32_t authBoxType{1}; // Authentication box type + UiAction pinInputResult; + // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) + UiAction confirmOperation{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code + std::vector authTypeList; + uint32_t currentAuthTypeIdx{0}; + int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure + int32_t pinCode{INVALID_PINCODE}; + bool serviceInfoFound{false}; + // Link delay release time, does not automatically disconnect after + // authorization (used for specific business needs), reserved field + int32_t connDelayCloseTime; + int32_t reason{DM_OK}; + int32_t reply; + int32_t state; + int32_t hmlActionId = 0; + bool authenticating; // Indicator whether authentication is in progress + bool successFinished{false}; + bool isAppCredentialVerified{false}; // Whether the application credential has been verified + bool hmlEnable160M{false}; + std::string pkgName; // Business-provided identifier, custom-defined by business, carries risk of spoofing + std::string pkgLabel; + std::string importCodeBundleName; // Bundle name for imported PIN code + std::string appThumbnail; // Application thumbnail + // Description of the operation this binding is used for, displayed in authorization dialog + std::string appOperation; + // Custom business field, provides detailed information to the user about this binding operation + std::string customData; + std::string connSessionType; + std::string extraInfo; // Expandable field, key-value structure + DmAuthDirection direction; // Indicator of authentication direction + ProcessInfo processInfo; + DmPeerTarget peerTarget; + DmAccess accesser; + DmAccess accessee; + std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee + + std::shared_ptr authStateMachine; + std::shared_ptr authUiStateMgr; + std::shared_ptr hiChainConnector; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr authPtr; // Pointer to authentication interface + std::shared_ptr timer; + std::string transmitData; // Data returned from onTrasmit function + std::string importPkgName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool pinNegotiateStarted{false}; + bool isAuthenticateDevice{false}; // Whether device authentication is in progress + bool needBind{true}; + bool needAgreeCredential{true}; + bool needAuth{true}; + + CleanNotifyCallback cleanNotifyCallback{nullptr}; + + std::string GetDeviceId(DmAuthSide side); + int32_t GetUserId(DmAuthSide side); + std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); + std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); + void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + std::string GetAccountId(DmAuthSide side); + uint32_t GetBindType(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h new file mode 100644 index 000000000..49915a2c2 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_ADAPTER_V2_H +#define OHOS_DM_AUTH_ADAPTER_V2_H + +#include +#include +#include +#include + +#include "softbus_session_callback.h" +#include "softbus_connector_callback.h" +#include "hichain_connector_callback.h" +#include "hichain_connector_callback.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { + +extern const char* DM_VERSION_5_0_1; +extern const char* DM_VERSION_5_0_2; +extern const char* DM_VERSION_5_0_3; +extern const char* DM_VERSION_5_0_4; +extern const char* DM_VERSION_5_0_5; +extern const char* DM_VERSION_5_1_0; +extern const char* DM_VERSION_5_0_OLD_MAX; // Estimated highest version number of the old version + +extern const char* TAG_DMVERSION; +extern const char* TAG_DM_VERSION_V2; // compatible for new and old protocol +extern const char* TAG_EDITION; +extern const char* TAG_DATA; +extern const char* TAG_DATA_LEN; +extern const char* TAG_BUNDLE_NAME; +extern const char* TAG_BUNDLE_NAME_V2; +extern const char* TAG_PEER_BUNDLE_NAME; +extern const char* TAG_PEER_BUNDLE_NAME_V2; +extern const char* TAG_PEER_PKG_NAME; +extern const char* TAG_BIND_LEVEL; +extern const char* TAG_REPLY; +extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +extern const char* TAG_AUTH_FINISH; +extern const char* TAG_LOCAL_USERID; +extern const char* TAG_LOCAL_DEVICE_ID; +extern const char* TAG_IDENTICAL_ACCOUNT; +extern const char* TAG_ACCOUNT_GROUPID; +extern const char* TAG_HAVE_CREDENTIAL; +extern const char* TAG_ISONLINE; +extern const char* TAG_AUTHED; +extern const char* TAG_LOCAL_ACCOUNTID; +extern const char* TAG_TOKENID; +extern const char* TAG_HOST_PKGLABEL; +extern const char* TAG_REMOTE_DEVICE_NAME; +extern const char* TAG_HOST; + +extern const char* APP_OPERATION_KEY; +extern const char* TARGET_PKG_NAME_KEY; +extern const char* CUSTOM_DESCRIPTION_KEY; +extern const char* CANCEL_DISPLAY_KEY; +extern const char* BUNDLE_NAME_KEY; + +extern const char* AUTHENTICATE_TIMEOUT_TASK; +extern const char* NEGOTIATE_TIMEOUT_TASK; +extern const char* CONFIRM_TIMEOUT_TASK; +extern const char* INPUT_TIMEOUT_TASK; +extern const char* SESSION_HEARTBEAT_TIMEOUT_TASK; +extern const char* WAIT_REQUEST_TIMEOUT_TASK; +extern const char* AUTH_DEVICE_TIMEOUT_TASK; +extern const char* WAIT_PIN_AUTH_TIMEOUT_TASK; +extern const char* WAIT_NEGOTIATE_TIMEOUT_TASK; +extern const char* ADD_TIMEOUT_TASK; +extern const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK; +extern const char* CLOSE_SESSION_TASK_SEPARATOR; + +extern const int32_t AUTHENTICATE_TIMEOUT; +extern const int32_t CONFIRM_TIMEOUT; +extern const int32_t NEGOTIATE_TIMEOUT; +extern const int32_t INPUT_TIMEOUT; +extern const int32_t ADD_TIMEOUT; +extern const int32_t WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; +extern const int32_t CLONE_CONFIRM_TIMEOUT; +extern const int32_t CLONE_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_ADD_TIMEOUT; +extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t CLONE_PIN_AUTH_TIMEOUT; +extern const int32_t HML_SESSION_TIMEOUT; +extern const int32_t SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t PIN_AUTH_TIMEOUT; +extern const int32_t EVENT_TIMEOUT; + +extern const int32_t DM_AUTH_TYPE_MAX; +extern const int32_t DM_AUTH_TYPE_MIN; +extern const int32_t MIN_PIN_TOKEN; +extern const int32_t MAX_PIN_TOKEN; + +using CleanNotifyCallback = std::function; + +class AuthManagerBase : public ISoftbusSessionCallback, + public ISoftbusConnectorCallback, + public IHiChainConnectorCallback, + public IDmDeviceAuthCallback { +public: + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + virtual void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); + + virtual void OnSessionClosed(const int32_t sessionId); + + virtual void OnSessionDisable(); + + virtual void OnDataReceived(const int32_t sessionId, const std::string message); + + virtual void OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result); + + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId); + + virtual void OnMemberJoin(int64_t requestId, int32_t status); + + virtual int32_t EstablishAuthChannel(const std::string &deviceId); + + virtual void StartNegotiate(const int32_t &sessionId); + + virtual void RespNegotiate(const int32_t &sessionId); + + virtual void SendAuthRequest(const int32_t &sessionId); + + virtual int32_t StartAuthProcess(const int32_t &action); + + virtual void StartRespAuthProcess(); + + virtual int32_t CreateGroup(); + + virtual int32_t ProcessPincode(int32_t pinCode); + + virtual std::string GetConnectAddr(std::string deviceId); + + virtual int32_t JoinNetwork(); + + virtual void AuthenticateFinish(); + + virtual bool GetIsCryptoSupport(); + + virtual int32_t SetAuthRequestState(std::shared_ptr authRequestState); + + virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); + + virtual int32_t GetPinCode(int32_t &code); + + virtual std::string GenerateGroupName(); + + virtual void HandleAuthenticateTimeout(std::string name); + + virtual int32_t GeneratePincode(); + + virtual void ShowConfigDialog(); + + virtual void ShowAuthInfoDialog(bool authDeviceError = false); + + virtual void ShowStartAuthDialog(); + + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms); + + virtual int32_t SetPageId(int32_t pageId); + + virtual int32_t SetReasonAndFinish(int32_t reason, int32_t state); + + virtual bool IsIdenticalAccount(); + + virtual int32_t RegisterUiStateCallback(const std::string pkgName); + + virtual int32_t UnRegisterUiStateCallback(const std::string pkgName); + + virtual int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + virtual int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + virtual int32_t RegisterAuthenticationType(int32_t authenticationType); + + virtual int32_t StopAuthenticateDevice(const std::string &pkgName); + + virtual void OnScreenLocked() = 0; + + virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + + // New interface added in version 5.1.0 + virtual int32_t GetReason(); + // When switching from the new protocol to the old protocol, the previous parameters + // need to be obtained for use by the old protocol + virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + + virtual void SetBindTargetParams(const PeerTargetId &targetId); + // Register the notification function when the auth_mgr event is complete. + virtual void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + + /** + * @brief Classical authMgr is global, single-frame collabration with double-frame device + * need it. If we start bind with single-frame device, we need clear dsoftbus callback + * to avoid the classical authMgr affect the single to single logical. + * For new protocal, the source and sink authMgr lifecycle obey the bind session, no need + * to process it. + */ + virtual void ClearSoftbusSessionCallback(); + /** + * @brief Classical authMgr is global, if we use classical logic, we need prepare the callback. + */ + virtual void PrepareSoftbusSessionCallback(); + + // Public functions + static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + static int32_t DmGetUserId(int32_t displayId); + bool IsTransferReady(); + void SetTransferReady(bool version); + void EnableInsensibleSwitching(); + void DisableInsensibleSwitching(); + int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); +protected: + bool NeedInsensibleSwitching(); + bool isTransferReady_{true}; + /** + For old protocol, when insensible switching is true, no new session needs to be created, + and the actual method 80 message is not sent. + */ + bool insensibleSwitching{false}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_ADAPTER_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h new file mode 100644 index 000000000..4565b12df --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H + +#include + +#include "access_control_profile.h" +#include "crypto_mgr.h" +#include "deviceprofile_connector.h" +#include "json_object.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; +struct DmAccess; + +extern const char* TAG_LNN_PUBLICK_KEY; +extern const char* TAG_TRANSMIT_PUBLICK_KEY; +extern const char* TAG_LNN_CREDENTIAL_ID; +extern const char* TAG_TRANSMIT_CREDENTIAL_ID; +extern const char* TAG_CONFIRM_OPERATION_V2; +extern const char* TAG_AUTH_TYPE_LIST; +extern const char* TAG_CURRENT_AUTH_TYPE_IDX; + +// IS interface input parameter json format string key +extern const char* TAG_METHOD; +extern const char* TAG_PEER_USER_SPACE_ID; +extern const char* TAG_SUBJECT; +extern const char* TAG_CRED_TYPE; +extern const char* TAG_KEY_FORMAT; +extern const char* TAG_ALGORITHM_TYPE; +extern const char* TAG_PROOF_TYPE; +extern const char* TAG_KEY_VALUE; +extern const char* TAG_AUTHORIZED_SCOPE; +extern const char* TAG_AUTHRIZED_APP_LIST; +extern const char* TAG_CREDENTIAL_OWNER; +extern const char* TAG_SYNC; +extern const char* TAG_ACCESS; +extern const char* TAG_PROXY; +extern const char* TAG_ACL; +extern const char* TAG_ACCESSER; +extern const char* TAG_ACCESSEE; +extern const char* TAG_SERVICEINFO; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +extern const char* TAG_TRANSMIT_SK_ID; +extern const char* TAG_LNN_SK_ID; +extern const char* TAG_TRANSMIT_SK_TIMESTAMP; +extern const char* TAG_LNN_SK_TIMESTAMP; +extern const char* TAG_USER_ID; +extern const char* TAG_TOKEN_ID; +extern const char* TAG_ISSUER; + +extern const char* TAG_DEVICE_VERSION; +extern const char* TAG_DEVICE_NAME; +extern const char* TAG_DEVICE_ID_HASH; +extern const char* TAG_ACCOUNT_ID_HASH; +extern const char* TAG_TOKEN_ID_HASH; +extern const char* TAG_SESSION_NAME; +extern const char* TAG_ACL_CHECKSUM; +extern const char* TAG_COMPRESS_ORI_LEN; +extern const char* TAG_COMPRESS; +extern const char* TAG_REPLY; +extern const char* TAG_STATE; +extern const char* TAG_REASON; +extern const char* TAG_PEER_USER_ID; +extern const char* TAG_PEER_DISPLAY_ID; +extern const char* TAG_EXTRA_INFO; + +extern const char* TAG_IS_ONLINE; +extern const char* TAG_IS_AUTHED; +extern const char* TAG_CREDENTIAL_INFO; +extern const char* TAG_CERT_INFO; +extern const char* TAG_LANGUAGE; + +// Logical Session Tag +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; + +// Message type +enum DmMessageType { + // Terminate/Exception Message + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_AUTH_TERMINATE = 1, + // Normal Message + MSG_TYPE_REQ_ACL_NEGOTIATE = 80, + MSG_TYPE_RESP_ACL_NEGOTIATE = 90, + MSG_TYPE_REQ_USER_CONFIRM = 100, + MSG_TYPE_RESP_USER_CONFIRM = 110, + MSG_TYPE_REQ_PIN_AUTH_START = 120, + MSG_TYPE_RESP_PIN_AUTH_START = 130, + MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE = 121, + MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE = 131, + MSG_TYPE_REQ_CREDENTIAL_EXCHANGE = 140, + MSG_TYPE_RESP_CREDENTIAL_EXCHANGE = 150, + MSG_TYPE_REQ_CREDENTIAL_AUTH_START = 160, + MSG_TYPE_RESP_CREDENTIAL_AUTH_START = 170, + MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE = 161, + MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE = 171, + MSG_TYPE_REQ_DATA_SYNC = 180, + MSG_TYPE_RESP_DATA_SYNC = 190, + MSG_TYPE_AUTH_REQ_FINISH = 200, + MSG_TYPE_AUTH_RESP_FINISH = 201, +}; + +struct DmAccessControlTable { + int32_t accessControlId; + int64_t accesserId; + int64_t accesseeId; + std::string deviceId; + std::string sessionKey; + int32_t bindType; + uint32_t authType; + uint32_t deviceType; + std::string deviceIdHash; + int32_t status; + int32_t validPeriod; + int32_t lastAuthTime; + uint32_t bindLevel; +}; + +// Structure used for synchronizing ACL access +// Attention: Modifying this structure requires updating the From/ToJson functions in dm_auth_message_processor.cpp. +struct DmAccessToSync { + std::string deviceName; + // For A->B communication, whether it's the A end or B end, the Accesser object stores + // the A end's deviceId, and the Accessee object stores the B end's deviceId + std::string deviceId; + int32_t userId; + std::string accountId; + uint64_t tokenId; + std::string bundleName; // Stores the bundleName, HAP -> bundleName in BMS, SA -> process name + std::string pkgName; // Store pkgName set by client + int32_t bindLevel; // Passed through for business purposes, no custom definition required + int32_t sessionKeyId; // User credential ID + int64_t skTimeStamp; // Used for aging, time is 2 days, user-level credential timestamp +}; + +// json and struct conversion functions +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table); +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table); +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table); +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table); + +using JsonTypeCheckFuncPtr = bool (JsonItemObject::*)() const; + +template +void SetValueFromJson(const JsonItemObject &itemObject, const std::string &key, + JsonTypeCheckFuncPtr funcPtr, T &value) +{ + if (itemObject.Contains(key) && (itemObject[key].*funcPtr)()) { + value = itemObject[key].Get(); + } +} + +class DmAuthMessageProcessor { +public: + using CreateMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(std::shared_ptr, JsonObject &jsonObject); + using ParaseMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(const JsonObject &, std::shared_ptr); + + DmAuthMessageProcessor(); + ~DmAuthMessageProcessor(); + // Parse the message, and save the parsed information to the context + int32_t ParseMessage(std::shared_ptr context, const std::string &message); + // Create a message, construct the corresponding message based on msgType + std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); + + // Create and send a message + void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); + + // Save the session key + int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); + + // Save the permanent session key to the data profile + int32_t SaveSessionKeyToDP(int32_t userId, int32_t &skId); + + // Save the current access control list + int32_t PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId); + + // Extract the access control list (ACL) for message parsing and bus usage. + // If no ACL is available, return an empty string. The returned string is in + // JSON format: {dmversion:x,accesser:[{accesserDeviceId:y,...},...], accessee:{...}} + int32_t DeleteSessionKeyToDP(int32_t userId, int32_t skId); + +private: + // Internal implementations for various message types + + // Used to encrypt the synchronization message + int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); + // Parse the authentication start message + int32_t ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context); + + // Parse the 80 message + int32_t ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 90 message + int32_t ParseMessageRespAclNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 100 message + int32_t ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 110 message + int32_t ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 120 message + int32_t ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 130 message + int32_t ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 121 message + int32_t ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 131 message + int32_t ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 140 message + int32_t ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 150 message + int32_t ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 161, 170, and 171 messages + int32_t ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 180 message + int32_t ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 190 message + int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 200 message + int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 201 message + int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); + + // Create the 80 message + int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 90 message + int32_t CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 100 message + int32_t CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 110 message + int32_t CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 120 message + int32_t CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 130 message + int32_t CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 121 message + int32_t CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 131 message + int32_t CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 140 message + int32_t CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 150 message + int32_t CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 160 message + int32_t CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 161, 170, and 171 credential authentication messages + int32_t CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 180 and 190 sync messages + int32_t CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 190 message + int32_t CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); + // Create the 200 message + int32_t CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + + // Compress the sync message + std::string CompressSyncMsg(std::string &inputStr); + // Decompress the sync message + std::string DecompressSyncMsg(std::string& compressed, uint32_t oriLen); + // Serialize the ACL + int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); + // Decrypt the 180 and 190 messages + int32_t DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg); + // Parse the sync message + int32_t ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, JsonObject &jsonObject); + + std::string Base64Encode(std::string &inputStr); + std::string Base64Decode(std::string &inputStr); + void SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile); + void SetTransmitAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + void SetLnnAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + int32_t CheckLogicalSessionId(const JsonObject &jsonObject, std::shared_ptr context); + bool CheckAccessValidityAndAssign(std::shared_ptr &context, DmAccess &access, + DmAccess &accessTmp); + std::shared_ptr cryptoMgr_ = nullptr; + std::unordered_map createMessageFuncMap_; + std::unordered_map paraseMessageFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h new file mode 100644 index 000000000..896bd4cb2 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_STATE_V2_H +#define OHOS_DM_AUTH_STATE_V2_H + +#include + +#include "access_control_profile.h" +#include "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { +const char* const FILED_CRED_OWNER = "credOwner"; +const char* const FILED_DEVICE_ID = "deviceId"; +const char* const FILED_USER_ID = "userId"; +const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* const FILED_CRED_ID = "credId"; +const char* const FILED_CRED_TYPE = "credType"; +const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; +const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; +const char* const FILED_SUBJECT = "subject"; + +// State Types +enum class DmAuthStateType { + AUTH_IDLE_STATE = 0, // When the device is initialized + // source end state + AUTH_SRC_START_STATE = 1, // User triggers BindTarget + AUTH_SRC_NEGOTIATE_STATE = 2, // Receive softbus callback OnSessionOpened, send 80 message + AUTH_SRC_CONFIRM_STATE = 3, // Receive 90 authorization result message, send 100 message + AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message + // or rollback or 90 jump + AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN + AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 6, // Ultrasonic PIN negotiation + AUTH_SRC_PIN_AUTH_START_STATE = 7, // Start authentication and send 120 message. + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 8, // Receive 130 authentication PIN result message, send 121 message + AUTH_SRC_PIN_AUTH_DONE_STATE = 9, // Receive 131 authentication PIN result message, call processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 10, // Trigger the Onfinish callback event and send a 140 message + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 11, // Received 150 encrypted messages, sent 160 messages + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 12, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 13, // Received 170 credential authentication message, sent 161 message + AUTH_SRC_DATA_SYNC_STATE = 14, // Received 190 message, sent 200 message + AUTH_SRC_FINISH_STATE = 15, // Received 201 message + + // sink end state + AUTH_SINK_START_STATE = 50, // Bus trigger OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE = 51, // Received 80 trusted relationship negotiation message, send 90 message + AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages + AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback + AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN + AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 55, // Negotiate ultrasonic PIN status passive trigger or + // other status active migration to enter ultrasonic + AUTH_SINK_PIN_AUTH_START_STATE = 56, // Receive 120 authentication PIN message, send 130 message + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 57, // Received 121 authentication PIN message, send 131 message + AUTH_SINK_PIN_AUTH_DONE_STATE = 58, // Trigger the Onfinish callback event + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 59, // Received 140 encrypted messages, sent 150 messages + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 60, // Receive 160 authentication message, send 170 message + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 61, // Received 161 credential negotiation message, + // reply with 171 message + AUTH_SINK_DATA_SYNC_STATE = 62, // Received 180 synchronization message, send 190 message + AUTH_SINK_FINISH_STATE = 63, // Received 200 end message, send 201 message +}; + +// Credential Addition Method +enum DmAuthCredentialAddMethod : uint8_t { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // Generate + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // Import +}; + +// Credential Subject +enum DmAuthCredentialSubject : uint8_t { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // Main Control + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // Accessories +}; + +// Credentials and account association +enum DmAuthCredentialAccountRelation : uint8_t { + DM_AUTH_CREDENTIAL_INVALID = 0, // Invalid + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // Account related + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED = 2, // Account independent + DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS = 3, // Share +}; + +// Key Type +enum DmAuthKeyFormat : uint8_t { + DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // Symmetric key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // Asymmetric key public key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // Asymmetric key (supported only for generation) + DM_AUTH_KEY_FORMAT_X509, // X509 certificate +}; + +// Algorithm type +enum DmAuthAlgorithmType : uint8_t { + DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 + DM_AUTH_ALG_TYPE_AES128, // AES128 + DM_AUTH_ALG_TYPE_P256, // P256 + DM_AUTH_ALG_TYPE_ED25519 // ED25519 +}; + +// Credential proof type +enum DmAuthCredentialProofType : uint8_t { + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI +}; + +enum DmCredType : uint8_t { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +enum DmAuthorizedScope : uint8_t { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + +enum DM_SUBJECT : uint8_t { + SUBJECT_PRIMARY = 1, + SUBJECT_SECONDARY, +}; + +class DmAuthState { +public: + virtual ~DmAuthState() {}; + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; + void SourceFinish(std::shared_ptr context); + void SinkFinish(std::shared_ptr context); + std::string GenerateBindResultContent(std::shared_ptr context); + static bool IsScreenLocked(); + static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); + static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); + static bool IsImportAuthCodeCompatibility(DmAuthType authType); + + void SetAclExtraInfo(std::shared_ptr context); + void SetAclInfo(std::shared_ptr context); + int32_t GetAclBindType(std::shared_ptr context, std::string credId); + static bool CheckProcessNameInWhiteList(const std::string &processName); + int32_t GetOutputState(int32_t state); + static void DeleteAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile); +protected: + bool NeedReqUserConfirm(std::shared_ptr context); + bool NeedAgreeCredential(std::shared_ptr context); + bool NeedAgreeAcl(std::shared_ptr context); + uint32_t GetCredType(std::shared_ptr context, const JsonItemObject &credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); + bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); +}; + +class AuthSrcConfirmState : public DmAuthState { +public: + virtual ~AuthSrcConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + void GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, + JsonObject &credTypeJson); +}; + +class AuthSinkStatePinAuthComm { +public: + static bool IsPinCodeValid(int32_t numpin); + static bool IsPinCodeValid(const std::string& strpin); + static bool IsAuthCodeReady(std::shared_ptr context); + static void GeneratePincode(std::shared_ptr context); + static int32_t ShowAuthInfoDialog(std::shared_ptr context); +private: + static void HandleSessionHeartbeat(std::shared_ptr context, std::string name); +}; + +class AuthSinkConfirmState : public DmAuthState { +public: + virtual ~AuthSinkConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + int32_t ShowConfigDialog(std::shared_ptr context); + void ReadServiceInfo(std::shared_ptr context); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); + int32_t ProcessBindAuthorize(std::shared_ptr context); + int32_t ProcessNoBindAuthorize(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); + int32_t ProcessCredAuth(std::shared_ptr context); + int32_t ProcessPinBind(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinInputState : public DmAuthState { +public: + virtual ~AuthSrcPinInputState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); +}; + +class AuthSinkPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinDisplayState : public DmAuthState { +public: + virtual ~AuthSinkPinDisplayState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); // Display PIN input box to user +}; + +class AuthSinkPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcStartState : public DmAuthState { +public: + virtual ~AuthSrcStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSrcNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + std::string GetAccountGroupIdHash(std::shared_ptr context); +}; + +// Middle class encapsulates public interfaces related to business. +class AuthCredentialAgreeState : public DmAuthState { +public: + virtual ~AuthCredentialAgreeState() {}; +protected: + std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, + const std::shared_ptr &authContext); + int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); + int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); +}; + +class AuthSrcCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSinkCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthStartState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSinkNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + +private: + int32_t RespQueryAcceseeIds(std::shared_ptr context); + int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); + void GetSinkCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, + JsonObject &credTypeJson); +}; + +class AuthSinkDataSyncState : public DmAuthState { +public: + virtual ~AuthSinkDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcDataSyncState : public DmAuthState { +public: + virtual ~AuthSrcDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkFinishState : public DmAuthState { +public: + virtual ~AuthSinkFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcFinishState : public DmAuthState { +public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h new file mode 100644 index 000000000..00a4c80e2 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_AUTH_STATE_MACHINE_V2_H +#define OHOS_DM_AUTH_STATE_MACHINE_V2_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dm_auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +// Define the state transition table type +using StateTransitionTable = std::map>; + +enum DmEventType { + ON_TRANSMIT = 0, + ON_SESSION_KEY_RETURNED, + ON_REQUEST, + ON_FINISH, + ON_ERROR, + + ON_TIMEOUT, + ON_USER_OPERATION, + ON_FAIL, + ON_SCREEN_LOCKED, + ON_SESSION_OPENED, +}; + +class DmAuthStateMachine { +public: + DmAuthStateMachine(std::shared_ptr context); + ~DmAuthStateMachine(); + + // Notify state transition, execute the corresponding action for the state, and handle exceptions + // only allowed to be called within OnDataReceived + int32_t TransitionTo(std::shared_ptr state); + + // Wait for the expected event within the action, block until the expected event is completed or + // an exception occurs, returning the actual event that occurred (only allowed to be called within actions) + DmEventType WaitExpectEvent(DmEventType eventType); + + // Notify the completion of an event, passing the event enumeration + // (only allowed to be called when the event is triggered). If it's an exception event, + // record it in the context's reason or reply. + void NotifyEventFinish(DmEventType eventType); + + DmAuthStateType GetCurState(); + + // Stop the thread + void Stop(); + +private: + // Loop to wait for state transitions and execute actions + void Run(std::shared_ptr context); + void InsertSrcTransTable(); + void InsertSinkTransTable(); + + // Fetch the current state and execute it + std::optional> FetchAndSetCurState(); + + void SetCurState(DmAuthStateType state); + + bool CheckStateTransitValid(DmAuthStateType nextState); + + DmAuthStateType curState_; + + // State transition table for normal state transitions (all state transitions to the Finish state are valid) + StateTransitionTable stateTransitionTable_; + + std::queue eventQueue_; + + // Set of exception events + std::set exceptionEvent_; + + // Atomic flag to control the state machine's running state + std::atomic running_; + + // Queue for storing states + std::queue> statesQueue_; + + // Synchronization primitives + std::mutex stateMutex_; + std::condition_variable stateCv_; + std::mutex eventMutex_; + std::condition_variable eventCv_; + + // Direction of authentication + DmAuthDirection direction_; + int32_t reason{DM_OK}; + + // Thread for state machine execution + std::thread thread_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_MACHINE_V2_H diff --git a/services/implementation/include/authentication_v2/dm_negotiate_process.h b/services/implementation/include/authentication_v2/dm_negotiate_process.h new file mode 100644 index 000000000..f8a21a9f0 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_negotiate_process.h @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_DM_NEGOTIATE_PROCESS_V2_H +#define OHOS_DM_NEGOTIATE_PROCESS_V2_H +#include +#include +#include + +#include "dm_auth_context.h" +#include "dm_single_instance.h" +namespace OHOS { +namespace DistributedHardware { +enum CredType : uint8_t { + DM_NO_CRED = 0, + DM_IDENTICAL_CREDTYPE = 1, + DM_SHARE_CREDTYPE = 2, + DM_P2P_CREDTYPE = 3, +}; + +enum AclType : uint8_t { + DM_NO_ACL = 0, + DM_IDENTICAL_ACL = 1, + DM_SHARE_ACL = 2, + DM_P2P_ACL = 3, +}; + +enum AuthType : uint8_t { + DM_INVALIED_AUTHTYPE = 0, + DM_INPUT_PINCODE = 1, + DM_IMPORT_AUTHTYPE = 2, +}; + +class NegotiateSpec { +public: + CredType credType; + AclType aclType; + AuthType authType; + + NegotiateSpec(CredType credTypeTemp, AclType aclTypeTemp, AuthType authTypeTemp) + : credType(credTypeTemp), aclType(aclTypeTemp), authType(authTypeTemp) {} + + // 重载<运算符用于map排序 + bool operator<(const NegotiateSpec& other) const + { + if (credType != other.credType) return credType < other.credType; + if (aclType != other.aclType) return aclType < other.aclType; + return authType < other.authType; + } +}; + +class NegotiateHandler { +public: + virtual int32_t NegotiateHandle(std::shared_ptr context) = 0; + virtual ~NegotiateHandler() {}; +}; + +class NoCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~NoCredNoAclInputAuthType() {}; +}; + +class NoCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~NoCredNoAclImportAuthType() {}; +}; + +class IdentCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredNoAclInputAuthType() {}; +}; + +class IdentCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredNoAclImportAuthType() {}; +}; + +class IdentCredIdentAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredIdentAclInputAuthType() {}; +}; + +class IdentCredIdentAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredIdentAclImportAuthType() {}; +}; + +class IdentCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredP2pAclInputAuthType() {}; +}; + +class IdentCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredP2pAclImportAuthType() {}; +}; + +class ShareCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredNoAclInputAuthType() {}; +}; + +class ShareCredNoAclImputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredNoAclImputAuthType() {}; +}; + +class ShareCredShareAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredShareAclInputAuthType() {}; +}; + +class ShareCredShareAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredShareAclImportAuthType() {}; +}; + +class ShareCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredP2pAclInputAuthType() {}; +}; + +class ShareCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredP2pAclImportAuthType() {}; +}; + +class P2pCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredNoAclInputAuthType() {}; +}; + +class P2pCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredNoAclImportAuthType() {}; +}; + +class P2pCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredP2pAclInputAuthType() {}; +}; + +class P2pCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredP2pAclImportAuthType() {}; +}; + +class NegotiateProcess { +DM_DECLARE_SINGLE_INSTANCE_BASE(NegotiateProcess); +public: + NegotiateProcess(); + ~NegotiateProcess(); + int32_t HandleNegotiateResult(std::shared_ptr context); +private: + CredType ConvertCredType(const std::string &credType); + AclType ConvertAclType(const std::string &aclType); + AuthType ConvertAuthType(const DmAuthType &authType); +private: + std::map> handlers_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/cryptomgr/crypto_mgr.h b/services/implementation/include/cryptomgr/crypto_mgr.h index 86a759081..e31e27c15 100644 --- a/services/implementation/include/cryptomgr/crypto_mgr.h +++ b/services/implementation/include/cryptomgr/crypto_mgr.h @@ -45,6 +45,7 @@ public: int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); int32_t ProcessSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); void ClearSessionKey(); + std::vector GetSessionKey(); private: int32_t DoEncryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 94d418501..5684ef0c9 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -16,7 +16,9 @@ #ifndef OHOS_HICHAIN_AUTH_CONNECTOR_H #define OHOS_HICHAIN_AUTH_CONNECTOR_H +#include #include + #include "device_auth.h" #include "device_auth_defines.h" #include "hichain_connector_callback.h" @@ -52,17 +54,34 @@ public: int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId); int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); - bool QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId); - int32_t ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, std::string publicKey); - int32_t DeleteCredential(const std::string &deviceId, int32_t userId, int32_t peerUserId); + bool QueryCredential(std::string &localUdid, int32_t osAccountId); + int32_t QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, JsonObject &resultJson); + int32_t QueryCredInfoByCredId(int32_t userId, std::string credId, JsonObject &resultJson); + int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); + int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); + int32_t RegisterHiChainAuthCallbackById(int64_t id, std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); + + int32_t ProcessCredData(int64_t authReqId, const std::string &data); + int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId); + int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey); + int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId); + int32_t DeleteCredential(int32_t osAccountId, const std::string &creId); + // Credential authentication pinCode Pin code (required for point-to-point temporary credentials) + int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode); + int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode); + private: void FreeJsonString(char *jsonStr); + static std::shared_ptr GetDeviceAuthCallback(int64_t id); private: DeviceAuthCallback deviceAuthCallback_; static std::shared_ptr dmDeviceAuthCallback_; + static std::map> dmDeviceAuthCallbackMap_; static std::mutex dmDeviceAuthCallbackMutex_; }; } // namespace DistributedHardware diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 1e8e73f43..56dd42bbc 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,8 +37,7 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - virtual int32_t GetPinCode(int32_t &code) = 0; - virtual void GetRemoteDeviceId(std::string &deviceId) = 0; + virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 718d7ddeb..f7c2acc85 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -32,6 +32,7 @@ #endif #include "softbus_connector_callback.h" #include "softbus_state_callback.h" +#include "hichain_auth_connector.h" namespace OHOS { namespace DistributedHardware { @@ -49,7 +50,7 @@ public: * @tc.desc: Get Connect Addr of the SoftbusConnector * @tc.type: FUNC */ - static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); + static std::shared_ptr GetConnectAddr(const std::string &deviceId, std::string &connectAddr); /** * @tc.name: SoftbusConnector::GetUdidByNetworkId @@ -86,6 +87,11 @@ public: */ static void JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId); + static void JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash); + + static void JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash); + /** * @tc.name: SoftbusConnector::RegisterConnectorCallback * @tc.desc: RegisterConnectorCallback of the Softbus Connector @@ -120,22 +126,34 @@ public: void HandleDeviceOffline(std::string deviceId); void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); + bool CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash); void SetProcessInfoVec(std::vector processInfoVec); std::vector GetProcessInfo(); void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); + void SyncAclList(int32_t userId, std::string credId, int32_t sessionKeyId, int32_t aclId); + int32_t SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList); + int32_t GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); private: static void ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); static void ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceBasicInfo &dmDeviceBasicInfo); static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); static void ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo); + static std::shared_ptr GetDeviceInfoFromMap(const std::string &deviceId); + int32_t ParaseAclChecksumList(const std::string &jsonString, std::string &dmVersion, + std::vector &remoteAclList); + int32_t SyncLocalAclList5_1_0(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::vector remoteAclList); private: static std::string remoteUdidHash_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr softbusSession_; + std::shared_ptr hiChainAuthConnector_; #endif static std::map> discoveryDeviceInfoMap_; std::shared_ptr deviceStateManagerCallback_; diff --git a/services/implementation/include/dependency/softbus/softbus_session.h b/services/implementation/include/dependency/softbus/softbus_session.h index 289a9cd60..b3dfc2840 100644 --- a/services/implementation/include/dependency/softbus/softbus_session.h +++ b/services/implementation/include/dependency/softbus/softbus_session.h @@ -33,7 +33,6 @@ class SoftbusSession { public: static int OnSessionOpened(int sessionId, int result); static void OnSessionClosed(int sessionId); - static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); public: SoftbusSession(); @@ -91,7 +90,6 @@ public: private: static std::shared_ptr sessionCallback_; - ISocketListener iSocketListener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 423e5be0f..8365fe874 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -16,24 +16,49 @@ #ifndef OHOS_DM_SERVICE_IMPL_H #define OHOS_DM_SERVICE_IMPL_H +#include +#include +#include +#include #include #include #include "access_control_profile.h" +#include "auth_manager.h" #include "dm_ability_manager.h" #include "dm_auth_manager.h" +#include "dm_auth_manager_base.h" #include "dm_common_event_manager.h" #include "dm_credential_manager.h" #include "dm_device_info.h" #include "dm_device_state_manager.h" +#include "dm_single_instance.h" #include "dp_inited_callback.h" #include "idevice_manager_service_impl.h" -#include "dm_single_instance.h" -#include "softbus_connector.h" +#include "ipc_skeleton.h" #include "mine_hichain_connector.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { + +class Session { +public: + Session(int sessionId, std::string deviceId); + int sessionId_; + std::string deviceId_; + std::string version_{""}; + std::atomic flag_{false}; // Only one session is allowed + std::set logicalSessionSet_; // Logical Session Set + std::atomic logicalSessionCnt_{0}; +}; + +struct Config { + std::string pkgName; + std::string authCode; + int32_t authenticationType{0}; +}; + class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { public: DeviceManagerServiceImpl(); @@ -124,6 +149,10 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList); + int32_t GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus); @@ -135,8 +164,19 @@ public: const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); int32_t RegisterAuthenticationType(int32_t authenticationType); void DeleteAlwaysAllowTimeOut(); - void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); + void CheckDeleteCredential(const std::string &remoteUdid); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + int32_t DeleteAclV2(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + static void NotifyCleanEvent(uint64_t logicalSessionId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, std::shared_ptr session, + uint64_t logicalSessionId); + private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); @@ -150,23 +190,77 @@ private: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); - void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); + void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); + std::shared_ptr GetAuthMgr(); + std::shared_ptr GetAuthMgrByTokenId(uint64_t tokenId); + std::shared_ptr GetCurrentAuthMgr(); + void CreateGlobalClassicalAuthMgr(); + std::shared_ptr GetCurSession(int sessionId); + std::shared_ptr GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam); + std::shared_ptr GetConfigByTokenId(); + int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); + + std::shared_ptr GetAuthMgrByMessage(int32_t msgType, uint64_t logicalSessionId, + const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession); + int32_t TransferSrcOldAuthMgr(std::shared_ptr curSession); + int32_t TransferSinkOldAuthMgr(const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, std::string &deviceId, + std::shared_ptr deviceInfo, int32_t &index); + bool IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId); + void ImportConfig(std::shared_ptr authMgr, uint64_t tokenId); + + // Resource cleanup thread + void CleanWorker(); + // Stop the thread + void Stop(); + uint64_t FetchCleanEvent(); + void CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId); + void CleanSessionMap(int sessionId, std::shared_ptr session); + void CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId); + int32_t DeleteProcAcl(uint32_t tokenId, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra, int32_t userId); + int32_t DeleteSkIdAndCredId(DmOfflineParam offlineParam, int32_t userId); private: - std::shared_ptr authMgr_; + std::shared_ptr authMgr_; // Old protocol only + std::mutex authMgrMtx_; + std::map> authMgrMap_; // New protocol sharing + std::shared_ptr hiChainConnector_; + std::shared_ptr hiChainAuthConnector_; std::shared_ptr deviceStateMgr_; std::shared_ptr softbusConnector_; std::shared_ptr abilityMgr_; - std::shared_ptr hiChainConnector_; std::shared_ptr mineHiChainConnector_; std::shared_ptr credentialMgr_; std::shared_ptr commonEventManager_; - std::shared_ptr hiChainAuthConnector_; std::shared_ptr listener_; std::atomic isCredentialType_ = false; sptr dpInitedCallback_ = nullptr; + + // The session ID corresponding to the device ID, used only on the src side + std::map deviceId2SessionIdMap_; + std::map> sessionsMap_; // sessionId corresponds to the session object + std::map deviceIdMutexMap_; // Lock corresponding to the device ID + std::mutex mapMutex_; // sessionsMap_的锁 + std::map sessionEnableCvMap_; // Condition variable corresponding to the session + std::map sessionEnableMutexMap_; // Lock corresponding to the session + std::map logicalSessionId2TokenIdMap_; // The relationship between logicalSessionId and tokenId + std::map logicalSessionId2SessionIdMap_; // The relationship logicalSessionId and physical sessionId + std::map> configsMap_; // Import when authMgr is not initialized + + std::thread thread_; + std::atomic running_; + static std::condition_variable cleanEventCv_; + static std::mutex cleanEventMutex_; + static std::queue cleanEventQueue_; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 6cd5df070..c0896ecc2 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -56,7 +56,7 @@ public: int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel, const std::string &extra); - + int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); @@ -140,12 +140,16 @@ public: int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); - void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); + void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList); + int32_t GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus); @@ -157,8 +161,10 @@ public: int32_t localUserId, const std::string &localAccountId); int32_t RegisterAuthenticationType(int32_t authenticationType); void DeleteAlwaysAllowTimeOut(); - void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); + void CheckDeleteCredential(const std::string &remoteUdid); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/i18n/dm_language_manager.h b/services/implementation/include/i18n/dm_language_manager.h index 9cbc36243..fe46455a6 100644 --- a/services/implementation/include/i18n/dm_language_manager.h +++ b/services/implementation/include/i18n/dm_language_manager.h @@ -31,9 +31,11 @@ public: DmLanguageManager() {} ~DmLanguageManager() {} std::string GetSystemParam(const std::string &key); + std::string GetSystemLanguage(); void GetLocaleByLanguage(const std::string &language, std::set &localeSet); std::string GetTextBySystemLocale(const cJSON *const textObj, const std::set &localeSet); std::string GetTextBySystemLanguage(const std::string &text); + std::string GetTextByLanguage(const std::string &text, const std::string &language); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 273db6dfb..44294f3b0 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace DistributedHardware { -const char* TAG_REPLY = "REPLY"; const char* TAG_NET_ID = "NETID"; const char* TAG_TARGET = "TARGET"; const char* TAG_APP_OPERATION = "APPOPERATION"; @@ -32,7 +31,6 @@ const char* TAG_GROUPIDS = "GROUPIDLIST"; const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; const char* TAG_DEVICE_TYPE = "DEVICETYPE"; const char* TAG_REQUESTER = "REQUESTER"; -const char* TAG_LOCAL_DEVICE_ID = "LOCALDEVICEID"; const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; const char* TAG_INDEX = "INDEX"; const char* TAG_SLICE_NUM = "SLICE"; @@ -41,44 +39,24 @@ const char* TAG_IS_SHOW_DIALOG = "IS_SHOW_DIALOG"; const char* TAG_TOKEN = "TOKEN"; const char* TAG_CRYPTO_NAME = "CRYPTONAME"; const char* TAG_CRYPTO_VERSION = "CRYPTOVERSION"; -const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; -const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; -const char* APP_THUMBNAIL = "appThumbnail"; const char* QR_CODE_KEY = "qrCode"; const char* TAG_AUTH_TOKEN = "authToken"; const char* NFC_CODE_KEY = "nfcCode"; const char* OLD_VERSION_ACCOUNT = "oldVersionAccount"; -const char* TAG_AUTH_FINISH = "isFinish"; -const char* TAG_HAVE_CREDENTIAL = "haveCredential"; const char* TAG_PUBLICKEY = "publicKey"; const char* TAG_SESSIONKEY = "sessionKey"; -const char* TAG_BIND_LEVEL = "bindLevel"; -const char* TAG_LOCAL_USERID = "localUserId"; const char* TAG_BIND_TYPE_SIZE = "bindTypeSize"; -const char* TAG_ISONLINE = "isOnline"; -const char* TAG_AUTHED = "authed"; -const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; -const char* TAG_DMVERSION = "dmVersion"; const char* TAG_HOST_PKGNAME = "hostPkgname"; -const char* TAG_TOKENID = "tokenId"; const char* TAG_HAVECREDENTIAL = "haveCredential"; const char* TAG_CONFIRM_OPERATION = "confirmOperation"; -const char* TAG_DATA = "data"; -const char* TAG_DATA_LEN = "dataLen"; const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; -const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -const char* TAG_EDITION = "edition"; -const char* TAG_BUNDLE_NAME = "bundleName"; const char* TAG_CRYPTIC_MSG = "encryptMsg"; -const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; -const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; const char* TAG_SESSIONKEY_ID = "sessionKeyId"; const int32_t MSG_MAX_SIZE = 45 * 1024; const int32_t GROUP_VISIBILITY_IS_PRIVATE = 0; const int32_t MAX_BINDTYPE_SIZE = 1000; -constexpr const char* TAG_HOST = "HOST"; constexpr const char* TAG_VISIBILITY = "VISIBILITY"; constexpr const char* TAG_APP_THUMBNAIL = "APPTHUM"; constexpr const char* TAG_THUMBNAIL_SIZE = "THUMSIZE"; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 4e3176136..f56184951 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -52,21 +52,6 @@ namespace OHOS { namespace DistributedHardware { -const int32_t AUTHENTICATE_TIMEOUT = 120; -const int32_t CONFIRM_TIMEOUT = 60; -const int32_t NEGOTIATE_TIMEOUT = 10; -const int32_t INPUT_TIMEOUT = 60; -const int32_t ADD_TIMEOUT = 10; -const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_ADD_TIMEOUT = 10; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t HML_SESSION_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -79,29 +64,11 @@ const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; -const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; const int32_t STRTOLL_BASE_10 = 10; const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms const int32_t SESSION_CLOSE_TIMEOUT = 2; -constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; -constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; -constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; -constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -constexpr const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; -constexpr const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; - -constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; -constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { - "com.example.myapplication", -}; - // clone task timeout map const std::map TASK_TIME_OUT_MAP = { { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, @@ -112,18 +79,12 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; +constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication" +}; -constexpr const char* APP_OPERATION_KEY = "appOperation"; -constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; -constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; -constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -constexpr const char* BUNDLE_NAME_KEY = "bundleName"; constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; -constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; -constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; -constexpr const char* DM_VERSION_5_0_3 = "5.0.3"; -constexpr const char* DM_VERSION_5_0_4 = "5.0.4"; -constexpr const char* DM_VERSION_5_0_5 = "5.0.5"; std::mutex g_authFinishLock; DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, @@ -232,8 +193,8 @@ int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const return ERR_DM_INPUT_PARA_INVALID; } - if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { - LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { + LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; @@ -337,8 +298,8 @@ void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) authRequestContext_->customDesc = DmLanguageManager::GetInstance(). GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get()); } - if (IsString(jsonObject, APP_THUMBNAIL)) { - authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].Get(); + if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { + authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); } CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); authRequestContext_->closeSessionDelaySeconds = 0; @@ -476,7 +437,7 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st LOGE("ReportDeleteTrustRelation failed"); } remoteDeviceId_ = udid; - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { DeleteGroup(pkgName, udid); } std::string extra = ""; @@ -525,19 +486,17 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & if (offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - offlineParam.peerUserId); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; } } - if (static_cast(bindLevel) == DEVICE && offlineParam.leftAclNumber != 0) { + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); return DM_OK; } - if (static_cast(bindLevel) == DEVICE && offlineParam.leftAclNumber == 0) { + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - offlineParam.peerUserId); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; } return ERR_DM_FAILED; @@ -552,7 +511,7 @@ int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::strin } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { DeleteGroup(pkgName, udid); } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); @@ -649,6 +608,22 @@ void DmAuthManager::OnSessionClosed(const int32_t sessionId) } } +void DmAuthManager::ClearSoftbusSessionCallback() +{ + LOGI("DmAuthManager ClearSoftbusSessionCallback"); + if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + } +} + +void DmAuthManager::PrepareSoftbusSessionCallback() +{ + LOGI("DmAuthManager PrepareSoftbusSessionCallback"); + if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(shared_from_this()); + } +} + void DmAuthManager::ProcessSourceMsg() { authRequestContext_ = authMessageProcessor_->GetRequestContext(); @@ -914,6 +889,9 @@ void DmAuthManager::HandleAuthenticateTimeout(std::string name) int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { + if (NeedInsensibleSwitching()) { + return DM_OK; + } int32_t sessionId = 0; if (IsHmlSessionType()) { CHECK_NULL_RETURN(authRequestContext_, ERR_DM_FAILED); @@ -989,7 +967,9 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->remoteDeviceName = authRequestContext_->localDeviceName; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + if (!NeedInsensibleSwitching()) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + } if (timer_ != nullptr) { timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { @@ -1042,10 +1022,10 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); NegotiateRespMsg(remoteVersion_); if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { ProcRespNegotiateExt(sessionId); timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), @@ -1101,7 +1081,7 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { ProcessAuthRequestExt(sessionId); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1305,7 +1285,7 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) LOGE("ReportAuthConfirmBox failed"); } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { return ConfirmProcessExt(action); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1552,6 +1532,9 @@ void DmAuthManager::AuthenticateFinish() authRequestStateTemp_ = nullptr; authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH; bundleName_ = ""; + if (cleanNotifyCallback_ != nullptr) { + cleanNotifyCallback_(0); + } LOGI("DmAuthManager::AuthenticateFinish complete"); } @@ -1799,9 +1782,6 @@ void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) { LOGE("ReportAuthPullPinBox failed"); } - JsonObject jsonObj; - jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = SafetyDump(jsonObj); pincodeDialogEverShown_ = true; DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1820,7 +1800,7 @@ void DmAuthManager::ShowStartAuthDialog() return; } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1859,7 +1839,7 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { return AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1920,35 +1900,26 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT); - if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { - LOGE("ReportAuthConfirmBox failed"); - } break; case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); - } break; case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); - } break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: ProcessPincode(std::atoi(params.c_str())); info.stageRes = static_cast(StageRes::STAGE_SUCC); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); - } break; default: LOGE("this action id not support"); break; } + if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { + LOGE("ReportAuthConfirmBox failed"); + } return DM_OK; } @@ -2054,7 +2025,7 @@ int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::str } int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) { struct RadarInfo info = { .funcName = "AuthenticateDevice", @@ -2138,30 +2109,6 @@ int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::strin return DM_OK; } -int32_t DmAuthManager::ParseAuthType(const std::map &bindParam, int32_t &authType) -{ - auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); - if (iter == bindParam.end()) { - LOGE("DmAuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string authTypeStr = iter->second; - if (authTypeStr.empty()) { - LOGE("DmAuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - if (authTypeStr.length() > 1) { - LOGE("DmAuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - if (!isdigit(authTypeStr[0])) { - LOGE("DmAuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - authType = std::atoi(authTypeStr.c_str()); - return DM_OK; -} - std::string DmAuthManager::ParseExtraFromMap(const std::map &bindParam) { auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); @@ -2295,26 +2242,9 @@ void DmAuthManager::RequestCredentialDone() int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey) { - LOGI("DmAuthManager::ImportCredential, deviceId %{public}s", GetAnonyString(deviceId).c_str()); + LOGI("DmAuthManager::ImportCredential"); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - // Source Import Credential - LOGI("Source Import Credential remoteUserId: %{public}d", authRequestContext_->remoteUserId); - CHECK_NULL_RETURN(authRequestContext_, ERR_DM_POINT_NULL); - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - return hiChainAuthConnector_->ImportCredential(osAccountId, authRequestContext_->remoteUserId, deviceId, - publicKey); - } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { - // Sink Import Credential - LOGI("Source Import Credential remoteUserId: %{public}d", authResponseContext_->remoteUserId); - CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - return hiChainAuthConnector_->ImportCredential(osAccountId, authResponseContext_->remoteUserId, deviceId, - publicKey); - } else { - LOGE("DmAuthManager::ImportCredential failed, authRequestState_ or authResponseState_ is invalid."); - return ERR_DM_AUTH_FAILED; - } + return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey); } void DmAuthManager::ResponseCredential() @@ -2569,7 +2499,9 @@ void DmAuthManager::PutSessionKeyAsync(int64_t requestId, std::vector guard(sessionKeyIdMutex_); int32_t sessionKeyId = 0; - int32_t ret = DeviceProfileConnector::GetInstance().PutSessionKey(hash, sessionKeyId); + int32_t ret = + DeviceProfileConnector::GetInstance().PutSessionKey(MultipleUserConnector::GetCurrentAccountUserID(), + hash, sessionKeyId); if (ret != DM_OK) { LOGI("PutSessionKey failed."); sessionKeyId = 0; @@ -2597,6 +2529,27 @@ int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId) return keyid; } +char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("DmAuthManager::AuthDeviceRequest start."); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + } + std::string deviceId = ""; + GetRemoteDeviceId(deviceId); + jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; + std::string jsonStr = SafetyDump(jsonObj); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + void DmAuthManager::GetRemoteDeviceId(std::string &deviceId) { LOGI("GetRemoteDeviceId start."); @@ -2613,7 +2566,7 @@ void DmAuthManager::CompatiblePutAcl() Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); std::string localUdidHash = static_cast(mUdidHash); DmAclInfo aclInfo; - aclInfo.bindLevel = DEVICE; + aclInfo.bindLevel = USER; aclInfo.bindType = DM_POINT_TO_POINT; aclInfo.trustDeviceId = remoteDeviceId_; if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { @@ -2675,7 +2628,7 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); authResponseContext_->haveCredential = hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, - MultipleUserConnector::GetFirstForegroundUserId(), authResponseContext_->remoteUserId); + MultipleUserConnector::GetFirstForegroundUserId()); if (!IsAuthTypeSupported(authResponseContext_->authType)) { LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; @@ -3029,21 +2982,6 @@ void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) hiChainConnector_->DeleteAllGroupByUdid(udid); } -std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition) -{ - std::string srcVersion = ""; - if (version == "" && edition != "") { - srcVersion = edition; - } else if (version == "" && edition == "") { - srcVersion = DM_VERSION_5_0_1; - } else if (version != "" && edition == "") { - srcVersion = version; - } - LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", - version.c_str(), edition.c_str(), srcVersion.c_str()); - return srcVersion; -} - std::string DmAuthManager::ConvertSinkVersion(const std::string &version) { std::string sinkVersion = ""; @@ -3089,13 +3027,13 @@ int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { - return DEVICE; + return USER; } #endif if (IsAllowDeviceBind()) { if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < DEVICE) { - return DEVICE; + static_cast(bindLevel) < USER) { + return USER; } return bindLevel; } @@ -3143,7 +3081,7 @@ int32_t DmAuthManager::GetBinderInfo() ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, authResponseContext_->peerBundleName, 0, authResponseContext_->tokenId); #ifndef DEVICE_MANAGER_COMMON_FLAG - if (ret == DM_OK && static_cast(authResponseContext_->bindLevel) != APP) { + if (ret == DM_OK && authResponseContext_->bindLevel != APP) { LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); return ERR_DM_FAILED; } @@ -3165,7 +3103,7 @@ void DmAuthManager::SetProcessInfo() } else { LOGE("DMAuthManager::SetProcessInfo failed, state is invalid."); } - } else if (static_cast(authResponseContext_->bindLevel) == DEVICE || + } else if (static_cast(authResponseContext_->bindLevel) == USER || static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { processInfo.pkgName = std::string(DM_PKG_NAME); processInfo.userId = authResponseContext_->localUserId; @@ -3284,11 +3222,6 @@ bool DmAuthManager::IsSourceMsgValid() int32_t DmAuthManager::RegisterAuthenticationType(int32_t authenticationType) { - if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && - authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - LOGE("Invalid parameter."); - return ERR_DM_INPUT_PARA_INVALID; - } authenticationType_ = authenticationType; return DM_OK; } @@ -3400,5 +3333,12 @@ void DmAuthManager::CloseAuthSession(const int32_t sessionId) CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession()); softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); } + +void DmAuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + cleanNotifyCallback_ = cleanNotifyCallback; + return; +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp new file mode 100644 index 000000000..7edf86dc6 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -0,0 +1,1070 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "app_manager.h" +#include "softbus_common.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "parameter.h" +#include "deviceprofile_connector.h" +#include "multiple_user_connector.h" + +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_random.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_device_info.h" +#include "dm_anonymous.h" +#include "dm_auth_state_machine.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "auth_manager.h" +#include "dm_auth_state.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; + +int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t closeSessionDelaySecondsMax = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +std::string GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +std::string ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +bool IsAllowDeviceBind() +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +} // namespace + +bool AuthManager::IsHmlSessionType(const std::string &sessionType) +{ + return sessionType == CONN_SESSION_TYPE_HML; +} + +AuthManager::AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainConnector = hiChainConnector; + context_->hiChainAuthConnector = hiChainAuthConnector; + context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->authenticationMap[AUTH_TYPE_NFC] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; + context_->timer = std::make_shared(); + context_->authMessageProcessor = std::make_shared(); +} + +AuthManager::~AuthManager() +{ + if (context_ != nullptr) { + context_->successFinished = true; + context_->authStateMachine = nullptr; // Release statemMachine + context_->timer->DeleteAll(); + } + bindParam_.clear(); +} + +void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + context_->cleanNotifyCallback = cleanNotifyCallback; + return; +} + +void AuthManager::SetAuthContext(std::shared_ptr context) +{ + this->context_ = context; +} + +std::shared_ptr AuthManager::GetAuthContext() +{ + return this->context_; +} + +int32_t AuthManager::GeneratePincode() +{ + LOGI("AuthManager::GeneratePincode start"); + context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + return context_->pinCode; +} + +int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::RegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->RegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::UnRegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGI("AuthManager::UnAuthenticateDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + if (authCode.empty() || pkgName.empty()) { + LOGE("ImportAuthCode failed, authCode or pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->importAuthCode = authCode; + context_->importPkgName = pkgName; + + if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { + context_->pinCode = std::stoi(authCode.c_str()); + } else { + AuthSinkStatePinAuthComm::GeneratePincode(context_); + } + LOGI("AuthManager::ImportAuthCode ok"); + return DM_OK; +} + +int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGI("AuthManager::UnBindDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) +{ + (void)pkgName; + LOGI("AuthManager::StopAuthenticateDevice start"); + + context_->reason = STOP_BIND; + if (context_->direction == DM_AUTH_SOURCE) { + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + context_->authStateMachine->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +void AuthManager::OnScreenLocked() +{ + LOGI("AuthManager::OnScreenLocked start"); + if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); + return; + } + context_->reason = ERR_DM_BIND_USER_CANCEL; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); +} + +void AuthManager::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("AuthManager::HandleDeviceNotTrust start"); +} + +int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) +{ + context_->confirmOperation = static_cast(authenticationType); + return DM_OK; +} + +int32_t AuthManager::GetReason() +{ + return context_->reason; +} + +// Save the key +void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); + LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); +} + +char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + return nullptr; +} + +void AuthManager::SetAuthType(int32_t authType) +{ + context_->authType = (DmAuthType)authType; +} + +bool AuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +bool AuthManager::IsAuthCodeReady(const std::string &pkgName) +{ + if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { + LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and pkgName %{public}s.", + context_->importAuthCode.c_str(), context_->importPkgName.c_str()); + return false; + } + if (pkgName != context_->importPkgName) { + LOGE("AuthManager::IsAuthCodeReady pkgName %{public}s not supported with import pkgName %{public}s.", + pkgName.c_str(), context_->importPkgName.c_str()); + return false; + } + return true; +} + +int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (pkgName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + JsonObject jsonObject(extra); + if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) || + jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get() != CONN_SESSION_TYPE_HML) && + !context_->softbusConnector->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && + (!IsAuthCodeReady(pkgName))) { + LOGE("Auth code not exist."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); + } + if (!IsHmlSessionType(context_->connSessionType)) { + return; + } + if(context_->connDelayCloseTime == 0){ + context_->connDelayCloseTime = HML_SESSION_TIMEOUT; + } + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); + } + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) { + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (IsNumberString(actionIdStr)) { + context_->hmlActionId = std::atoi(actionIdStr.c_str()); + } + if (context_->hmlActionId <= 0) { + context_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", context_->hmlActionId); + } + + return; +} + +std::string AuthManager::GetBundleName(const JsonObject &jsonObject) +{ + if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { + return jsonObject[BUNDLE_NAME_KEY].Get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +void AuthManager::ParseJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + return; + } + + if (jsonObject[APP_OPERATION_KEY].IsString()) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); + } + if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); + } + if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) { + context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); + } + context_->connDelayCloseTime = 0; + if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); + context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); + } + + context_->accesser.bundleName = GetBundleName(jsonObject); + context_->accessee.bundleName = context_->accesser.bundleName; + + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString() && !jsonObject[TAG_PEER_BUNDLE_NAME].Get().empty()) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + context_->accessee.oldBundleName = context_->accessee.bundleName; + } else { + context_->accessee.oldBundleName = context_->pkgName; + } + + context_->accesser.pkgName = context_->pkgName; + context_->accessee.pkgName = context_->accesser.pkgName; + + if (jsonObject[TAG_PEER_PKG_NAME].IsString()) { + context_->accessee.pkgName = jsonObject[TAG_PEER_PKG_NAME].Get(); + } + + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); + } + if (jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) { + context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get(); + } else { + context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); + } + ParseHmlInfoInJsonObject(jsonObject); + return; +} + +int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) +{ + int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); + } + return ret; +} + +bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) +{ + if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); + return true; + } + if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); + return true; + } + return false; +} + +int32_t GetBindLevel(int32_t bindLevel) +{ +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); + std::string processName = ""; + int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); + LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); + if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { + return USER; + } +#endif + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < USER) { + return USER; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param with pkgName %{public}s and extra %{public}s.", pkgName.c_str(), extra.c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context_->accesser.deviceId = std::string(localDeviceId); + context_->pkgName = pkgName; + context_->pkgLabel = GetBundleLable(pkgName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); + context_->accesser.isOnline = false; + uint32_t callingTokenId = 0; + MultipleUserConnector::GetCallingTokenId(callingTokenId); + context_->accesser.tokenId = static_cast(callingTokenId); + + context_->accessee.deviceId = deviceId; + context_->accessee.addr = deviceId; + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); + + // compatible for old version + context_->accesser.oldBindLevel = INVALIED_TYPE; + CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel); + context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel); + + context_->accesser.bindLevel = DmRole::DM_ROLE_FA; + if (AppManager::GetInstance().IsSystemApp()) { + context_->accesser.bindLevel = DmRole::DM_ROLE_FA; + } + if (AppManager::GetInstance().IsSystemSA()) { + context_->accesser.bindLevel = DmRole::DM_ROLE_SA; + } + if (DmAuthState::CheckProcessNameInWhiteList(context_->accesser.bundleName)) { + context_->accesser.bindLevel = DmRole::DM_ROLE_USER; + } +} + +void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = context_->authenticationMap.find(authType); + if (iter != context_->authenticationMap.end()) { + context_->authPtr = iter->second; + } + + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + GetAuthParam(pkgName, authType, deviceId, extra); + context_->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthManager::AuthenticateDevice complete"); + + return; +} + +int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + context_->processInfo.pkgName = pkgName; + context_->processInfo.userId = userId; + int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + context_->isAuthenticateDevice = true; + if (authType == AUTH_TYPE_CRE) { + LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); + context_->softbusConnector->JoinLnn(deviceId, true); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, + "", STATUS_DM_AUTH_DEFAULT, DM_OK); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + return DM_OK; + } + InitAuthState(pkgName, authType, deviceId, extra); + return DM_OK; +} + +int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) +{ + int ret = DM_OK; + LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str()); + for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { + LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); + } + + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (pkgName.empty()) { + LOGE("AuthManager::BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->peerTargetId = targetId_; + bindParam_ = bindParam; + if (!targetId.deviceId.empty()) { + ret = AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + if (ret != DM_OK) { + return ret; + } + } else { + LOGE("AuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } + + context_->sessionId = sessionId; + context_->logicalSessionId = logicalSessionId; + context_->requestId = static_cast(logicalSessionId); + context_->authStateMachine->TransitionTo(std::make_shared()); + info = { .funcName = "BindTarget" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + return ret; +} + +AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SINK; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSinkManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; + context_->authStateMachine->TransitionTo(std::make_shared()); + } + + return; +} + +bool AuthSinkManager::GetIsCryptoSupport() +{ + return false; +} + +void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!jsonObject[TAG_DATA].IsString() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[TAG_DATA].Get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; +} + +void AuthManager::GetRemoteDeviceId(std::string &deviceId) +{ + deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; + return; +} + +int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSinkManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: + context_->confirmOperation = static_cast(action); + context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH."); + context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); + context_->confirmOperation = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + context_->reason = ERR_DM_TIME_OUT; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); + context_->confirmOperation = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSinkManager::OnUserOperation leave."); + return DM_OK; +} + +AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SOURCE; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSrcManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSrcManager::OnSessionDisable() +{ + context_->sessionId = -1; +} + +void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; + context_->authStateMachine->TransitionTo(std::make_shared()); + } + + return; +} + +bool AuthSrcManager::GetIsCryptoSupport() +{ + return false; +} + +void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!jsonObject[TAG_DATA].IsNumberInteger() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[TAG_DATA].Get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; +} + +int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSrcManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user cancel"); + context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user input done"); + context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + { + if (!IsNumberString(params)) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->pinCode = std::stoi(params); + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSrcManager::OnUserOperation leave."); + return DM_OK; +} + +void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSrcManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSrcManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSrcManager::AuthDeviceError leave."); +} + +void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSinkManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSinkManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSinkManager::AuthDeviceError leave."); +} + +bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSrcManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSrcManager::AuthDeviceTransmit leave."); + return true; +} + +bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSinkManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSinkManager::AuthDeviceTransmit leave."); + return true; +} + +void AuthSrcManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSrcManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + // Perform business processing based on the current state + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + switch (curState) { + case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE: + // ON_FINISH event occurs, start credential exchange + context_->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + break; + } + LOGI("AuthSrcManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSinkManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + LOGI("AuthSinkManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); +} + +char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + } + } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { + if (context_->isOnline) { // Non-first time certification + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else if (!context_->isAppCredentialVerified) { // First-time authentication && appCred auth + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else { // First-time authentication && User credential authentication + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId; + } + } + jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + std::string jsonStr = jsonObj.Dump(); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +int32_t AuthManager::GetPinCode(int32_t &code) +{ + if (context_ == nullptr) { + LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("GetPinCode called."); + code = context_->pinCode; + return DM_OK; +} + +// Reacquire BindParams to rebuild the link, generally used when switching between old and new protocol objects +void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + pkgName = context_->pkgName; + targetId = targetId_; + bindParam = bindParam_; + + LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); + return; +} + +void AuthManager::SetBindTargetParams(const PeerTargetId &targetId) +{ + targetId_ = targetId; + LOGI("AuthManager::SetBindTargetParams set targetId to reuse"); + return; +} + +void AuthManager::ClearSoftbusSessionCallback() +{} + +void AuthManager::PrepareSoftbusSessionCallback() +{} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp new file mode 100644 index 000000000..0b913a0b4 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "auth_manager.h" +#include "deviceprofile_connector.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms + +// Received 180 synchronization message, send 190 message +int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkDataSyncState::Action start"); + // Query the ACL of the sink end. Compare the ACLs at both ends. + context->softbusConnector->SyncLocalAclListProcess(context->accessee.deviceId, context->accessee.userId, + context->accesser.deviceId, context->accesser.userId, context->accesser.aclStrList); + + // Synchronize the local SP information, the format is uncertain, not done for now + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); + LOGI("AuthSinkDataSyncState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSinkDataSyncState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE; +} + +// Received 190 message, sent 200 message +int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcDataSyncState::Action start"); + + if (NeedAgreeAcl(context)) { + // Query the ACL of the sink end. Compare the ACLs at both ends. + context->softbusConnector->SyncLocalAclListProcess(context->accesser.deviceId, context->accesser.userId, + context->accessee.deviceId, context->accessee.userId, context->accessee.aclStrList); + + // Save this acl + SetAclInfo(context); + context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); + // Synchronize the local SP information, the format is uncertain, not done for now + } + + // Trigger networking + if (!context->accesser.isOnline) { + if (context->connSessionType == CONN_SESSION_TYPE_HML) { + context->softbusConnector->JoinLnnByHml(context->sessionId, context->accesser.transmitSessionKeyId, + context->accessee.transmitSessionKeyId); + } else { + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("AuthSrcDataSyncState joinLnn get udidhash by udid: %{public}s failed", + context->accessee.deviceId.c_str()); + return ERR_DM_FAILED; + } + std::string peerUdidHash = std::string(udidHashTmp); + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->accesser.transmitSessionKeyId, + context->accessee.transmitSessionKeyId, context->accessee.addr, peerUdidHash); + } + } + context->reason = DM_OK; + context->reply = DM_OK; + context->state = static_cast(GetStateType()); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + LOGI("AuthSrcDataSyncState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSrcDataSyncState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE; +} + +// Received 200 end message, send 201 +int32_t AuthSinkFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkFinishState::Action start"); + context->state = static_cast(GetStateType()); + SinkFinish(context); + LOGI("AuthSinkFinishState::Action ok"); + if (context->cleanNotifyCallback != nullptr) { + context->cleanNotifyCallback(context->logicalSessionId); + } + + return DM_OK; +} + +DmAuthStateType AuthSinkFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_FINISH_STATE; +} + +// Received 201 end message +int32_t AuthSrcFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcFinishState::Action start"); + if (context->reason != DM_OK) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + } + SourceFinish(context); + LOGI("AuthSrcFinishState::Action ok"); + std::shared_ptr tempContext = context; + auto taskFunc = [this, tempContext]() { + if (tempContext->cleanNotifyCallback != nullptr) { + tempContext->cleanNotifyCallback(tempContext->logicalSessionId); + } + }; + const int64_t MICROSECOND_PER_SECOND = 1000000L; + int32_t delaySeconds = context->connDelayCloseTime; + if (context->reason != DM_OK && context->reason != DM_ALREADY_AUTHED) { + delaySeconds = 0; + } + ffrt::submit(taskFunc, ffrt::task_attr().delay(delaySeconds * MICROSECOND_PER_SECOND)); + return DM_OK; +} + +DmAuthStateType AuthSrcFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FINISH_STATE; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp new file mode 100644 index 000000000..4d201c719 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -0,0 +1,738 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "auth_manager.h" +#include "access_control_profile.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_negotiate_process.h" +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char* TAG_CRED_ID = "credId"; +constexpr const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; +constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; +constexpr const char* TAG_REQUESTER = "REQUESTER"; +constexpr const char* UNVALID_CREDTID = "invalidCredId"; +// authType fallback table +using FallBackKey = std::pair; // accessee.bundleName, authType +static std::map g_pinAuthTypeFallBackMap = { + {{"CastEngineService", DmAuthType::AUTH_TYPE_NFC}, DmAuthType::AUTH_TYPE_PIN}, +}; +// Maximum number of recursive lookups +constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; + +DmAuthStateType AuthSrcConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; +} + +void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", + accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); + if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + return; + } + if (accesseeCredTypeList.Contains("identicalCredType") && accesserCredTypeList.Contains("identicalCredType")) { + LOGI("have identical credential."); + credTypeNegoResult["identicalCredType"] = DM_IDENTICAL_ACCOUNT; + context->accesser.isGenerateLnnCredential = false; + } + if (accesseeCredTypeList.Contains("shareCredType") && accesserCredTypeList.Contains("shareCredType")) { + LOGI("have share credential."); + credTypeNegoResult["shareCredType"] = DM_SHARE; + context->accesser.isGenerateLnnCredential = false; + } + if (accesseeCredTypeList.Contains("pointTopointCredType") && + accesserCredTypeList.Contains("pointTopointCredType")) { + LOGI("have point_to_point credential."); + credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; + } + if (accesseeCredTypeList.Contains("lnnCredType") && accesserCredTypeList.Contains("lnnCredType")) { + LOGI("have lnn credential."); + credTypeNegoResult["lnnCredType"] = DM_LNN; + context->accesser.isGenerateLnnCredential = false; + } +} + +void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeAclList; + accesseeAclList.Parse(context->accessee.aclTypeList); + JsonObject accesserAclList; + accesserAclList.Parse(context->accesser.aclTypeList); + LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", + accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); + if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { + LOGE("aclList invalid."); + return; + } + if (accesseeAclList.Contains("identicalAcl") && accesserAclList.Contains("identicalAcl")) { + LOGI("have identical acl."); + aclNegoResult["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accesser.isAuthed = true; + context->accesser.isPutLnnAcl = false; + } + if (accesseeAclList.Contains("shareCredType") && accesserAclList.Contains("shareCredType")) { + LOGI("have share acl."); + aclNegoResult["shareAcl"] = DM_SHARE; + context->accesser.isAuthed = true; + context->accesser.isPutLnnAcl = false; + } + if (accesseeAclList.Contains("pointTopointAcl") && accesserAclList.Contains("pointTopointAcl")) { + LOGI("have point_to_point acl."); + aclNegoResult["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("lnnAcl") && accesserAclList.Contains("lnnAcl")) { + LOGI("have lnn acl."); + aclNegoResult["lnnAcl"] = DM_LNN; + context->accesser.isPutLnnAcl = false; + } +} + +void AuthSrcConfirmState::GetSrcCredType(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson) +{ + CHECK_NULL_VOID(context); + std::vector deleteCredInfo; + for (const auto &item : credInfo.Items()) { + if (!item.Contains(FILED_CRED_TYPE) || !item[FILED_CRED_TYPE].IsNumberInteger() || + !item.Contains(FILED_CRED_ID) || !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + int32_t credType = item[FILED_CRED_TYPE].Get(); + LOGI("credType %{public}d.", credType); + switch (credType) { + case DM_IDENTICAL_ACCOUNT: + credTypeJson["identicalCredType"] = credType; + context->accesser.credentialInfos[credType] = item.Dump(); + break; + case DM_SHARE: + credTypeJson["shareCredType"] = credType; + context->accesser.credentialInfos[credType] = item.Dump(); + break; + case DM_POINT_TO_POINT: + if (!aclInfo.Contains("pointTopointAcl") || + (context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != + item[FILED_CRED_ID].Get() && + context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != + item[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + } else { + credTypeJson["pointTopointCredType"] = credType; + context->accesser.credentialInfos[credType] = item.Dump(); + } + break; + case DM_LNN: + if (!aclInfo.Contains("lnnAcl") || + (context->accesser.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != + item[FILED_CRED_ID].Get() && + context->accesser.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != + item[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + } else { + credTypeJson["lnnCredType"] = credType; + context->accesser.credentialInfos[credType] = item.Dump(); + } + break; + default: + LOGE("invalid credType %{public}d.", credType); + break; + } + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, item); + } +} + +void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + uint32_t bindLevel = DM_INVALIED_TYPE; + for (const auto &item : profiles) { + std::string trustDeviceId = item.GetTrustDeviceId(); + std::string trustDeviceIdHash = Crypto::Sha256(trustDeviceId); + if ((trustDeviceIdHash != context->accessee.deviceIdHash && + trustDeviceIdHash != context->accesser.deviceIdHash)) { + LOGE("devId %{public}s hash %{public}s, accesser devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), + GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); + continue; + } + bindLevel = item.GetBindLevel(); + switch (item.GetBindType()) { + case DM_IDENTICAL_ACCOUNT: + if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { + aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accesser.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; + } + break; + case DM_SHARE: + if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_SHARE)) { + aclInfo["shareAcl"] = DM_SHARE; + context->accesser.aclProfiles[DM_SHARE] = item; + } + break; + case DM_POINT_TO_POINT: + if (Point2PointAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_POINT_TO_POINT)) { + aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accesser.aclProfiles[DM_POINT_TO_POINT] = item; + } + if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accesser.aclProfiles[DM_LNN] = item; + } + break; + default: + LOGE("invalid bindType %{public}d.", item.GetBindType()); + break; + } + } + if (aclInfo.Contains("pointTopointAcl") && !aclInfo.Contains("lnnAcl") && bindLevel != USER) { + aclInfo.Erase("pointTopointAcl"); + DeleteAcl(context, context->accesser.aclProfiles[DM_POINT_TO_POINT]); + } +} + +bool AuthSrcConfirmState::CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) +{ + LOGI("start."); + std::string credId = profile.GetAccesser().GetAccesserCredentialIdStr(); + if (!credInfo.Contains(credId)) { + credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); + if (!credInfo.Contains(credId)) { + LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + DeleteAcl(context, profile); + return false; + } + } + if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || + !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { + LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); + DeleteAcl(context, profile); + credInfo.Erase(credId); + return false; + } + bool checkResult = false; + switch (bindType) { + LOGI("bindType %{public}d.", bindType); + case DM_IDENTICAL_ACCOUNT: + case DM_SHARE: + case DM_LNN: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + break; + case DM_POINT_TO_POINT: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + const size_t APP_LIST_SIZE = 2; + if (appList.size() >= APP_LIST_SIZE && + ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || + (std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0]))) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + } + break; + default: + break; + } + return checkResult; +} + +bool AuthSrcConfirmState::IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start."); + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; +} + +bool AuthSrcConfirmState::ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start."); + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; +} + +bool AuthSrcConfirmState::Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start."); + return (accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + accesser.GetAccesserTokenId() == context->accesser.tokenId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash) || + (accessee.GetAccesseeDeviceId() == context->accesser.deviceId && + accessee.GetAccesseeUserId() == context->accesser.userId && + accessee.GetAccesseeTokenId() == context->accesser.tokenId && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accessee.tokenIdHash); +} + +bool AuthSrcConfirmState::LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start."); + return ((accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId) || + (accessee.GetAccesseeDeviceId() == context->accesser.deviceId && + accessee.GetAccesseeUserId() == context->accesser.userId)) && + accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == "" && + (Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash || + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash) && + accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == ""; +} + +void AuthSrcConfirmState::GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo) +{ + LOGI("start."); + CHECK_NULL_VOID(context); + // get identical credential + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + GetIdenticalCredentialInfo(context, credInfo); + } + // get share credential + if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountIdHash != Crypto::Sha256("ohosAnonymousUid") && + context->accessee.accountIdHash != Crypto::Sha256("ohosAnonymousUid")) { + GetShareCredentialInfo(context, credInfo); + GetP2PCredentialInfo(context, credInfo); + } + // get point_to_point credential + if (context->accesser.accountIdHash == Crypto::Sha256("ohosAnonymousUid") || + context->accessee.accountIdHash == Crypto::Sha256("ohosAnonymousUid")) { + GetP2PCredentialInfo(context, credInfo); + } + std::vector deleteCredInfo; + for (auto &item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 + uint32_t credType = DmAuthState::GetCredentialType(context, item); + if (credType == DM_INVALIED_TYPE || !item.Contains(FILED_CRED_TYPE) || + !item[FILED_CRED_TYPE].IsNumberInteger() || !item.Contains(FILED_CRED_ID) || + !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + item[FILED_CRED_TYPE] = credType; + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSrcConfirmState::GetIdenticalCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + LOGI("start."); + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID] = context->accesser.deviceId; + queryParams[FILED_USER_ID] = context->accesser.accountId; + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSrcConfirmState::GetShareCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + LOGI("start."); + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accessee.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSrcConfirmState::GetP2PCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + LOGI("start."); + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accessee.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +int32_t AuthSrcConfirmState::Action(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + // check version compatibility + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { + LOGE("incompatible version %{public}s compare to 5.1.0", + context->accessee.dmVersion.c_str()); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + context->accessee.isOnline = SoftbusCache::GetInstance().CheckIsOnline(context->accessee.deviceIdHash); + JsonObject credInfo; + GetSrcCredentialInfo(context, credInfo); + JsonObject aclInfo; + GetSrcAclInfo(context, credInfo, aclInfo); + context->accesser.aclTypeList = aclInfo.Dump(); + JsonObject credTypeJson; + GetSrcCredType(context, credInfo, aclInfo, credTypeJson); + context->accesser.credTypeList = credTypeJson.Dump(); + // update credType negotiate result + JsonObject credTypeNegoResult; + NegotiateCredential(context, credTypeNegoResult); + context->accesser.credTypeList = credTypeNegoResult.Dump(); + // update acl negotiate result + JsonObject aclNegoResult; + NegotiateAcl(context, aclNegoResult); + context->accesser.aclTypeList = aclNegoResult.Dump(); + + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); + context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + +DmAuthStateType AuthSinkConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CONFIRM_STATE; +} + +int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowConfigDialog start"); + + if (IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowStartAuthDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + JsonObject jsonObj; + jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; + jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; + jsonObj[TAG_REQUESTER] = context->accesser.deviceName; + jsonObj[TAG_USER_ID] = context->accessee.userId; // Reserved + jsonObj[TAG_HOST_PKGLABEL] = context->pkgName; + + const std::string params = jsonObj.Dump(); + DmDialogManager::GetInstance().ShowConfirmDialog(params); + + LOGI("AuthSinkConfirmState::ShowConfigDialog end"); + return DM_OK; +} + +void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", + accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); + if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + return; + } + if (accesseeCredTypeList.Contains("identicalCredType") && accesserCredTypeList.Contains("identicalCredType")) { + LOGI("have identical credential."); + credTypeNegoResult["identicalCredType"] = DM_IDENTICAL_ACCOUNT; + context->accessee.isGenerateLnnCredential = false; + } + if (accesseeCredTypeList.Contains("shareCredType") && accesserCredTypeList.Contains("shareCredType")) { + LOGI("have share credential."); + credTypeNegoResult["shareCredType"] = DM_SHARE; + context->accessee.isGenerateLnnCredential = false; + } + if (accesseeCredTypeList.Contains("pointTopointCredType") && + accesserCredTypeList.Contains("pointTopointCredType")) { + LOGI("have point_to_point credential."); + credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; + } + if (accesseeCredTypeList.Contains("lnnCredType") && accesserCredTypeList.Contains("lnnCredType")) { + LOGI("have lnn credential."); + credTypeNegoResult["lnnCredType"] = DM_LNN; + context->accessee.isGenerateLnnCredential = false; + } + return; +} + +void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeAclList; + accesseeAclList.Parse(context->accessee.aclTypeList); + JsonObject accesserAclList; + accesserAclList.Parse(context->accesser.aclTypeList); + LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", + accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); + if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { + LOGE("aclList invalid."); + return; + } + if (accesseeAclList.Contains("identicalAcl") && accesserAclList.Contains("identicalAcl")) { + LOGI("have identical acl."); + aclNegoResult["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accessee.isPutLnnAcl = false; + context->accessee.isAuthed = true; + } + if (accesseeAclList.Contains("shareCredType") && accesserAclList.Contains("shareCredType")) { + LOGI("have share acl."); + aclNegoResult["shareAcl"] = DM_SHARE; + context->accessee.isPutLnnAcl = false; + context->accessee.isAuthed = true; + } + if (accesseeAclList.Contains("pointTopointAcl") && accesserAclList.Contains("pointTopointAcl")) { + LOGI("have point_to_point acl."); + aclNegoResult["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accessee.isAuthed = true; + } + if (accesseeAclList.Contains("lnnAcl") && accesserAclList.Contains("lnnAcl")) { + LOGI("have lnn acl."); + aclNegoResult["lnnAcl"] = DM_LNN; + context->accessee.isPutLnnAcl = false; + } +} + +void AuthSinkConfirmState::MatchFallBackCandidateList( + std::shared_ptr context, DmAuthType authType) +{ + for (size_t i = 0; i < MAX_FALLBACK_LOOPKUP_TIMES; i++) { + auto it = g_pinAuthTypeFallBackMap.find({context->accessee.bundleName, authType}); + if (it != g_pinAuthTypeFallBackMap.end()) { + authType = it->second; + context->authTypeList.push_back(authType); + } else { + break; + } + } +} + +void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr context) +{ + // query ServiceInfo by accessee.bundleName and authType from client + OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; + auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( + context->accessee.bundleName, context->authType, srvInfo); + if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { + LOGI("AuthSinkConfirmState::ReadServiceInfo found"); + // ServiceInfo found + context->serviceInfoFound = true; + context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + std::string pinCode = srvInfo.GetPinCode(); // read pincode + if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { + context->pinCode = std::stoi(pinCode.c_str()); + } + srvInfo.SetPinCode("******"); + DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(srvInfo); + } + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box + int32_t confirmOperation = srvInfo.GetAuthType(); // read confirmOperation + if (confirmOperation == 0) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; + } else if (confirmOperation == OHOS::DistributedDeviceProfile::NUM_1) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } else if (confirmOperation == OHOS::DistributedDeviceProfile::NUM_6) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } else { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } + } + context->customData = srvInfo.GetDescription(); // read customData + } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { + // only special scenarios can import pincode + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box + } else { + // not special scenarios, reset confirmOperation to cancel + context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box + } +} + +int32_t AuthSinkConfirmState::Action(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject credTypeNegoResult; + JsonObject aclNegoResult; + NegotiateCredential(context, credTypeNegoResult); + context->accessee.credTypeList = credTypeNegoResult.Dump(); + NegotiateAcl(context, aclNegoResult); + context->accessee.aclTypeList = aclNegoResult.Dump(); + if (credTypeNegoResult.Dump() != context->accesser.credTypeList || + aclNegoResult.Dump() != context->accesser.aclTypeList) { + LOGE("compability negotiate not match."); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + int32_t ret = NegotiateProcess::GetInstance().HandleNegotiateResult(context); + if (ret != DM_OK) { + LOGE("HandleNegotiateResult failed ret %{public}d.", ret); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ret; + } + if (context->needBind) { + return ProcessBindAuthorize(context); + } else { + return ProcessNoBindAuthorize(context); + } +} + +int32_t AuthSinkConfirmState::ProcessBindAuthorize(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + ReadServiceInfo(context); + context->authTypeList.clear(); + context->authTypeList.push_back(context->authType); + MatchFallBackCandidateList(context, context->authType); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + (context->serviceInfoFound || AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) && + context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_1) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (ShowConfigDialog(context) != DM_OK) { + LOGE("ShowConfigDialog failed"); + context->reason = ERR_DM_SHOW_CONFIRM_FAILED; + return ERR_DM_FAILED; + } + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGE("AuthSinkConfirmState::Action ON_USER_OPERATION err"); + return ERR_DM_FAILED; + } + if (context->confirmOperation == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGE("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_FAILED; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + return ERR_DM_FAILED; +} + +int32_t AuthSinkConfirmState::ProcessNoBindAuthorize(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + if (accesseeCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + if (accesseeCredTypeList.Contains("identicalCredType")) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_IDENTICAL_ACCOUNT); + } else if (accesseeCredTypeList.Contains("shareCredType")) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_SHARE); + } else if (accesseeCredTypeList.Contains("pointTopointCredType")) { + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_POINT_TO_POINT); + } else if (accesseeCredTypeList.Contains("lnnCredType")) { + context->accessee.lnnCredentialId = GetCredIdByCredType(context, DM_LNN); + } else { + LOGE("credTypeList invalid."); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string AuthSinkConfirmState::GetCredIdByCredType(std::shared_ptr context, int32_t credType) +{ + LOGI("credType %{public}d.", credType); + CHECK_NULL_RETURN(context, UNVALID_CREDTID); + if (context->accessee.credentialInfos.find(credType) != context->accessee.credentialInfos.end()) { + LOGE("invalid credType."); + return UNVALID_CREDTID; + } + std::string credInfoStr = context->accessee.credentialInfos[credType]; + LOGI("yangwei credInfoStr %{public}s.", credInfoStr.c_str()); + JsonObject credInfoJson; + credInfoJson.Parse(credInfoStr); + if (credInfoJson.IsDiscarded() || !credInfoJson.Contains(FILED_CRED_ID) || + !credInfoJson[FILED_CRED_ID].IsNumberInteger()) { + LOGE("credInfoStr invalid."); + return UNVALID_CREDTID; + } + return credInfoJson[FILED_CRED_ID].Get(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp new file mode 100644 index 000000000..9f1169a0c --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_message_processor.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "deviceprofile_connector.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +namespace { + +// tag in Lowercase, need by hichain tag +constexpr const char* TAG_LOWER_DEVICE_ID = "deviceId"; +constexpr const char* TAG_LOWER_USER_ID = "userId"; + +constexpr const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; + +// decrypt process +int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) +{ + if (context->transmitData.empty()) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData failed."); + return ERR_DM_FAILED; + } + + int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthCredentialTransmitDecryptProcess: ProcessCredData transmit data failed"); + return ERR_DM_FAILED; + } + + if (context->authStateMachine->WaitExpectEvent(event) != event) { + LOGE("AuthCredentialTransmitDecryptProcess: Hichain auth transmit data failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AuthCredentialTransmitSend(std::shared_ptr context, DmMessageType msgType) +{ + if (context->transmitData.empty()) { + LOGE("AuthCredentialTransmitSend: Get onTransmitData failed."); + return ERR_DM_FAILED; + } + + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); + if (message.empty()) { + LOGE("AuthCredentialTransmitSend: CreateMessage AuthCredential transmit data failed"); + return ERR_DM_FAILED; + } + + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +void SetAuthContext(int32_t skId, int64_t &appSkTimeStamp, int32_t &appSessionKeyId) +{ + appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + appSessionKeyId = skId; + return; +} + +} + +DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} + +// Parse the ontransmit data, respond with 161 message +int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + // decrypt and transmit transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + // Send 161 message + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE); +} + +DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE; +} + +int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) +{ + // decrypt and transmit transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); + if (ret != DM_OK) { + return ret; + } + + // Authentication completion triggers the Onfinish callback event. + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + DmMessageType msgType; + int32_t skId; + ret = context->authMessageProcessor->SaveSessionKeyToDP(context->accesser.userId ,skId); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); + return ret; + } + + // first time joinLnn, auth lnnCredential + if (context->accesser.isGenerateLnnCredential == true && context->isAppCredentialVerified == false && + context->accesser.bindLevel != USER) { + context->isAppCredentialVerified = true; + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); + msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; + ret = context->hiChainAuthConnector->AuthCredential(context->accesser.userId, context->requestId, + context->accesser.lnnCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); + return ret; + } + + // wait for onTransmit event + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthDoneState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } + // First-time authentication and Lnn credential process + } else if (context->accesser.isGenerateLnnCredential == true && context->accesser.bindLevel != USER) { + SetAuthContext(skId, context->accesser.lnnSkTimeStamp, context->accesser.lnnSessionKeyId); + msgType = MSG_TYPE_REQ_DATA_SYNC; + } else { // Non-first-time authentication transport credential process + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); + msgType = MSG_TYPE_REQ_DATA_SYNC; + } + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); + if (message.empty()) { + LOGE("AuthSrcCredentialAuthDoneState::Action CreateMessage failed"); + return ERR_DM_FAILED; + } + + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSinkCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE; +} + +int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr context) +{ + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START); +} + +DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} + +int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + // Construct and send 171 message + ret = AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE); + if (ret != DM_OK) { + return ret; + } + + if (context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED) != ON_SESSION_KEY_RETURNED) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + int32_t skId; + ret = context->authMessageProcessor->SaveSessionKeyToDP(context->accessee.userId, skId); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action DP save user session key failed"); + return ret; + } + + // First lnn cred auth, second time receiving 161 message + if (context->accessee.isGenerateLnnCredential == true && context->accessee.bindLevel != USER && + context->isAppCredentialVerified == true) { + context->accessee.lnnSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->accessee.lnnSessionKeyId = skId; + } else { // Twice transport cred auth + context->isAppCredentialVerified = true; + context->accessee.transmitSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->accessee.transmitSessionKeyId = skId; + } + return DM_OK; +} + +// Generate the json string of authParams in the credential negotiation state +std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authorizedScope, + DmAuthCredentialAddMethod method, const std::shared_ptr &authContext) +{ + LOGI("AuthCredentialAgreeState::CreateAuthParamsString start."); + + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + (method != DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE && method != DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT)) { + return std::string(""); + } + + JsonObject jsonObj; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { + jsonObj[TAG_METHOD] = method; + } + + jsonObj[TAG_LOWER_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); + } + jsonObj[TAG_LOWER_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); + jsonObj[TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; + jsonObj[TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + jsonObj[TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; + jsonObj[TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; + jsonObj[TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); + } + jsonObj[TAG_AUTHORIZED_SCOPE] = authorizedScope; + if (authorizedScope == DM_AUTH_SCOPE_APP) { + std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), + std::to_string(authContext->accessee.tokenId)}; + jsonObj[TAG_AUTHRIZED_APP_LIST] = tokenIds; + } + jsonObj[TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; + + LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); + return jsonObj.Dump(); +} + +// Generate credential ID and public key +int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + LOGI("authorizedScope %{public}d.", static_cast(authorizedScope)); + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + authContext == nullptr || authContext->hiChainAuthConnector == nullptr) { + return ERR_DM_FAILED; + } + + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + int32_t osAccountId = (authContext->direction == DM_AUTH_SOURCE) ? + authContext->accesser.userId : authContext->accessee.userId; + std::string credId; + int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, add credential failed."); + return ret; + } + + std::string publicKey; + ret = authContext->hiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey(), export publicKey failed."); + authContext->hiChainAuthConnector->DeleteCredential(osAccountId, credId); + return ret; + } + + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey credId=%{public}s, publicKey=%{public}s.\n", + authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str(), + authContext->GetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str()); + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey leave."); + return DM_OK; +} + +// Get the negotiation credential ID by agree credential +int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + LOGI("AuthCredentialAgreeState::AgreeCredential start."); + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || authContext == nullptr) { + return ERR_DM_FAILED; + } + + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::AgreeCredential error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? + authContext->accesser.userId : authContext->accessee.userId; + std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); + std::string credId; + LOGI("AuthCredentialAgreeState::AgreeCredential agree with accountId %{public}d and param %{public}s.", + osAccountId, authParamsString.c_str()); + int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, + authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::AgreeCredential error, agree credential failed."); + return ret; + } + + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + LOGI("AuthCredentialAgreeState::AgreeCredential leave."); + return DM_OK; +} + +DmAuthStateType AuthSrcCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcCredentialExchangeState::Action() start."); + int32_t ret = ERR_DM_FAILED; + context->isAppCredentialVerified = false; + + if (!NeedAgreeAcl(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + + if (!NeedAgreeCredential(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + + // First authentication, generate LNN credentials and public key + if (context->accesser.isGenerateLnnCredential && context->accesser.bindLevel != USER) { + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate user credId and publicKey failed."); + return ret; + } + } + + // Generate transmit credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate app credId and publicKey failed."); + return ret; + } + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSrcCredentialExchangeState::Action() leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSinkCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkCredentialExchangeState::Action start."); + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId; + int32_t osAccountId = context->accessee.userId; + context->isAppCredentialVerified = false; + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + // First authentication lnn cred + if (context->accessee.isGenerateLnnCredential && context->accessee.bindLevel != USER) { + // Generate credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate user cred and publicKey failed."); + return ret; + } + + // Agree credentials + tmpCredId = context->accessee.lnnCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree user cred failed."); + return ret; + } + + // Delete temporary credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Generate transport credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate app cred and publicKey failed."); + return ret; + } + + // Agree transport credentials and public key + tmpCredId = context->accessee.transmitCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree app cred failed."); + return ret; + } + + // Delete temporary transport credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSinkCredentialExchangeState::Action leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSrcCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE; +} + +int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr context) +{ + LOGI(" AuthSrcCredentialAuthStartState::Action start."); + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId = ""; + int32_t osAccountId = context->accesser.userId; + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + if (NeedAgreeCredential(context)) { + // First authentication + if (context->accesser.isGenerateLnnCredential && context->accesser.bindLevel != USER) { + // Agree lnn credentials and public key + tmpCredId = context->accesser.lnnCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree user cred failed."); + return ret; + } + + // Delete temporary lnn credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Agree transport credentials and public key + tmpCredId = context->accesser.transmitCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree app cred failed."); + return ret; + } + + // Delete temporary transport credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Transport credential authentication + ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, + context->accesser.transmitCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, auth app cred failed."); + return ret; + } + + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_AUTH_START, context); + LOGI(" AuthSrcCredentialAuthStartState::Action leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp new file mode 100644 index 000000000..fa3ee432d --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -0,0 +1,512 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "accesstoken_kit.h" +#include "access_control_profile.h" +#include "accesser.h" +#include "accessee.h" +#include "auth_manager.h" +#include "app_manager.h" +#include "dm_crypto.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_language_manager.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "dm_random.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" +#include "device_auth.h" +#include "hap_token_info.h" +#include "json_object.h" +#include "multiple_user_connector.h" +#include "os_account_manager.h" +#include "parameter.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace DistributedHardware { + +DmAuthStateType AuthSrcStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_START_STATE; +} + +int32_t AuthSrcStartState::Action(std::shared_ptr context) +{ + return DM_OK; +} + +DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; +} + +std::string AuthSrcNegotiateStateMachine::GetAccountGroupIdHash(std::shared_ptr context) +{ + JsonObject jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + std::string queryParams = SafetyDump(jsonObj); + + int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); + if (osAccountUserId < 0) { + LOGE("get current process account user id failed"); + return ""; + } + std::vector groupList; + if (!context->hiChainConnector->GetGroupInfo(osAccountUserId, queryParams, groupList)) { + return ""; + } + JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY); + for (auto &groupInfo : groupList) { + jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId)); + } + return SafetyDump(jsonAccountObj); +} + +int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); + + context->reply = ERR_DM_AUTH_REJECT; + context->accessee.dmVersion = ""; + + // Calculate the hash value + context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); + context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + + // Create old message for compatible + context->accesser.accountGroupIdHash = GetAccountGroupIdHash(context); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + return DM_OK; +} + +DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; +} + +int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + // 1. Get deviceId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = std::string(localDeviceId); + context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); + + // 2. Get userId + context->accessee.userId = MultipleUserConnector::GetUserIdByDisplayId( + static_cast(context->accessee.displayId)); + if (context->accessee.userId < 0) { + LOGE("get userId failed."); + return ERR_DM_GET_LOCAL_USERID_FAILED; + } + + // 3. Get accountId + context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); + context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); + + // 4. Get tokenId + if (AppManager::GetInstance().GetNativeTokenIdByName(context->accessee.bundleName, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_SA; + } else if (AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, context->accessee.bundleName, 0, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_FA; + } else { + LOGE("sink not contain the bundlename %{public}s.", context->accessee.bundleName.c_str()); + return ERR_DM_GET_TOKENID_FAILED; + } + if (DmAuthState::CheckProcessNameInWhiteList(context->accessee.bundleName)) { + context->accessee.bindLevel = DmRole::DM_ROLE_USER; + } + context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); + context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); + context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + int32_t ret = RespQueryAcceseeIds(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); + return ret; + } + JsonObject credInfo; + GetSinkCredentialInfo(context, credInfo); + JsonObject aclTypeJson; + GetSinkAclInfo(context, credInfo, aclTypeJson); + context->accessee.aclTypeList = aclTypeJson.Dump(); + JsonObject credTypeJson; + GetSinkCredType(context, credInfo, aclTypeJson, credTypeJson); + context->accessee.credTypeList = credTypeJson.Dump(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + + // 1. Create an authorization timer + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + // To be compatible with historical versions, use ConvertSrcVersion to get the actual version on the source side. + std::string preVersion = std::string(DM_VERSION_5_0_OLD_MAX); + LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", + context->accesser.dmVersion.c_str(), preVersion.c_str()); + if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version"); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + int32_t ret = ProcRespNegotiate5_1_0(context); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); + context->reason = ret; + return ret; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); + context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson) +{ + CHECK_NULL_VOID(context); + std::vector deleteCredInfo; + for (const auto &item : credInfo.Items()) { + if (!item.Contains(FILED_CRED_TYPE) || !item[FILED_CRED_TYPE].IsNumberInteger() || + !item.Contains(FILED_CRED_ID) || !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + int32_t credType = item[FILED_CRED_TYPE].Get(); + LOGI("credType %{public}d.", credType); + switch (credType) { + case DM_IDENTICAL_ACCOUNT: + credTypeJson["identicalCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + break; + case DM_SHARE: + credTypeJson["shareCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + break; + case DM_POINT_TO_POINT: + if (!aclInfo.Contains("pointTopointAcl") || + (context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != + item[FILED_CRED_ID].Get() && + context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != + item[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + } else { + credTypeJson["pointTopointCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + } + break; + case DM_LNN: + if (!aclInfo.Contains("lnnAcl") || + (context->accessee.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != + item[FILED_CRED_ID].Get() && + context->accessee.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != + item[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + } else { + credTypeJson["lnnCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + } + break; + default: + LOGE("invalid credType %{public}d.", credType); + break; + } + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, item); + } +} + +void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + int32_t bindLevel = DM_INVALIED_TYPE; + for (const auto &item : profiles) { + std::string trustDeviceId = item.GetTrustDeviceId(); + std::string trustDeviceIdHash = Crypto::Sha256(trustDeviceId); + if (trustDeviceIdHash != context->accesser.deviceIdHash && + trustDeviceIdHash != context->accessee.deviceIdHash) { + LOGE("devId %{public}s hash %{public}s, er devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), + GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); + continue; + } + bindLevel = item.GetBindLevel(); + switch (item.GetBindType()) { + case DM_IDENTICAL_ACCOUNT: + if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { + aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accessee.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; + } + break; + case DM_SHARE: + if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_SHARE)) { + aclInfo["shareAcl"] = DM_SHARE; + context->accessee.aclProfiles[DM_SHARE] = item; + } + break; + case DM_POINT_TO_POINT: + if (Point2PointAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_POINT_TO_POINT)) { + aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accessee.aclProfiles[DM_POINT_TO_POINT] = item; + } + if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accessee.aclProfiles[DM_LNN] = item; + } + break; + default: + LOGE("invalid bindType %{public}d.", item.GetBindType()); + break; + } + } + if (aclInfo.Contains("pointTopointAcl") && !aclInfo.Contains("lnnAcl") && bindLevel != USER) { + aclInfo.Erase("pointTopointAcl"); + DeleteAcl(context, context->accessee.aclProfiles[DM_POINT_TO_POINT]); + } +} + +bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) +{ + std::string credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); + if (!credInfo.Contains(credId)) { + credId = profile.GetAccesser().GetAccesserCredentialIdStr(); + if (!credInfo.Contains(credId)) { + LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + DeleteAcl(context, profile); + return false; + } + } + if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || + !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { + LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); + credInfo.Erase(credId); + DeleteAcl(context, profile); + return false; + } + bool checkResult = false; + switch (bindType) { + LOGI("bindType %{public}d.", bindType); + case DM_IDENTICAL_ACCOUNT: + case DM_SHARE: + case DM_LNN: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + break; + case DM_POINT_TO_POINT: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + const size_t APP_LIST_SIZE = 2; + if (appList.size() >= APP_LIST_SIZE && + ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || + (std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0] && + std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1]))) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + } else { + DeleteAcl(context, profile); + } + break; + default: + break; + } + return checkResult; +} + +bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash; +} + +bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash; +} + +bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return (accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + accessee.GetAccesseeTokenId() == context->accessee.tokenId && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash) || + (accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId && + accesser.GetAccesserTokenId() == context->accessee.tokenId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accesser.tokenIdHash); +} + +bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return ((accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId) || + (accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId)) && + accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == "" && + (Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash || + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash) && + accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == ""; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + // get identical credential + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + GetIdenticalCredentialInfo(context, credInfo); + } + // get share credential + if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountIdHash != Crypto::Sha256("ohosAnonymousUid") && + context->accessee.accountIdHash != Crypto::Sha256("ohosAnonymousUid")) { + GetShareCredentialInfo(context, credInfo); + GetP2PCredentialInfo(context, credInfo); + } + // get point_to_point credential + if (context->accesser.accountIdHash == Crypto::Sha256("ohosAnonymousUid") || + context->accessee.accountIdHash == Crypto::Sha256("ohosAnonymousUid")) { + GetP2PCredentialInfo(context, credInfo); + } + std::vector deleteCredInfo; + for (auto& item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 + uint32_t credType = DmAuthState::GetCredentialType(context, item); + if (credType == DM_INVALIED_TYPE || !item.Contains(FILED_CRED_TYPE) || + !item[FILED_CRED_TYPE].IsNumberInteger() || !item.Contains(FILED_CRED_ID) || + !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + item[FILED_CRED_TYPE] = credType; + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSinkNegotiateStateMachine::GetIdenticalCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID] = context->accessee.deviceId; + queryParams[FILED_USER_ID] = context->accessee.accountId; + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetShareCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetP2PCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp new file mode 100644 index 000000000..f53c7162e --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "auth_manager.h" +#include "deviceprofile_connector.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "dm_auth_state_machine.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_negotiate_process.h" +#include "dm_random.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" +#include "service_info_profile.h" + +namespace OHOS { +namespace DistributedHardware { + +constexpr int32_t MAX_AUTH_INPUT_PIN_FAIL_TIMES = 3; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +constexpr const char* UNVALID_CREDTID = "invalidCredId"; + +int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowAuthInfoDialog start"); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowAuthInfoDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + DmDialogManager::GetInstance().ShowPinDialog(std::to_string(context->pinCode)); + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + return DM_OK; +} + +void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptr context, std::string name) +{ + context->timer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + if (context->successFinished) { + return; + } + + LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); + JsonObject jsonObj; + jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; + std::string message = jsonObj.Dump(); + context->softbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); + + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + + LOGI("DmAuthManager::HandleSessionHeartbeat complete."); +} + +bool AuthSinkStatePinAuthComm::IsPinCodeValid(int32_t numpin) +{ + if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) { + return false; + } + return true; +} + +bool AuthSinkStatePinAuthComm::IsPinCodeValid(const std::string& strpin) +{ + if (strpin.empty()) { + return false; + } + for (size_t i = 0; i < strpin.length(); i++) { + if (!isdigit(strpin[i])) { + return false; + } + } + int32_t pinnum = std::atoi(strpin.c_str()); + return IsPinCodeValid(pinnum); +} + +bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr context) +{ + if (context->importAuthCode.empty() || context->importPkgName.empty()) { + LOGE("AuthSinkStatePinAuthComm::IsAuthCodeReady, auth code not ready with authCode %{public}s and " + "pkgName %{public}s.", context->importAuthCode.c_str(), context->importPkgName.c_str()); + return false; + } + if (context->pkgName != context->importPkgName) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady pkgName %{public}s not supported with " + "import pkgName %{public}s.", context->pkgName.c_str(), context->importPkgName.c_str()); + return false; + } + return true; +} + +void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) +{ + context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} + +DmAuthStateType AuthSrcPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE; +} + +int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::Action start"); + // auth pincode + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(context->accesser.userId, context->requestId, + context->pinCode); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthStartState::AuthDevice call AuthCredentialPinCode failed."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 120 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + return DM_OK; + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE; +} + +int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthStartState::Action start"); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + } + + // Stop the abnormal authentication process + if (context->authTypeList.empty() || + (context->confirmOperation != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->confirmOperation != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { + LOGE("AuthSinkPinAuthStartState::Action invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + + // process pincode auth + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 130 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + return STOP_BIND; +} + +DmAuthStateType AuthSrcPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 121 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthMsgNegotiateState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + LOGE("AuthSrcPinAuthMsgNegotiateState::Action failed."); + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthMsgNegotiateState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 131 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, context); + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_TRANSMIT ON_ERROR failed, maybe retry."); + return DM_OK; + } else { + return STOP_BIND; + } + + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_SESSION_KEY_RETURNED); + if (retEvent == DmEventType::ON_SESSION_KEY_RETURNED) { + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_FINISH); + if (retEvent == DmEventType::ON_FINISH || retEvent == DmEventType::ON_ERROR) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_SESSION_KEY_RETURNED ON_ERROR failed, maybe retry."); + return DM_OK; + } + + LOGE("AuthSinkPinAuthMsgNegotiateState::AuthDevice failed."); + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSinkPinAuthDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthDoneState Action"); + return DM_OK; +} + +DmAuthStateType AuthSrcPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthDoneState::Action start"); + std::string onTransmitData = context->transmitData; + if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { + LOGE("AuthSrcPinAuthDoneState::Action failed, processCredData failed."); + return ERR_DM_FAILED; + } + + // wait for ON_SESSION_KEY_RETURNED from hichain + DmEventType ret = context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED); + if (ret != ON_SESSION_KEY_RETURNED) { + if (ret == ON_ERROR) { + LOGE("AuthSrcPinAuthDoneState::Action, ON_SESSION_KEY_RETURNED event not arriverd, maybe retry."); + return DM_OK; + } else { + LOGE("AuthSrcPinAuthDoneState::Action failed, ON_SESSION_KEY_RETURNED event failed, other event arriverd."); + return ERR_DM_FAILED; + } + } + + // wait for ON_FINISH from hichain + ret = context->authStateMachine->WaitExpectEvent(ON_FINISH); + if (ret == ON_FINISH) { + LOGI("AuthSrcPinAuthDoneState::Action wait ON_FINISH done"); + return DM_OK; + } else if (ret == ON_ERROR) { + return DM_OK; + LOGE("AuthSrcPinAuthDoneState::Action, ON_FINISH event not arriverd, maybe retry."); + } + + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptr context, bool firstTime) +{ + if (firstTime) { + if (context->authTypeList.empty()) { + LOGE("authTypeList empty"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx = 0; + context->authType = context->authTypeList[0]; + } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { + LOGI("input pin auth err, retry"); + } else { + // try to fallback to next auth type + if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + LOGE("all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx++; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; + } + } + + // restart pin auth timer + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + if (AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("auth code not ready"); + context->reason = ERR_DM_INPUT_PARA_INVALID; + return ERR_DM_FAILED; + } + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + int32_t ret = NegotiateProcess::GetInstance().HandleNegotiateResult(context); + if (ret != DM_OK) { + LOGE("HandleNegotiateResult failed ret %{public}d", ret); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ret; + } + if (!context->needBind && !context->needAgreeCredential && context->needAuth) { + return ProcessCredAuth(context); + } + if (context->needBind) { + return ProcessPinBind(context); + } + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; +} + +int32_t AuthSrcPinNegotiateStartState::ProcessCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + if (accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid"); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + if (accesserCredTypeList.Contains("identicalCredType")) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_IDENTICAL_ACCOUNT); + } else if (accesserCredTypeList.Contains("shareCredType")) { + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_SHARE); + } else if (accesserCredTypeList.Contains("pointTopointCredType")) { + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_POINT_TO_POINT); + } else if (accesserCredTypeList.Contains("lnnCredType")) { + context->accesser.lnnCredentialId = GetCredIdByCredType(context, DM_LNN); + } else { + LOGE("credTypeList invalid."); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string AuthSrcPinNegotiateStartState::GetCredIdByCredType(std::shared_ptr context, int32_t credType) +{ + LOGI("credType %{public}d.", credType); + CHECK_NULL_RETURN(context, UNVALID_CREDTID); + if (context->accesser.credentialInfos.find(credType) != context->accesser.credentialInfos.end()) { + LOGE("invalid credType."); + return UNVALID_CREDTID; + } + std::string credInfoStr = context->accesser.credentialInfos[credType]; + JsonObject credInfoJson; + credInfoJson.Parse(credInfoStr); + if (credInfoJson.IsDiscarded() || !credInfoJson.Contains(FILED_CRED_ID) || + !credInfoJson[FILED_CRED_ID].IsNumberInteger()) { + LOGE("credInfoStr invalid."); + return UNVALID_CREDTID; + } + return credInfoJson[FILED_CRED_ID].Get(); +} + +int32_t AuthSrcPinNegotiateStartState::ProcessPinBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + CHECK_NULL_RETURN(context->timer, ERR_DM_POINT_NULL); + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + if (context->confirmOperation != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->confirmOperation != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("confirmOperation not allow"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_BIND_USER_CANCEL; + } + // import pin code auth always excute + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + (!context->authTypeList.empty()) && + DmAuthState::IsImportAuthCodeCompatibility(context->authTypeList[0])) { + return NegotiatePinAuth(context, true); + } else { + return NegotiatePinAuth(context, false); + } + } else { + return NegotiatePinAuth(context, false); + } + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSrcPinInputState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE; +} + +int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr context) +{ + LOGI("AuthSrcPinInputState::ShowStartAuthDialog start."); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSrcPinInputState screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; + } + + DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); + LOGI("AuthSrcPinInputState::ShowStartAuthDialog end."); + return DM_OK; +} + +int32_t AuthSrcPinInputState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinInputState::Action start"); + if (context->inputPinAuthFailTimes == 0) { + auto ret = ShowStartAuthDialog(context); + if (ret != DM_OK) { + return ret; + } + } else { + // clear input pin box, and show try again + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } + + LOGI("AuthSrcPinInputState::Action waitting user operation"); + // wait for user operation + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGI("AuthSrcPinInputState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; + } + + if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { + LOGE("AuthSrcPinInputState::Action not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); + return STOP_BIND; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) +{ + if (!context->pinNegotiateStarted) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + context->pinNegotiateStarted = true; + } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); + } else { + // try to fallback to next auth type + auto idx = context->currentAuthTypeIdx; + if (idx + 1 >= context->authTypeList.size()) { + LOGE("AuthSinkPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + ++idx; + context->currentAuthTypeIdx = idx; + context->authType = context->authTypeList[idx]; + } + } + // restart pin auth timer + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + LOGI("AuthSinkPinNegotiateStartState::Action import auth code"); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin"); + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + LOGI("AuthSinkPinNegotiateStartState::Action ultrasonic pin"); + } else { + LOGE("AuthSinkPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +DmAuthStateType AuthSinkPinDisplayState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE; +} + +int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) +{ + if (context->inputPinAuthFailTimes == 0) { + // gen pincode + AuthSinkStatePinAuthComm::GeneratePincode(context); + // show pincode + return AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context); + } + return DM_OK; +} + +DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSinkPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return ERR_DM_FAILED; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp new file mode 100644 index 000000000..13bfb140a --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +std::string DmAuthContext::GetDeviceId(DmAuthSide side) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.deviceId : remoteAccess.deviceId; +} + +int32_t DmAuthContext::GetUserId(DmAuthSide side) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.userId : remoteAccess.userId; +} + +std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnCredentialId : access.transmitCredentialId; +} + +std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnPublicKey : access.transmitPublicKey; +} + +void DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &credId = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnCredentialId : access.transmitCredentialId; + credId = credentialId; + return; +} + +void DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &key = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnPublicKey : access.transmitPublicKey; + key = publicKey; + + return; +} + +std::string DmAuthContext::GetAccountId(DmAuthSide side) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.accountId : remoteAccess.accountId; +} + +uint32_t DmAuthContext::GetBindType() +{ + if (accesser.accountId == "ohosAnonymousUid" || accessee.accountId == "ohosAnonymousUid") { + return DM_POINT_TO_POINT; + } else { + return DM_ACROSS_ACCOUNT; + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp new file mode 100644 index 000000000..24d710867 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -0,0 +1,491 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "multiple_user_connector.h" +#include "os_account_manager.h" + +#include "dm_constants.h" +#include "dm_error_type.h" +#include "dm_auth_manager_base.h" + +#ifdef OS_ACCOUNT_PART_EXISTS +#include "os_account_manager.h" +using namespace OHOS::AccountSA; +#endif // OS_ACCOUNT_PART_EXISTS + +namespace OHOS { +namespace DistributedHardware { + +const char* DM_VERSION_5_0_1 = "5.0.1"; +const char* DM_VERSION_5_0_2 = "5.0.2"; +const char* DM_VERSION_5_0_3 = "5.0.3"; +const char* DM_VERSION_5_0_4 = "5.0.4"; +const char* DM_VERSION_5_0_5 = "5.0.5"; +const char* DM_VERSION_5_1_0 = "5.1.0"; +const char* DM_VERSION_5_0_OLD_MAX = "5.0.9"; // Estimated highest version number of the old version + +const char* TAG_DMVERSION = "dmVersion"; +const char* TAG_DM_VERSION_V2 = "dmVersionV2"; +const char* TAG_EDITION = "edition"; +const char* TAG_DATA = "data"; +const char* TAG_DATA_LEN = "dataLen"; +const char* TAG_BUNDLE_NAME = "bundleName"; +const char* TAG_BUNDLE_NAME_V2 = "bundleNameV2"; +const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; +const char* TAG_PEER_BUNDLE_NAME_V2 = "PEER_BUNDLE_NAME_V2"; +const char* TAG_PEER_PKG_NAME = "PEER_PKG_NAME"; +const char* TAG_BIND_LEVEL = "bindLevel"; +const char* TAG_REPLY = "REPLY"; +const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +const char* TAG_AUTH_FINISH = "isFinish"; +const char* TAG_LOCAL_USERID = "localUserId"; +const char* TAG_LOCAL_DEVICE_ID = "LOCALDEVICEID"; +const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; +const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; +const char* TAG_HAVE_CREDENTIAL = "haveCredential"; +const char* TAG_ISONLINE = "isOnline"; +const char* TAG_AUTHED = "authed"; +const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; +const char* TAG_TOKENID = "tokenId"; +const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; +const char* TAG_HOST = "HOST"; + +const char* APP_OPERATION_KEY = "appOperation"; +const char* TARGET_PKG_NAME_KEY = "targetPkgName"; +const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; +const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +const char* BUNDLE_NAME_KEY = "bundleName"; + +const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; +const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; +const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; +const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; +const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; +const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; + +const int32_t AUTHENTICATE_TIMEOUT = 120; +const int32_t CONFIRM_TIMEOUT = 60; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t INPUT_TIMEOUT = 60; +const int32_t ADD_TIMEOUT = 10; +const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; +const int32_t PIN_AUTH_TIMEOUT = 60; +const int32_t EVENT_TIMEOUT = 5000; // 5000 ms + + +int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGE("AuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGE("UnAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGE("UnBindDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGE("OnSessionOpened is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionClosed(const int32_t sessionId) +{ + LOGE("OnSessionClosed is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionDisable() +{ + LOGE("OnSessionDisable is not implemented in the current version"); +} + +void AuthManagerBase::OnDataReceived(const int32_t sessionId, const std::string message) +{ + LOGE("OnDataReceived is not implemented in the current version"); +} + +void AuthManagerBase::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result) +{ + LOGE("OnSoftbusJoinLNNResult is not implemented in the current version"); +} + +void AuthManagerBase::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + LOGE("OnGroupCreated is not implemented in the current version"); +} + +void AuthManagerBase::OnMemberJoin(int64_t requestId, int32_t status) +{ + LOGE("OnMemberJoin is not implemented in the current version"); +} + +int32_t AuthManagerBase::EstablishAuthChannel(const std::string &deviceId) +{ + LOGE("EstablishAuthChannel is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartNegotiate(const int32_t &sessionId) +{ + LOGE("StartNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::RespNegotiate(const int32_t &sessionId) +{ + LOGE("RespNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::SendAuthRequest(const int32_t &sessionId) +{ + LOGE("SendAuthRequest is not implemented in the current version"); +} + +int32_t AuthManagerBase::StartAuthProcess(const int32_t &action) +{ + LOGE("StartAuthProcess is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartRespAuthProcess() +{ + LOGE("StartRespAuthProcess is not implemented in the current version"); +} + +int32_t AuthManagerBase::CreateGroup() +{ + LOGE("CreateGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ProcessPincode(int32_t pinCode) +{ + LOGE("ProcessPincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GetConnectAddr(std::string deviceId) +{ + LOGE("GetConnectAddr is not implemented in the current version"); + return ""; +} + +int32_t AuthManagerBase::JoinNetwork() +{ + LOGE("JoinNetwork is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::AuthenticateFinish() +{ + LOGE("AuthenticateFinish is not implemented in the current version"); +} + +bool AuthManagerBase::GetIsCryptoSupport() +{ + LOGE("GetIsCryptoSupport is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::SetAuthRequestState(std::shared_ptr authRequestState) +{ + LOGE("SetAuthRequestState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr authResponseState) +{ + LOGE("SetAuthResponseState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetPinCode(int32_t &code) +{ + LOGE("GetPinCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GenerateGroupName() +{ + LOGE("GenerateGroupName is not implemented in the current version"); + return ""; +} + +void AuthManagerBase::HandleAuthenticateTimeout(std::string name) +{ + LOGE("HandleAuthenticateTimeout is not implemented in the current version"); +} + +int32_t AuthManagerBase::GeneratePincode() +{ + LOGE("GeneratePincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::ShowConfigDialog() +{ + LOGE("ShowConfigDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowAuthInfoDialog(bool authDeviceError) +{ + LOGE("ShowAuthInfoDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowStartAuthDialog() +{ + LOGE("ShowStartAuthDialog is not implemented in the current version"); +} + +int32_t AuthManagerBase::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGE("OnUserOperation is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetPageId(int32_t pageId) +{ + LOGE("SetPageId is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetReasonAndFinish(int32_t reason, int32_t state) +{ + LOGE("SetReasonAndFinish is not implemented in the current version"); + return ERR_DM_FAILED; +} + +bool AuthManagerBase::IsIdenticalAccount() +{ + LOGE("IsIdenticalAccount is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::RegisterUiStateCallback(const std::string pkgName) +{ + LOGE("RegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGE("UnRegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + LOGE("ImportAuthCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) +{ + LOGE("BindTarget is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::RegisterAuthenticationType(int32_t authenticationType) +{ + LOGE("RegisterAuthenticationType is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) +{ + LOGE("StopAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGE("DeleteGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetReason() +{ + LOGE("GetReason is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + LOGE("GetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::SetBindTargetParams(const PeerTargetId &targetId) +{ + LOGE("SetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + LOGE("RegisterCleanNotifyCallback is not implemented in the current version"); + return; +} + +std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_1_0; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +// Scenario 1: The remote side specifies userId -> Verify if it is a front-end user +// Scenario 2: The remote side does not specify userId +// Scenario 2.1: Single user -> Use the current unique front-end user +// Scenario 2.2: Multiple users -> Use the current main screen user +int32_t AuthManagerBase::DmGetUserId(int32_t displayId) +{ + int32_t ret; + int32_t userId = -1; + + std::vector userIds; + ret = MultipleUserConnector::GetForegroundUserIds(userIds); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return -1; + } + // Scenario 1: The remote side specifies userId -> Verify if it is a front-end user + // Scenario 2: The remote side does not specify userId + // Scenario 2.1: Single user -> Use the current unique front-end user + // Scenario 2.2: Multiple users -> Use the current main screen user + if (userIds.size() == 0) { + LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); + return -1; + } + + if (displayId != -1) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); + return -1; + } + return userId; + } + if (userIds.size() == 1) { + return userIds[0]; + } else { + // If userIds.size() > 1, we need to find the main screen user +#ifdef OS_ACCOUNT_PART_EXISTS + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); + if (ret != DM_OK) { + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed in multi users with error %{public}d", ret); + return -1; + } + return userId; +#else + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed because no OsAcccountManager"); + return -1; +#endif + } +} + +bool AuthManagerBase::IsTransferReady() +{ + return isTransferReady_; +} + +void AuthManagerBase::SetTransferReady(bool version) +{ + isTransferReady_ = version; +} + +void AuthManagerBase::ClearSoftbusSessionCallback() +{} + +void AuthManagerBase::PrepareSoftbusSessionCallback() +{} + +void AuthManagerBase::EnableInsensibleSwitching() +{ + insensibleSwitching = true; +} + +void AuthManagerBase::DisableInsensibleSwitching() +{ + insensibleSwitching = false; +} + +bool AuthManagerBase::NeedInsensibleSwitching() +{ + return insensibleSwitching; +} + +int32_t AuthManagerBase::ParseAuthType(const std::map &bindParam, int32_t &authType) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("AuthManagerBase::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string authTypeStr = iter->second; + if (authTypeStr.empty()) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (authTypeStr.length() > 1) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!isdigit(authTypeStr[0])) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + authType = std::atoi(authTypeStr.c_str()); + return DM_OK; +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp new file mode 100644 index 000000000..bc87c07c6 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -0,0 +1,1366 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "distributed_device_profile_client.h" +#include "deviceprofile_connector.h" +#include "service_info_profile.h" +#include "service_info_unique_key.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "access_control_profile.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_context.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "parameter.h" + +namespace OHOS { +namespace DistributedHardware { + +const char* TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; +const char* TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; +const char* TAG_LNN_CREDENTIAL_ID = "lnnCredentialId"; +const char* TAG_TRANSMIT_CREDENTIAL_ID = "transmitCredentialId"; +const char* TAG_CONFIRM_OPERATION_V2 = "confirmOperation"; +const char* TAG_AUTH_TYPE_LIST = "authTypeList"; +const char* TAG_CURRENT_AUTH_TYPE_IDX = "currentAuthTypeIdx"; + +// IS interface input parameter json format string key +const char* TAG_METHOD = "method"; +const char* TAG_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* TAG_SUBJECT = "subject"; +const char* TAG_CRED_TYPE = "credType"; +const char* TAG_KEY_FORMAT = "keyFormat"; +const char* TAG_ALGORITHM_TYPE = "algorithmType"; +const char* TAG_PROOF_TYPE = "proofType"; +const char* TAG_KEY_VALUE = "keyValue"; +const char* TAG_AUTHORIZED_SCOPE = "authorizedScope"; +const char* TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; +const char* TAG_CREDENTIAL_OWNER = "credOwner"; +const char* TAG_SYNC = "syncMessage"; +const char* TAG_ACCESS = "dmAccess"; +const char* TAG_PROXY = "proxy"; +const char* TAG_ACL = "accessControlTable"; +const char* TAG_ACCESSER = "dmAccesser"; +const char* TAG_ACCESSEE = "dmAccessee"; +const char* TAG_SERVICEINFO = "serviceInfo"; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +const char* TAG_TRANSMIT_SK_ID = "accessAppSKId"; +const char* TAG_LNN_SK_ID = "accessUserSKId"; +const char* TAG_TRANSMIT_SK_TIMESTAMP = "accessAppSKTimeStamp"; +const char* TAG_LNN_SK_TIMESTAMP = "accessUserSKTimeStamp"; +const char* TAG_USER_ID = "userId"; +const char* TAG_TOKEN_ID = "tokenId"; +const char* TAG_ISSUER = "issuer"; + +const char* TAG_DEVICE_VERSION = "deviceVersion"; +const char* TAG_DEVICE_NAME = "deviceName"; +const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; +const char* TAG_ACCOUNT_ID_HASH = "accountIdHash"; +const char* TAG_TOKEN_ID_HASH = "tokenIdHash"; +const char* TAG_PKG_NAME = "pkgName"; +const char* TAG_ACL_CHECKSUM = "aclCheckSum"; +const char* TAG_COMPRESS_ORI_LEN = "compressOriLen"; +const char* TAG_COMPRESS = "compressMsg"; +const char* TAG_STATE = "state"; +const char* TAG_REASON = "reason"; +const char* TAG_PEER_USER_ID = "peerUserId"; +const char* TAG_PEER_DISPLAY_ID = "peerDisplayId"; +const char* TAG_EXTRA_INFO = "extraInfo"; +const char* TAG_ACL_TYPE_LIST = "aclTypeList"; +const char* TAG_CERT_TYPE_LIST = "certTypeList"; + +const char* TAG_IS_ONLINE = "isOnline"; +const char* TAG_IS_AUTHED = "isAuthed"; +const char* TAG_CREDENTIAL_INFO = "credentialInfo"; +const char* TAG_CERT_INFO = "certInfo"; +const char* TAG_LANGUAGE = "language"; + +namespace { + +constexpr const int32_t DM_HASH_LEN = 32; +const char* TAG_DEVICE_TYPE = "DEVICETYPE"; + +void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access) +{ + JsonObject accessjson(jsonString); + DmAccessToSync srcAccessToSync = accessjson.Get(); + access.deviceName = srcAccessToSync.deviceName; + access.deviceId = srcAccessToSync.deviceId; + access.userId = srcAccessToSync.userId; + access.accountId = srcAccessToSync.accountId; + access.tokenId = srcAccessToSync.tokenId; + access.bundleName = srcAccessToSync.bundleName; + access.pkgName = srcAccessToSync.pkgName; + access.bindLevel = srcAccessToSync.bindLevel; + access.sessionKeyId = srcAccessToSync.sessionKeyId; + access.skTimeStamp = srcAccessToSync.skTimeStamp; + return; +} + +bool IsMessageValid(const JsonItemObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); + return false; + } + if (!jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); + return false; + } + return true; +} + +} + +int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + return cryptoMgr_->ProcessSessionKey(sessionKey, keyLen); +} + +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t userId, int32_t &skId) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKeyToDP failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + return DeviceProfileConnector::GetInstance().PutSessionKey(userId, cryptoMgr_->GetSessionKey(), skId); +} + +int32_t DmAuthMessageProcessor::DeleteSessionKeyToDP(int32_t userId, int32_t skId) +{ + return DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId); +} + +void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile) +{ + uint32_t authenticationType = ALLOW_AUTH_ONCE; + if (context->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + authenticationType = ALLOW_AUTH_ALWAYS; + } + profile.SetAuthenticationType(authenticationType); + profile.SetStatus(ACTIVE); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); +} + +void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(context->accesser.tokenId); + accesser.SetAccesserBundleName(context->accesser.pkgName); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserCredentialIdStr(context->accesser.transmitCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); + accesser.SetAccesserExtraData(context->accesser.extraInfo); + + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(context->accessee.tokenId); + accessee.SetAccesseeBundleName(context->accessee.pkgName); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeCredentialIdStr(context->accessee.transmitCredentialId); // 依赖dp + accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); + accessee.SetAccesseeExtraData(context->accessee.extraInfo); +} + +void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(0); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserCredentialIdStr(context->accesser.lnnCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); + accesser.SetAccesserExtraData(context->accesser.extraInfo); + + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(0); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeCredentialIdStr(context->accessee.lnnCredentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); + accessee.SetAccesseeExtraData(context->accessee.extraInfo); +} + +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) +{ + LOGI("Start."); + DistributedDeviceProfile::Accesser accesser; + DistributedDeviceProfile::Accessee accessee; + SetLnnAccessControlList(context, accesser, accessee); + DistributedDeviceProfile::AccessControlProfile profile; + SetAccessControlList(context, profile); + profile.SetTrustDeviceId(trustDeviceId); + profile.SetDeviceIdHash(access.deviceIdHash); + profile.SetBindType(access.lnnBindType); + profile.SetAccessee(accessee); + profile.SetAccesser(accesser); + JsonObject extraData; + if (access.isPutLnnAcl && access.bindLevel != static_cast(USER)) { + profile.SetBindLevel(USER); + extraData["IsLnnAcl"] = "true"; + profile.SetExtraData(extraData.Dump()); + int32_t ret = + DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutAccessControlProfile(profile); + if (ret != DM_OK) { + LOGE("PutAccessControlProfile failed."); + } + } + extraData["IsLnnAcl"] = "false"; + profile.SetExtraData(extraData.Dump()); + profile.SetBindLevel(access.bindLevel); + SetTransmitAccessControlList(context, accesser, accessee); + profile.SetBindLevel(access.bindLevel); + profile.SetBindType(access.transmitBindType); + profile.SetAccessee(accessee); + profile.SetAccesser(accesser); + int32_t ret = + DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutAccessControlProfile(profile); + if (ret != DM_OK) { + LOGE("PutAccessControlProfile failed."); + } + return ret; +} + +DmAuthMessageProcessor::DmAuthMessageProcessor() +{ + LOGI("DmAuthMessageProcessor constructor"); + cryptoMgr_ = std::make_shared(); + createMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + }; + paraseMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, + }; + LOGI("DmAuthMessageProcessor constructor leave."); +} + +DmAuthMessageProcessor::~DmAuthMessageProcessor() +{ + if (cryptoMgr_ != nullptr) { + cryptoMgr_->ClearSessionKey(); + cryptoMgr_ = nullptr; + } +} + +int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) +{ + JsonObject jsonObject(message); + if (context == nullptr || !IsMessageValid(jsonObject)) { + return ERR_DM_FAILED; + } + DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); + context->msgType = msgType; + LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); + if (CheckLogicalSessionId(jsonObject, context) != DM_OK) { + LOGE("CheckLogicalSessionId failed."); + return ERR_DM_FAILED; + } + auto itr = paraseMessageFuncMap_.find(msgType); + if (itr == paraseMessageFuncMap_.end()) { + LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); + return ERR_DM_FAILED; + } + return (this->*(itr->second))(jsonObject, context); +} + +static std::vector stringToVectorAuthType(const std::string& str) +{ + std::vector vec; + std::istringstream iss(str); + int32_t num; + while (iss >> num) { + vec.push_back(static_cast(num)); + } + return vec; +} + +static std::string vectorAuthTypeToString(const std::vector& vec) +{ + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << static_cast(vec[i]); + if (i != vec.size() - 1) { + oss << " "; // Add a separator (e.g. space) + } + } + return oss.str(); +} + +int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); + return ERR_DM_FAILED; + } + + context->transmitData = jsonObject[TAG_DATA].Get(); + + switch (context->msgType) { + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + return ERR_DM_FAILED; + } + + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + context->transmitData = jsonObject[TAG_DATA].Get(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); + return ERR_DM_FAILED; + } + JsonObject jsonData(plainText); + + // First authentication, parse lnn public key + if (context->accessee.isGenerateLnnCredential && context->accessee.bindLevel != static_cast(USER)) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); + return ERR_DM_FAILED; + } + context->accesser.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + } + + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); + return ERR_DM_FAILED; + } + context->accesser.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accesser.deviceId = jsonData[TAG_DEVICE_ID].Get(); + context->accesser.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); + context->accesser.tokenId = jsonData[TAG_TOKEN_ID].Get(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &jsonObject, + std::shared_ptr context) +{ + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); + return ERR_DM_FAILED; + } + + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange plainText=%{public}s", plainText.c_str()); + + JsonObject jsonData(plainText); + + // First authentication, parse lnn public key + std::string tmpString = ""; + if (context->accesser.isGenerateLnnCredential && context->accesser.bindLevel != static_cast(USER)) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey."); + return ERR_DM_FAILED; + } + context->accessee.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + } + + // First authentication, parse transmit public key + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, decode MSG_TYPE_RESP_CREDENTIAL_EXCHANGE " + "message error."); + return ERR_DM_FAILED; + } + context->accessee.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.deviceId = jsonData[TAG_DEVICE_ID].Get(); + context->accessee.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); + context->accessee.tokenId = jsonData[TAG_TOKEN_ID].Get(); + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) +{ + LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); + JsonObject jsonObj; + jsonObj[TAG_MSG_TYPE] = msgType; + jsonObj[DM_TAG_LOGICAL_SESSION_ID] = context->logicalSessionId; + auto itr = createMessageFuncMap_.find(msgType); + if (itr == createMessageFuncMap_.end()) { + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + return ""; + } + int32_t ret = (this->*(itr->second))(context, jsonObj); + LOGI("DmAuthMessageProcessor::CreateMessage start. message is %{public}s", jsonObj.Dump().c_str()); + return (ret == DM_OK) ? jsonObj.Dump() : ""; +} + +int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr context, + JsonObject &jsonObject) +{ + std::string encryptMsg; + jsonObject[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t CreateNegotiateOldMessage(std::shared_ptr context, JsonObject &jsonObject) +{ + jsonObject[TAG_CRYPTO_SUPPORT] = false; + jsonObject[TAG_AUTH_TYPE] = context->authType; + jsonObject[TAG_REPLY] = context->reply; + jsonObject[TAG_LOCAL_DEVICE_ID] = context->accesser.deviceId; + jsonObject[TAG_ACCOUNT_GROUPID] = context->accesser.accountGroupIdHash; + + jsonObject[TAG_BIND_LEVEL] = context->accesser.oldBindLevel; // compatible issue + jsonObject[TAG_LOCAL_ACCOUNTID] = context->accesser.accountId; + jsonObject[TAG_LOCAL_USERID] = context->accesser.userId; + jsonObject[TAG_ISONLINE] = false; + jsonObject[TAG_AUTHED] = false; + jsonObject[TAG_HOST] = context->pkgName; + jsonObject[TAG_TOKENID] = context->accesser.tokenId; + jsonObject[TAG_IDENTICAL_ACCOUNT] = false; + jsonObject[TAG_HAVE_CREDENTIAL] = false; + jsonObject[TAG_HOST_PKGLABEL] = context->pkgLabel; + jsonObject[TAG_REMOTE_DEVICE_NAME] = context->accesser.deviceName; + + return DM_OK; +} + +// Create 80 message. +int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) +{ + // create old message for compatible in import auth code + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + CreateNegotiateOldMessage(context, jsonObject); + } + jsonObject[TAG_DMVERSION] = ""; + jsonObject[TAG_EDITION] = DM_VERSION_5_0_5; + jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; + jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.oldBundleName; + + jsonObject[TAG_PKG_NAME] = context->pkgName; + + jsonObject[TAG_DM_VERSION_V2] = context->accesser.dmVersion; + jsonObject[TAG_USER_ID] = context->accesser.userId; + jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; + jsonObject[TAG_BUNDLE_NAME_V2] = context->accesser.bundleName; + jsonObject[TAG_EXTRA_INFO] = context->accesser.extraInfo; + + jsonObject[TAG_PEER_BUNDLE_NAME_V2] = context->accessee.bundleName; + jsonObject[TAG_PEER_DISPLAY_ID] = context->accessee.displayId; + jsonObject[TAG_PEER_PKG_NAME] = context->accessee.pkgName; + + return DM_OK; +} + +// Create 90 message. +int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, + JsonObject &jsonObject) +{ + jsonObject[TAG_DEVICE_VERSION] = context->accessee.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accessee.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accessee.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accessee.tokenIdHash; + jsonObject[TAG_USER_ID] = context->accessee.userId; + jsonObject[TAG_ACL_TYPE_LIST] = context->accessee.aclTypeList; + jsonObject[TAG_CERT_TYPE_LIST] = context->accessee.credTypeList; + jsonObject[TAG_LANGUAGE] = context->accessee.language; + jsonObject[TAG_EXTRA_INFO] = context->accessee.extraInfo; + jsonObject[TAG_IS_ONLINE] = context->accesser.isOnline; + + return DM_OK; +} + +// Create 140 message. +int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, + JsonObject &jsonObject) +{ + JsonObject jsonData; + if (context->accesser.isGenerateLnnCredential && context->accesser.bindLevel != static_cast(USER)) { + jsonData[TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; + } + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.transmitPublicKey; + jsonData[TAG_DEVICE_ID] = context->accesser.deviceId; + jsonData[TAG_PEER_USER_SPACE_ID] = context->accesser.userId; + jsonData[TAG_TOKEN_ID] = context->accesser.tokenId; + + std::string plainText = jsonData.Dump(); + std::string cipherText; + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageReqCredExchange encryptMessage failed."); + return ret; + } + jsonObject[TAG_DATA] = cipherText; + return ret; +} + +// Create 150 message. +int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, + JsonObject &jsonObject) +{ + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange start."); + JsonObject jsonData; + if (context->accessee.isGenerateLnnCredential && context->accessee.bindLevel != static_cast(USER)) { + jsonData[TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; + } + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; + jsonData[TAG_DEVICE_ID] = context->accessee.deviceId; + jsonData[TAG_PEER_USER_SPACE_ID] = context->accessee.userId; + jsonData[TAG_TOKEN_ID] = context->accessee.tokenId; + + std::string plainText = jsonData.Dump(); + std::string cipherText; + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange plainText=%{public}s", plainText.c_str()); + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange encryptMessage failed."); + return ret; + } + jsonObject[TAG_DATA] = cipherText; + return ret; +} + +// Create 160 message. +int32_t DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, + JsonObject &jsonObject) +{ + std::string onTransmitData; + + JsonObject jsonData; + jsonObject[TAG_DATA] = context->transmitData; + return DM_OK; +} + +// Create 190 message. +int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, + JsonObject &jsonObject) +{ + DmAccess access; + if (context->direction == DM_AUTH_SINK) { + access = context->accessee; + } else { + access = context->accesser; + } + + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, access, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageSyncResp encrypt failed"); + return ret; + } + jsonObject[TAG_SYNC] = encSyncMsg; + return ret; +} + +// Create 200 message. +int32_t DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr context, + JsonObject &jsonObject) +{ + jsonObject[TAG_REPLY] = context->reply; + jsonObject[TAG_STATE] = context->state; + jsonObject[TAG_REASON] = context->reason; + return DM_OK; +} + +bool DmAuthMessageProcessor::CheckAccessValidityAndAssign(std::shared_ptr &context, DmAccess &access, + DmAccess &accessTmp) +{ + const DmAccess &selfAccess = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + + bool isSame = accessTmp.dmVersion == access.dmVersion && + accessTmp.deviceName == access.deviceName && + Crypto::Sha256(accessTmp.deviceId) == access.deviceIdHash && + accessTmp.userId == access.userId && + Crypto::Sha256(accessTmp.accountId) == access.accountIdHash && + Crypto::Sha256(std::to_string(accessTmp.tokenId)) == access.tokenIdHash && + accessTmp.bundleName == access.bundleName && + accessTmp.pkgName == access.pkgName && + accessTmp.bindLevel == selfAccess.bindLevel; + if (isSame) { + access.transmitSessionKeyId = accessTmp.transmitSessionKeyId; + access.transmitSkTimeStamp = accessTmp.transmitSkTimeStamp; + access.transmitCredentialId = accessTmp.transmitCredentialId; + access.lnnSessionKeyId = accessTmp.lnnSessionKeyId; + access.lnnSkTimeStamp = accessTmp.lnnSkTimeStamp; + access.lnnCredentialId = accessTmp.lnnCredentialId; + } + return isSame; +} + +int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, JsonObject &jsonObject) +{ + DmAccess accessTmp; + // transmit session key is mandatory + if (!jsonObject[TAG_TRANSMIT_SK_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_ID error"); + return ERR_DM_FAILED; + } + accessTmp.transmitSessionKeyId = std::atoi(jsonObject[TAG_TRANSMIT_SK_ID].Get().c_str()); + + if (!jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_TIMESTAMP error"); + return ERR_DM_FAILED; + } + accessTmp.transmitSkTimeStamp = std::atoi(jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); + + if (!jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_CREDENTIAL_ID error"); + return ERR_DM_FAILED; + } + accessTmp.transmitCredentialId = jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str(); + + // lnn session key is optional + if (jsonObject[TAG_LNN_SK_ID].IsString()) { + accessTmp.lnnSessionKeyId = std::atoi(jsonObject[TAG_LNN_SK_ID].Get().c_str()); + } + if (jsonObject[TAG_LNN_SK_TIMESTAMP].IsString()) { + accessTmp.lnnSkTimeStamp = std::atoi(jsonObject[TAG_LNN_SK_TIMESTAMP].Get().c_str()); + } + + if (jsonObject[TAG_LNN_CREDENTIAL_ID].IsString()) { + accessTmp.lnnCredentialId = jsonObject[TAG_LNN_CREDENTIAL_ID].Get().c_str(); + } + + if (!jsonObject[TAG_DMVERSION].IsString()) { + LOGE("ParseSyncMessage TAG_DMVERSION error"); + return ERR_DM_FAILED; + } + + accessTmp.dmVersion = jsonObject[TAG_DMVERSION].Get(); + if (!jsonObject[TAG_ACCESS].IsString()) { + LOGE("ParseSyncMessage TAG_ACCESS error"); + return ERR_DM_FAILED; + } + std::string srcAccessStr = jsonObject[TAG_ACCESS].Get(); + // Parse into access + ParseDmAccessToSync(srcAccessStr, accessTmp); + // check access validity + if (!CheckAccessValidityAndAssign(context, access, accessTmp)) { + LOGE("ParseSyncMessage CheckAccessValidityAndAssign error, data between two stages different, stop auth."); + return ERR_DM_FAILED; + } + ParseDmAccessToSync(srcAccessStr, access); + if (!jsonObject[TAG_ACL_CHECKSUM].IsString()) { // Re-parse the acl + LOGE("ParseSyncMessage TAG_ACL_CHECKSUM error"); + return ERR_DM_FAILED; + } + access.aclStrList = jsonObject[TAG_ACL_CHECKSUM].Get(); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg) +{ + std::string syncMsgCompress = ""; + int32_t ret = cryptoMgr_->DecryptMessage(enSyncMsg, syncMsgCompress); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage syncMsg error"); + return ret; + } + JsonObject plainJson(syncMsgCompress); + if (plainJson.IsDiscarded()) { + LOGE("DecryptSyncMessage plainJson error"); + return ERR_DM_FAILED; + } + if (!plainJson[TAG_COMPRESS_ORI_LEN].IsNumberInteger()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + int32_t dataLen = plainJson[TAG_COMPRESS_ORI_LEN].Get(); + if (!plainJson[TAG_COMPRESS].IsString()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + std::string compressMsg = plainJson[TAG_COMPRESS].Get(); + std::string compressBase64 = Base64Decode(compressMsg); + std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); + JsonObject jsonObject(syncMsg); + if (jsonObject.IsDiscarded()) { + LOGE("DmAuthMessageProcessor::DecryptSyncMessage jsonStr error"); + return ERR_DM_FAILED; + } + + ret = ParseSyncMessage(context, access, jsonObject); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage ParseSyncMessage jsonStr error"); + return ret; + } + return DM_OK; +} + +// Parse 180 message, save remote encrypted quadruple, acl, sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (!jsonObject[TAG_SYNC].IsString()) { + LOGE("ParseMessageSyncReq json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); + // Decrypt data and parse data into context + int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 190 message save the remote encrypted quadruple, acl sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (!jsonObject[TAG_SYNC].IsString()) { + LOGE("ParseMessageSyncResp json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); + // Decrypt data and parse data into context + int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 200 message +int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); + } + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); + } + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 201 message +int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); + } + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); + } + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CheckLogicalSessionId(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + if (context->logicalSessionId != 0 && + jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get() != context->logicalSessionId) { + return ERR_DM_PARSE_MESSAGE_FAILED; + } + } + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + context->logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + context->requestId = static_cast(context->logicalSessionId); + } + + if (jsonObject[TAG_PKG_NAME].IsString()) { + context->pkgName = jsonObject[TAG_PKG_NAME].Get(); + context->accesser.pkgName = context->pkgName; + context->accessee.pkgName = context->accesser.pkgName; + } + + if (jsonObject[TAG_PEER_PKG_NAME].IsString()) { + context->accessee.pkgName = jsonObject[TAG_PEER_PKG_NAME].Get(); + } + + if (jsonObject[TAG_DM_VERSION_V2].IsString()) { + context->accesser.dmVersion = jsonObject[TAG_DM_VERSION_V2].Get(); + } + if (jsonObject[TAG_USER_ID].IsNumberInteger()) { + context->accesser.userId = jsonObject[TAG_USER_ID].Get(); + } + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); + } + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); + } + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); + } + if (jsonObject[TAG_BUNDLE_NAME_V2].IsString()) { + context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME_V2].Get(); + } + if (jsonObject[TAG_EXTRA_INFO].IsString()) { + context->accesser.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); + } + + if (jsonObject[TAG_PEER_BUNDLE_NAME_V2].IsString()) { + context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME_V2].Get(); + } + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); + } + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[TAG_DEVICE_VERSION].IsString()) { + context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].Get(); + } + + if (jsonObject[TAG_DEVICE_NAME].IsString()) { + context->accessee.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); + } + + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accessee.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); + } + + if (jsonObject[TAG_USER_ID].IsNumberInteger()) { + context->accessee.userId = jsonObject[TAG_USER_ID].Get(); + } + + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accessee.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); + } + + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accessee.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); + } + + if (jsonObject[TAG_IS_ONLINE].IsBoolean()) { + context->isOnline = jsonObject[TAG_IS_ONLINE].Get(); + } + + if (jsonObject[TAG_ACL_TYPE_LIST].IsString()) { + context->accessee.aclTypeList = jsonObject[TAG_ACL_TYPE_LIST].Get(); + } + + if (jsonObject[TAG_CERT_TYPE_LIST].IsString()) { + context->accessee.credTypeList = jsonObject[TAG_CERT_TYPE_LIST].Get(); + } + + if (jsonObject[TAG_LANGUAGE].IsString()) { + context->accessee.language = jsonObject[TAG_LANGUAGE].Get(); + } + + if (jsonObject[TAG_EXTRA_INFO].IsString()) { + context->accessee.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DEVICE_TYPE].IsNumberInteger()) { + context->accesser.deviceType = json[TAG_DEVICE_TYPE].Get(); + } + if (json[TAG_DEVICE_NAME].IsString()) { + context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); + } + if (json[TAG_AUTH_TYPE].IsNumberInteger()) { + context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); + } + if (json[TAG_ACL_TYPE_LIST].IsString()) { + context->accesser.aclTypeList = json[TAG_ACL_TYPE_LIST].Get(); + } + if (json[TAG_CERT_TYPE_LIST].IsString()) { + context->accesser.credTypeList = json[TAG_CERT_TYPE_LIST].Get(); + } + if (json[TAG_EXTRA_INFO].IsString()) { + context->accesser.extraInfo = json[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_CONFIRM_OPERATION_V2].IsNumberInteger()) { + context->confirmOperation = static_cast(json[TAG_CONFIRM_OPERATION_V2].Get()); + } + + if (json[TAG_AUTH_TYPE_LIST].IsString()) { + auto strList = json[TAG_AUTH_TYPE_LIST].Get(); + context->authTypeList = stringToVectorAuthType(strList); + } + if (json[TAG_EXTRA_INFO].IsString()) { + context->accessee.extraInfo = json[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) +{ + json[TAG_AUTH_TYPE] = context->authType; + json[TAG_ACL_TYPE_LIST] = context->accesser.aclTypeList; + json[TAG_CERT_TYPE_LIST] = context->accesser.credTypeList; + json[TAG_DEVICE_TYPE] = context->accesser.deviceType; + json[TAG_DEVICE_NAME] = context->accesser.deviceName; + json[TAG_EXTRA_INFO] = context->accesser.extraInfo; + + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) +{ + json[TAG_CONFIRM_OPERATION_V2] = context->confirmOperation; + json[TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); + json[TAG_EXTRA_INFO] = context->accessee.extraInfo; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) +{ + auto message = CreateMessage(msgType, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +std::string DmAuthMessageProcessor::CompressSyncMsg(std::string &inputStr) +{ + uint32_t srcLen = inputStr.size(); + uint32_t boundSize = compressBound(srcLen); // Maximum compression length + std::string compressed(boundSize, '\0'); + + // Compress to reserved space + unsigned long destSize = boundSize; // Actual usable length + int32_t ret = compress(reinterpret_cast(&compressed[0]), &destSize, + reinterpret_cast(inputStr.data()), srcLen); + if (ret != Z_OK) { + LOGE("DmAuthMessageProcessor::CompressSyncMsg zlib compress failed"); + return ""; + } + compressed.resize(destSize); // Actual usage length + return compressed; +} + +std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, uint32_t oriLen) +{ + std::string decompressed; + decompressed.resize(oriLen); + unsigned long destLen = oriLen; // Actual usage length + int32_t ret = uncompress(reinterpret_cast(&decompressed[0]), &destLen, + reinterpret_cast(compressed.data()), // Skip header when decompressing + compressed.size()); + if (ret != Z_OK || destLen != oriLen) { + LOGE("DmAuthMessageProcessor::DecompressSyncMsg decompress failed"); + return ""; + } + return decompressed; +} + +std::string DmAuthMessageProcessor::Base64Encode(std::string &inputStr) +{ + // Convert input string to binary + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // Calculate the maximum length after base64 encoding + size_t maxEncodeLen = ((srcLen + 2) / 3) * 4 + 1; + std::vector buffer(maxEncodeLen); + + // Actual encoding length + size_t encodedLen = 0; + int32_t ret = mbedtls_base64_encode(buffer.data(), buffer.size(), &encodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Encode mbedtls_base64_encode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), encodedLen); // No terminator needed +} + +std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) +{ + // Convert input string to binary + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // Calculate the maximum length after base64 encoding + size_t maxEncodeLen = (srcLen / 4) * 3 + 1; + std::vector buffer(maxEncodeLen); + + // Actual encoding length + size_t decodedLen = 0; + int32_t ret = mbedtls_base64_decode(buffer.data(), buffer.size(), &decodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Decode mbedtls_base64_decode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), decodedLen); // 无需终止符 +} + +int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, + std::string &encSyncMsg) +{ + JsonObject syncMsgJson; + DmAccessToSync accessToSync; + accessToSync.deviceName = accessSide.deviceName; + accessToSync.deviceId = accessSide.deviceId; + accessToSync.userId = accessSide.userId; + accessToSync.accountId = accessSide.accountId; + accessToSync.tokenId = accessSide.tokenId; + accessToSync.bundleName = accessSide.bundleName; + accessToSync.pkgName = accessSide.pkgName; + accessToSync.bindLevel = accessSide.bindLevel; + syncMsgJson[TAG_TRANSMIT_SK_ID] = std::to_string(accessSide.transmitSessionKeyId); + syncMsgJson[TAG_TRANSMIT_SK_TIMESTAMP] = std::to_string(accessSide.transmitSkTimeStamp); + syncMsgJson[TAG_TRANSMIT_CREDENTIAL_ID] = accessSide.transmitCredentialId; + // First certification + if (accessSide.isGenerateLnnCredential && accessSide.bindLevel != static_cast(USER)) { + syncMsgJson[TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); + syncMsgJson[TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); + syncMsgJson[TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; + } + JsonObject accessJsonObj{}; + accessJsonObj = accessToSync; + syncMsgJson[TAG_DMVERSION] = accessSide.dmVersion; + syncMsgJson[TAG_ACCESS] = accessJsonObj.Dump(); + syncMsgJson[TAG_PROXY] = ""; // Reserved field, leave blank + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + DmAccess &access = (context->accesser.deviceId == localUdid) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->accesser.deviceId == localUdid) ? context->accessee : context->accesser; + std::string aclHashList; + int32_t ret = DeviceProfileConnector::GetInstance().GetAclListHashStr(localUdid, access.userId, + remoteAccess.deviceId, remoteAccess.userId, accessSide.dmVersion, aclHashList); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage GetAclListHashStr failed"); + return ERR_DM_FAILED; + } + + syncMsgJson[TAG_ACL_CHECKSUM] = aclHashList; + std::string syncMsg = syncMsgJson.Dump(); + + std::string compressMsg = CompressSyncMsg(syncMsg); + if (compressMsg.empty()) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage compress failed"); + return ERR_DM_FAILED; + } + JsonObject plainJson; + plainJson[TAG_COMPRESS_ORI_LEN] = syncMsg.size(); + plainJson[TAG_COMPRESS] = Base64Encode(compressMsg); + return cryptoMgr_->EncryptMessage(plainJson.Dump(), encSyncMsg); +} + +int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr) +{ + DmAccessControlTable dmAcl; + dmAcl.accessControlId = acl.GetAccessControlId(); + dmAcl.accesserId = acl.GetAccesserId(); + dmAcl.accesseeId = acl.GetAccesseeId(); + dmAcl.deviceId = acl.GetTrustDeviceId(); + dmAcl.sessionKey = acl.GetSessionKey(); + dmAcl.bindType = acl.GetBindType(); + dmAcl.authType = acl.GetAuthenticationType(); + dmAcl.deviceType = acl.GetDeviceIdType(); + dmAcl.deviceIdHash = acl.GetDeviceIdHash(); + dmAcl.status = acl.GetStatus(); + dmAcl.validPeriod = acl.GetValidPeriod(); + dmAcl.lastAuthTime = acl.GetLastAuthTime(); + dmAcl.bindLevel = acl.GetBindType(); + JsonObject aclJsonObj{}; + aclJsonObj = dmAcl; + aclStr = aclJsonObj.Dump(); + if (aclStr.empty()) { + LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject) +{ + DmAccess accessSide; + if (context->direction == DM_AUTH_SOURCE) { + accessSide = context->accesser; + } else { + accessSide = context->accessee; + } + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, accessSide, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); + return ret; + } + jsonObject[TAG_SYNC] = encSyncMsg; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || + !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json string failed"); + return ERR_DM_FAILED; + } + context->transmitData = jsonObject[TAG_DATA].Get(); + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + + +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table) +{ + itemObject["accessControlId"] = table.accessControlId; + itemObject["accesserId"] = table.accesserId; + itemObject["accesseeId"] = table.accesseeId; + itemObject["deviceId"] = table.deviceId; + itemObject["sessionKey"] = table.sessionKey; + itemObject["bindType"] = table.bindType; + itemObject["authType"] = table.authType; + itemObject["deviceType"] = table.deviceType; + itemObject["deviceIdHash"] = table.deviceIdHash; + itemObject["status"] = table.status; + itemObject["validPeriod"] = table.validPeriod; + itemObject["lastAuthTime"] = table.lastAuthTime; + itemObject["bindLevel"] = table.bindLevel; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) +{ + SetValueFromJson(itemObject, "accessControlId", &JsonItemObject::IsNumberInteger, table.accessControlId); + SetValueFromJson(itemObject, "accesserId", &JsonItemObject::IsNumberInteger, table.accesserId); + SetValueFromJson(itemObject, "accesseeId", &JsonItemObject::IsNumberInteger, table.accesseeId); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsNumberInteger, table.deviceId); + SetValueFromJson(itemObject, "sessionKey", &JsonItemObject::IsString, table.sessionKey); + SetValueFromJson(itemObject, "bindType", &JsonItemObject::IsNumberInteger, table.bindType); + SetValueFromJson(itemObject, "authType", &JsonItemObject::IsNumberInteger, table.authType); + SetValueFromJson(itemObject, "deviceType", &JsonItemObject::IsNumberInteger, table.deviceType); + SetValueFromJson(itemObject, "deviceIdHash", &JsonItemObject::IsString, table.deviceIdHash); + SetValueFromJson(itemObject, "status", &JsonItemObject::IsNumberInteger, table.status); + SetValueFromJson(itemObject, "validPeriod", &JsonItemObject::IsNumberInteger, table.validPeriod); + SetValueFromJson(itemObject, "lastAuthTime", &JsonItemObject::IsNumberInteger, table.lastAuthTime); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); +} + +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) +{ + itemObject["deviceName"] = table.deviceName; + itemObject["deviceId"] = table.deviceId; + itemObject["userId"] = table.userId; + itemObject["accountId"] = table.accountId; + itemObject["tokenId"] = table.tokenId; + itemObject["bundleName"] = table.bundleName; + itemObject["pkgName"] = table.pkgName; + itemObject["bindLevel"] = table.bindLevel; + itemObject["sessionKeyId"] = table.sessionKeyId; + itemObject["skTimeStamp"] = table.skTimeStamp; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table) +{ + SetValueFromJson(itemObject, "deviceName", &JsonItemObject::IsString, table.deviceName); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsString, table.deviceId); + SetValueFromJson(itemObject, "userId", &JsonItemObject::IsNumberInteger, table.userId); + SetValueFromJson(itemObject, "accountId", &JsonItemObject::IsString, table.accountId); + SetValueFromJson(itemObject, "tokenId", &JsonItemObject::IsNumberInteger, table.tokenId); + SetValueFromJson(itemObject, "bundleName", &JsonItemObject::IsString, table.bundleName); + SetValueFromJson(itemObject, "pkgName", &JsonItemObject::IsString, table.pkgName); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); + SetValueFromJson(itemObject, "sessionKeyId", &JsonItemObject::IsNumberInteger, table.sessionKeyId); + SetValueFromJson(itemObject, "skTimeStamp", &JsonItemObject::IsNumberInteger, table.skTimeStamp); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp new file mode 100644 index 000000000..dcc2c87f6 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "access_control_profile.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" +#include "dm_crypto.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "dm_softbus_cache.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), CLONE_PIN_AUTH_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + +const std::map NEW_AND_OLD_STATE_MAPPING = { + { DmAuthStateType::AUTH_SRC_FINISH_STATE, DmAuthStatus::STATUS_DM_AUTH_FINISH }, + { DmAuthStateType::AUTH_SINK_FINISH_STATE, DmAuthStatus::STATUS_DM_AUTH_FINISH } +}; + +constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; +constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication" +}; +constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { + "CollaborationFwk", + "gameservice_server" +}; + + +int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + +void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) +{ + LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); + context->timer->DeleteTimer(name); + context->reason = ERR_DM_TIME_OUT; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + LOGI("DmAuthContext::HandleAuthenticateTimeout complete"); +} + +bool DmAuthState::IsScreenLocked() +{ + bool isLocked = false; +#if defined(SUPPORT_SCREENLOCK) + isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); +#endif + LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); + return isLocked; +} + +void DmAuthState::SourceFinish(std::shared_ptr context) +{ + LOGI("SourceFinish reason:%{public}d", context->reason); + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, + GetOutputState(context->state), context->reason); + context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, + GetOutputState(context->state), GenerateBindResultContent(context)); + context->successFinished = true; + + if (context->reason != DM_OK && context->reason != DM_ALREADY_AUTHED) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, + context->accesser.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, + context->accesser.transmitSessionKeyId); + } + LOGI("SourceFinish notify online"); + if (SoftbusCache::GetInstance().CheckIsOnline(context->accessee.deviceId)) { + context->softbusConnector->HandleDeviceOnline(context->accessee.deviceId, context->GetBindType()); + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + context->timer->DeleteAll(); +} + +void DmAuthState::SinkFinish(std::shared_ptr context) +{ + LOGI("SinkFinish reason:%{public}d", context->reason); + context->listener->OnSinkBindResult(context->processInfo, context->peerTargetId, context->reply, + GetOutputState(context->state), GenerateBindResultContent(context)); + context->successFinished = true; + if (context->reason != DM_OK) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, + context->accessee.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, + context->accessee.transmitSessionKeyId); + } else { + SetAclInfo(context); + if (NeedAgreeAcl(context)) { + context->authMessageProcessor->PutAccessControlList(context, + context->accessee, context->accesser.deviceId); + } + LOGI("SinkFinish notify online"); + if (SoftbusCache::GetInstance().CheckIsOnline(context->accesser.deviceId)) { + context->softbusConnector->HandleDeviceOnline(context->accesser.deviceId, context->GetBindType()); + } + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + context->timer->DeleteAll(); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 +} + +std::string DmAuthState::GenerateBindResultContent(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ""); + DmAccess access = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + context->accessee : context->accesser; + JsonObject jsonObj; + jsonObj[DM_BIND_RESULT_NETWORK_ID] = access.networkId; + if (access.deviceId.empty()) { + jsonObj[TAG_DEVICE_ID] = ""; + } else { + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(access.deviceId, reinterpret_cast(deviceIdHash)); + jsonObj[TAG_DEVICE_ID] = deviceIdHash; + } + jsonObj[TAG_CONFIRM_OPERATION_V2] = context->confirmOperation; + std::string content = jsonObj.Dump(); + return content; +} + +bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) +{ + // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + return true; + } + + // 有ACL,跳转到结束状态,发200报文,直接组网 + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + if (access.isAuthed) { + return false; + } + + return true; +} + +bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) +{ + return context->needAgreeCredential; +} + +bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) +{ + return (context->direction == DM_AUTH_SOURCE) ? !context->accesser.isAuthed : !context->accessee.isAuthed; +} + +bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) +{ + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || + authType == DmAuthType::AUTH_TYPE_NFC) { + return true; + } + return false; +} + + + +void DmAuthState::SetAclExtraInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + JsonObject jsonObj; + jsonObj[TAG_DMVERSION] = access.dmVersion; + access.extraInfo = jsonObj.Dump(); + remoteAccess.extraInfo = jsonObj.Dump(); +} + +void DmAuthState::SetAclInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + SetAclExtraInfo(context); + access.lnnBindType = GetAclBindType(context, access.lnnCredentialId); + remoteAccess.lnnBindType = GetAclBindType(context, remoteAccess.lnnCredentialId); + + access.transmitBindType = GetAclBindType(context, access.transmitCredentialId); + remoteAccess.transmitBindType = GetAclBindType(context, remoteAccess.transmitCredentialId); +} + +int32_t DmAuthState::GetAclBindType(std::shared_ptr context, std::string credId) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + JsonObject result; + int32_t ret = context->hiChainAuthConnector->QueryCredInfoByCredId(access.userId, credId, result); + if (ret != DM_OK) { + LOGE("GetAclBindType QueryCredInfoByCredId failed, ret: %{public}d.", ret); + return DM_UNKNOWN_TYPE; + } + if (!result.Contains(credId)) { + LOGE("GetAclBindType result not contains credId."); + return DM_UNKNOWN_TYPE; + } + int32_t credType = result[credId][FILED_CRED_TYPE].Get(); + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED) { + return DM_SAME_ACCOUNT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) { + return DM_POINT_TO_POINT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { + return DM_SHARE_TYPE; + } + return DM_UNKNOWN_TYPE; +} + +uint32_t DmAuthState::GetCredType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + int32_t subject = credInfo[FILED_SUBJECT].Get(); + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { + return DM_LNN; + } + return DM_INVALIED_TYPE; +} + +uint32_t DmAuthState::GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + CHECK_NULL_RETURN(context, DM_INVALIED_TYPE); + if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || + !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return DM_INVALIED_TYPE; + } + return GetCredType(context, credInfo); +} + +bool DmAuthState::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return ((srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash)) || + ((sinkTokenIdHash == context->accesser.tokenIdHash) && + (srcTokenIdHash == context->accessee.tokenIdHash)); +} + +bool DmAuthState::CheckProcessNameInWhiteList(const std::string &processName) +{ + LOGI("DmAuthState::CheckProcessNameInWhiteList start"); + if (processName.empty()) { + LOGE("processName is empty"); + return false; + } + uint16_t index = 0; +#ifdef DEVICE_MANAGER_COMMON_FLAG + for (; index < OPEN_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(OPEN_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#else + for (; index < CLOSE_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(CLOSE_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#endif + LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); + return false; +} + +int32_t DmAuthState::GetOutputState(int32_t state) +{ + auto it = NEW_AND_OLD_STATE_MAPPING.find(static_cast(state)); + if (it == NEW_AND_OLD_STATE_MAPPING.end()) { + return state; + } + return static_cast(it->second); +} + +void DmAuthState::DeleteAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile) +{ + CHECK_NULL_VOID(context); + LOGI("direction %{public}d.", static_cast(context->direction)); + CHECK_NULL_VOID(context->authMessageProcessor); + CHECK_NULL_VOID(context->hiChainAuthConnector); + int32_t userId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserUserId() : profile.GetAccessee().GetAccesseeUserId(); + int32_t sessionKeyId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserSessionKeyId() : profile.GetAccessee().GetAccesseeSessionKeyId(); + std::string credId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserCredentialIdStr() : profile.GetAccessee().GetAccesseeCredentialIdStr(); + + context->authMessageProcessor->DeleteSessionKeyToDP(userId, sessionKeyId); + context->hiChainAuthConnector->DeleteCredential(userId, credId); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp new file mode 100644 index 000000000..6cef7a6dc --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_log.h" +#include "dm_constants.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + +DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) +{ + exceptionEvent_= { + DmEventType::ON_ERROR, // Authentication error, there is a possibility of retry. + DmEventType::ON_TIMEOUT, + DmEventType::ON_FAIL, // Authentication failed + DmEventType::ON_SCREEN_LOCKED, + }; + + running_ = true; + direction_ = context->direction; + + if (direction_ == DM_AUTH_SOURCE) { + this->InsertSrcTransTable(); + } else { + this->InsertSinkTransTable(); + } + + this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); + thread_ = std::thread(&DmAuthStateMachine::Run, this, context); +} + +DmAuthStateMachine::~DmAuthStateMachine() +{ + Stop(); + thread_.join(); +} + +void DmAuthStateMachine::InsertSrcTransTable() +{ + // Source-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, + {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, + }}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SRC_FINISH_STATE}}, + + {DmAuthStateType::AUTH_SRC_FINISH_STATE, {}} + }); + + return; +} + +void DmAuthStateMachine::InsertSinkTransTable() +{ + // Sink-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_CONFIRM_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_FINISH_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, + + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, + {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}} + }); + + return; +} + +// Notification status transition. The execution status corresponds to specific actions and exception handling. +int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) +{ + int32_t ret = DM_OK; + DmAuthStateType nextState = state->GetStateType(); + { + std::lock_guard lock(stateMutex_); + if (this->CheckStateTransitValid(nextState)) { + LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", + statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + statesQueue_.push(state); + } else { + // The state transition is invalid. + LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", + statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + ret = ERR_DM_NEXT_STATE_INVALID; + reason = ERR_DM_NEXT_STATE_INVALID; + if (direction_ == DM_AUTH_SOURCE) { + statesQueue_.push(std::make_shared()); + } else { + statesQueue_.push(std::make_shared()); + } + } + } + stateCv_.notify_one(); + return ret; +} + +/* +Expected event in an action, which is used for blocking. +When the expected event is complete or other exceptions occur, the actual event is returned. +Other normal events continue to be blocked (only in the action). +*/ +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) +{ + /* + 1. Actual event = Expected event, return actual event + 2. Actual event = Abnormal event (event timeout). The actual event is also returned. + 3. Actual event = Other events, continue to block, but there is a timeout limit. + */ + std::unique_lock lock(eventMutex_); + auto startTime = std::chrono::high_resolution_clock::now(); + while (running_.load()) { + eventCv_.wait(lock, [&] { + return !running_.load() || !eventQueue_.empty(); + }); + if (!running_.load()) { + return DmEventType::ON_FAIL; + } + + DmEventType actualEventType = eventQueue_.front(); + eventQueue_.pop(); + // Determine whether the event is an expected event or abnormal event in list. + if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { + return actualEventType; + } + // Event Wait Timeout + auto elapsedTime = std::chrono::duration_cast( + std::chrono::high_resolution_clock::now() - startTime); + if (elapsedTime.count() >= EVENT_TIMEOUT) { + break; + } + } + return DmEventType::ON_TIMEOUT; +} + +/* +The event is invoked after the event is complete. +The event enumeration can be invoked only when the event is triggered. +If the event is an abnormal event, the reason or reply of the context must be recorded. +*/ +void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) +{ + LOGI("DmAuthStateMachine: NotifyEventFinish Event:%{public}d.", eventType); + { + std::unique_lock lock(eventMutex_); + eventQueue_.push(eventType); + } + eventCv_.notify_one(); + if (eventType == DmEventType::ON_FAIL) { + if (direction_ == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + } +} + +// Cyclically wait for state transition and execute action. +void DmAuthStateMachine::Run(std::shared_ptr context) +{ + while (running_.load()) { + auto state = FetchAndSetCurState(); + if (!state.has_value()) { + break; + } + if (reason != DM_OK) { + context->reason = reason; + } + // Obtain the status and execute the status action. + DmAuthStateType stateType = state.value()->GetStateType(); + int32_t ret = state.value()->Action(context); + if (ret != DM_OK) { + LOGE("DmAuthStateMachine::Run err:%{public}d", ret); + if (context->reason == DM_OK) { + // If the context reason is not set, set action ret. + context->reason = ret; + } + context->state = static_cast(stateType); + context->successFinished = false; + if (context->direction == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + } else { + LOGI("DmAuthStateMachine::Run ok state:%{public}d", stateType); + } + } + LOGI("DmAuthStateMachine::Run end"); +} + +std::optional> DmAuthStateMachine::FetchAndSetCurState() +{ + std::unique_lock lock(stateMutex_); + stateCv_.wait(lock, [&] { + return !running_.load() || !statesQueue_.empty(); + }); + + if (!running_.load()) return std::nullopt; + + std::shared_ptr state = statesQueue_.front(); + statesQueue_.pop(); + SetCurState(state->GetStateType()); + return state; +} + +void DmAuthStateMachine::Stop() +{ + std::lock_guard lock(stateMutex_); // Use locking to prevent signal loss + running_.store(false); + stateCv_.notify_all(); + eventCv_.notify_all(); +} + +void DmAuthStateMachine::SetCurState(DmAuthStateType state) +{ + LOGI("DmAuthStateMachine::SetCurState state: %{public}d", state); + curState_ = state; +} + +DmAuthStateType DmAuthStateMachine::GetCurState() +{ + return curState_; +} + +// Verify the validity of the next state transition. +bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) +{ + if (curState_ == nextState || curState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || + curState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return false; + } + + /* + Check whether the next state is AuthSrcFinishState or AuthSinkFinishState + which can directly switch to the state and return. + */ + if (direction_ == DM_AUTH_SOURCE) { + if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE) { + return true; + } + } else { + if (nextState == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return true; + } + } + // Check whether the state transition table is met. + DmAuthStateType state = curState_; + if (!statesQueue_.empty()) { + state = statesQueue_.back()->GetStateType(); + } + auto it = stateTransitionTable_.find(state); + if (it != stateTransitionTable_.end()) { + const std::set& allowedStates = it->second; + return allowedStates.find(nextState) != allowedStates.end(); + } + return false; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_negotiate_process.cpp b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp new file mode 100644 index 000000000..8111934cf --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_negotiate_process.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(NegotiateProcess); + +int32_t OnlyPinBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = true; + context->needAgreeCredential = false; + context->needAuth = false; + return DM_OK; +} + +int32_t EndBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = false; + context->needAgreeCredential = false; + context->needAuth = false; + context->reason = ERR_DM_BIND_TRUST_TARGET; + return ERR_DM_BIND_TRUST_TARGET; +} + +int32_t OnlyCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = false; + context->needAgreeCredential = false; + context->needAuth = true; + return DM_OK; +} + +int32_t PinBindAndCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = true; + context->needAgreeCredential = true; + context->needAuth = true; + return DM_OK; +} + +NegotiateProcess::NegotiateProcess() +{ + LOGI("start."); + handlers_[NegotiateSpec(CredType::DM_NO_CRED, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_NO_CRED, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_IDENTICAL_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_IDENTICAL_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); +} + +int32_t NegotiateProcess::HandleNegotiateResult(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + std::string credTypeList = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + context->accesser.credTypeList : context->accessee.credTypeList; + std::string aclTypeList = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + context->accesser.aclTypeList : context->accessee.aclTypeList; + CredType credType = ConvertCredType(credTypeList); + AclType aclType = ConvertAclType(aclTypeList); + AuthType authType = ConvertAuthType(context->authType); + LOGI("credType %{public}d, aclType %{public}d, authType %{public}d.", + static_cast(credType), static_cast(aclType), static_cast(authType)); + NegotiateSpec negotiateSpec(credType, aclType, authType); + auto handler = handlers_.find(negotiateSpec); + if (handler != handlers_.end()) { + return handler->second->NegotiateHandle(context); + } + return ERR_DM_CAPABILITY_NEGOTIATE_FAILED; +} + +CredType NegotiateProcess::ConvertCredType(const std::string &credType) +{ + LOGI("start credType %{public}s.", credType.c_str()); + CredType credTypeTemp = CredType::DM_NO_CRED; + if (credType.empty()) { + return credTypeTemp; + } + JsonObject credTypeJson; + credTypeJson.Parse(credType); + if (credTypeJson.IsDiscarded()) { + LOGE("Parse credType str failed."); + return credTypeTemp; + } + if (credTypeJson.Contains("identicalCredType")) { + credTypeTemp = CredType::DM_IDENTICAL_CREDTYPE; + } else if (credTypeJson.Contains("shareCredType")) { + credTypeTemp = CredType::DM_SHARE_CREDTYPE; + } else if (credTypeJson.Contains("pointTopointCredType")) { + credTypeTemp = CredType::DM_P2P_CREDTYPE; + } else { + credTypeTemp = CredType::DM_NO_CRED; + } + return credTypeTemp; +} + +AclType NegotiateProcess::ConvertAclType(const std::string &aclType) +{ + LOGI("start credType %{public}s.", aclType.c_str()); + AclType aclTypeTemp = AclType::DM_NO_ACL; + if (aclType.empty()) { + return aclTypeTemp; + } + JsonObject aclTypeJson; + aclTypeJson.Parse(aclType); + if (aclTypeJson.IsDiscarded()) { + LOGE("Parse credType str failed."); + return aclTypeTemp; + } + if (aclTypeJson.Contains("identicalAcl")) { + aclTypeTemp = AclType::DM_IDENTICAL_ACL; + } else if (aclTypeJson.Contains("shareAcl")) { + aclTypeTemp = AclType::DM_SHARE_ACL; + } else if (aclTypeJson.Contains("pointTopointAcl")) { + aclTypeTemp = AclType::DM_P2P_ACL; + } else { + aclTypeTemp = AclType::DM_NO_ACL; + } + return aclTypeTemp; +} + +AuthType NegotiateProcess::ConvertAuthType(const DmAuthType &authType) +{ + LOGI("start authType %{public}d.", static_cast(authType)); + AuthType authTypeTemp = AuthType::DM_INVALIED_AUTHTYPE; + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || authType == DmAuthType::AUTH_TYPE_NFC) { + authTypeTemp = AuthType::DM_IMPORT_AUTHTYPE; + } else { + authTypeTemp = AuthType::DM_INPUT_PINCODE; + } + return authTypeTemp; +} + +int32_t NoCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t NoCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t IdentCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t IdentCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t IdentCredIdentAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t IdentCredIdentAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t IdentCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t IdentCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t ShareCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t ShareCredNoAclImputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t ShareCredShareAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t ShareCredShareAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t ShareCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t ShareCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t P2pCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t P2pCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t P2pCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t P2pCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/cryptomgr/crypto_mgr.cpp b/services/implementation/src/cryptomgr/crypto_mgr.cpp index 91d35dee0..4af9f65f9 100644 --- a/services/implementation/src/cryptomgr/crypto_mgr.cpp +++ b/services/implementation/src/cryptomgr/crypto_mgr.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "mbedtls/base64.h" #include "mbedtls/cipher.h" @@ -308,6 +309,12 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL return DM_OK; } +std::vector CryptoMgr::GetSessionKey() +{ + std::lock_guard lock(sessionKeyMtx_); + return std::vector(sessionKey_.key, sessionKey_.key + sessionKey_.keyLen); +} + void CryptoMgr::ClearSessionKey() { std::lock_guard lock(sessionKeyMtx_); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 5732e0e7f..6ddbc6626 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#include #include "hichain_auth_connector.h" #include "dm_log.h" @@ -25,6 +27,7 @@ namespace OHOS { namespace DistributedHardware { std::shared_ptr HiChainAuthConnector::dmDeviceAuthCallback_ = nullptr; +std::map> HiChainAuthConnector::dmDeviceAuthCallbackMap_; std::mutex HiChainAuthConnector::dmDeviceAuthCallbackMutex_; void HiChainAuthConnector::FreeJsonString(char *jsonStr) @@ -47,6 +50,11 @@ HiChainAuthConnector::HiChainAuthConnector() HiChainAuthConnector::~HiChainAuthConnector() { + for (auto& pair : dmDeviceAuthCallbackMap_) { + pair.second = nullptr; + } + dmDeviceAuthCallbackMap_.clear(); + dmDeviceAuthCallback_ = nullptr; LOGI("HiChainAuthConnector::destructor."); } @@ -57,6 +65,28 @@ int32_t HiChainAuthConnector::RegisterHiChainAuthCallback(std::shared_ptr callback) +{ + std::lock_guard lock(dmDeviceAuthCallbackMutex_); + dmDeviceAuthCallbackMap_[id] = callback; + return DM_OK; +} + +std::shared_ptr HiChainAuthConnector::GetDeviceAuthCallback(int64_t id) +{ + if (dmDeviceAuthCallbackMap_.find(id) != dmDeviceAuthCallbackMap_.end()) { + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ id: %{public}" PRId64 ".", id); + return dmDeviceAuthCallbackMap_[id]; + } + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ not found, id: %{public}" + PRId64 ".", id); + // If the callback registered by the new protocol ID cannot be found, the callback registered + // by the old protocol is used. However, the old protocol callback may be empty. + return dmDeviceAuthCallback_; +} + int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) { LOGI("HiChainAuthConnector::AuthDevice start."); @@ -89,39 +119,172 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut return DM_OK; } +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + LOGI("HiChainAuthConnector::ProcessCredData start."); + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->processCredData(authReqId, reinterpret_cast(data.c_str()), + data.length(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("Hichain processData failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::ProcessCredData leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AddCredential start."); + LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", + osAccountId, authParams.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain addCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", + ret, returnData); + credId = std::string(returnData); + LOGI("HiChainAuthConnector::AddCredential addCredId=%{public}s.", credId.c_str()); + credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AddCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + LOGI("HiChainAuthConnector::ExportCredential start. osAccountId=%{public}d, credId=%{public}s", + osAccountId, credId.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain exportCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam(returnData); + credManager->destroyInfo(&returnData); + if (jsonAuthParam.IsDiscarded() || !jsonAuthParam["keyValue"].IsString()) { + LOGE("Hichain exportCredential failed, returnData is invalid."); + return ERR_DM_FAILED; + } + + publicKey = jsonAuthParam["keyValue"].Get(); + LOGI("HiChainAuthConnector::ExportCredential leave. publicKey=%{public}s", publicKey.c_str()); + return DM_OK; +} + +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AgreeCredential start."); + LOGI("HiChainAuthConnector::AgreeCredential osAccountId=%{public}d, selfCredId=%{public}s, authParams=%{public}s\n", + osAccountId, selfCredId.c_str(), authParams.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain agreeCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + credId = returnData; + credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AgreeCredential leave agreeCredId=%{public}s.", credId.c_str()); + return DM_OK; +} + +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &credId) +{ + LOGI("HiChainAuthConnector::DeleteCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->deleteCredential(osAccountId, credId.c_str()); + if (ret != HC_SUCCESS) { + LOGE("Hichain deleteCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::DeleteCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); + if (credId.empty() && pinCode.empty()) { + LOGE("HiChainAuthConnector::AuthCredential failed, credId and pinCode is empty."); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam; + if (!credId.empty()) { + jsonAuthParam["credId"] = credId; + } + if (!pinCode.empty()) { + jsonAuthParam["pinCode"] = pinCode; + } + std::string authParams = jsonAuthParam.Dump(); + + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::AuthCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start."); + if (pinCode == INVALID_PINCODE) { + LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pinCode is empty."); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam; + + jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonAuthParam[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + + std::string authParams = jsonAuthParam.Dump(); + + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + + return DM_OK; +} + bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("AuthDevice onTransmit, requestId %{public}" PRId64, requestId); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onTransmit dmDeviceAuthCallback_ is nullptr."); return false; } - return dmDeviceAuthCallback_->AuthDeviceTransmit(requestId, data, dataLen); + return dmDeviceAuthCallback->AuthDeviceTransmit(requestId, data, dataLen); } char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { LOGI("HiChainAuthConnector::onRequest start."); - (void)requestId; - (void)reqParams; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onRequest dmDeviceAuthCallback_ is nullptr."); return nullptr; } - JsonObject jsonObj; - int32_t pinCode = INVALID_PINCODE; - if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - } - std::string deviceId = ""; - dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafetyDump(jsonObj); - char *buffer = strdup(jsonStr.c_str()); - return buffer; + return dmDeviceAuthCallback->AuthDeviceRequest(requestId, operationCode, reqParams); } void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) @@ -129,11 +292,12 @@ void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const LOGI("HiChainAuthConnector::onFinish reqId:%{public}" PRId64 ", operation:%{public}d.", requestId, operationCode); (void)returnData; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onFinish dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceFinish(requestId); + dmDeviceAuthCallback->AuthDeviceFinish(requestId); } void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) @@ -142,7 +306,8 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err requestId, operationCode, errorCode); (void)operationCode; (void)errorReturn; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onError dmDeviceAuthCallback_ is nullptr."); return; } @@ -150,17 +315,18 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err if (errorCode == PROOF_MISMATCH) { dmErrorCode = ERR_DM_HICHAIN_PROOFMISMATCH; } - dmDeviceAuthCallback_->AuthDeviceError(requestId, dmErrorCode); + dmDeviceAuthCallback->AuthDeviceError(requestId, dmErrorCode); } void HiChainAuthConnector::onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { LOGI("HiChainAuthConnector::onSessionKeyReturned start."); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onSessionKeyReturned dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); + dmDeviceAuthCallback->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); } int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey) @@ -185,21 +351,88 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t LOGE("Decode generate return data jsonStr error."); return ERR_DM_FAILED; } - if (!IsString(jsonObject, "publicKey")) { + if (!IsInt32(jsonObject, "result") || !IsString(jsonObject, "publicKey") || + jsonObject["result"].Get() != HC_SUCCESS) { LOGE("Hichain generate public key jsonObject invalied."); return ERR_DM_FAILED; } + if (jsonObject["result"].Get() != 0) { + LOGE("Hichain generate public key failed"); + return ERR_DM_FAILED; + } publicKey = jsonObject["publicKey"].Get(); return DM_OK; } -bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, + JsonObject &resultJson) { - LOGI("QueryCredential start, deviceId: %{public}s, peerOsAccountId: %{public}d", - GetAnonyString(localUdid).c_str(), peerOsAccountId); + int32_t ret; + + const CredManager *cm = GetCredMgrInstance(); + char *credIdList = nullptr; + ret = cm->queryCredentialByParams(userId, queryParams.Dump().c_str(), + &credIdList); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list with ret %{public}d.", ret); + return ERR_DM_FAILED; + } + JsonObject credIdListJson(credIdList); + FreeJsonString(credIdList); + if (credIdListJson.IsDiscarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential id list to jsonStr error"); + return ERR_DM_FAILED; + } + + for (const auto& element : credIdListJson.Items()) { + if (!element.IsString()) { + continue; + } + std::string credId = element.Get(); + + char *returnCredInfo = nullptr; + ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential info."); + return ERR_DM_FAILED; + } + JsonObject credInfoJson(returnCredInfo); + FreeJsonString(returnCredInfo); + if (credInfoJson.IsDiscarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential info jsonStr error"); + return ERR_DM_FAILED; + } + + resultJson.Insert(credId, credInfoJson); + } + + return DM_OK; +} + +int32_t HiChainAuthConnector::QueryCredInfoByCredId(int32_t userId, std::string credId, JsonObject &resultJson) +{ + const CredManager *cm = GetCredMgrInstance(); + char *returnCredInfo = nullptr; + int32_t ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("[HICHAIN]::QueryCredInfoByCredId failed, ret: %{public}d.", ret); + return ret; + } + JsonObject credInfoJson(returnCredInfo); + FreeJsonString(returnCredInfo); + if (credInfoJson.IsDiscarded()) { + LOGE("QueryCredInfoByCredId credential info jsonStr error"); + return ERR_DM_FAILED; + } + resultJson.Insert(credId, credInfoJson); + return DM_OK; +} + +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) +{ + LOGI("HiChainAuthConnector::QueryCredential start."); JsonObject jsonObj; jsonObj["osAccountId"] = osAccountId; - jsonObj["peerOsAccountId"] = peerOsAccountId; jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; @@ -217,7 +450,11 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc LOGE("Decode query return data jsonStr error."); return false; } - if (!IsString(jsonObject, "publicKey")) { + if (!IsInt32(jsonObject, "result") || jsonObject["result"].Get() == -1) { + LOGE("Hichain generate public key failed."); + return false; + } + if (!IsString(jsonObject, "publicKey") || jsonObject["result"].Get() == 1) { LOGI("Credential not exist."); return false; } @@ -246,7 +483,11 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc LOGE("Decode query return data jsonStr error."); return ERR_DM_FAILED; } - if (!IsString(jsonObject, "publicKey")) { + if (!IsInt32(jsonObject, "result") || jsonObject["result"].Get() == -1) { + LOGE("Hichain generate public key failed."); + return ERR_DM_FAILED; + } + if (!IsString(jsonObject, "publicKey") || jsonObject["result"].Get() == 1) { LOGI("Credential not exist."); return ERR_DM_FAILED; } @@ -254,14 +495,11 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc return DM_OK; } -int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, - std::string publicKey) +int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) { - LOGI("ImportCredential start, deviceId: %{public}s, peerOsAccountId: %{public}d", - GetAnonyString(deviceId).c_str(), peerOsAccountId); + LOGI("HiChainAuthConnector::ImportCredential"); JsonObject jsonObj; jsonObj["osAccountId"] = osAccountId; - jsonObj["peerOsAccountId"] = peerOsAccountId; jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; @@ -272,19 +510,32 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, int32_t peer FreeJsonString(returnData); return ERR_DM_FAILED; } + std::string returnDataStr = static_cast(returnData); FreeJsonString(returnData); + JsonObject jsonObject(returnDataStr); + if (jsonObject.IsDiscarded()) { + LOGE("Decode import return data jsonStr error."); + return ERR_DM_FAILED; + } + if (!IsInt32(jsonObject, "result")) { + LOGI("Hichain import public key jsonObject invalied."); + return ERR_DM_FAILED; + } + int32_t result = jsonObject["result"].Get(); + if (result != 0) { + LOGE("Hichain import public key result is %{public}d.", result); + return ERR_DM_FAILED; + } return DM_OK; } -int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int32_t userId, int32_t peerUserId) +int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int32_t userId) { - LOGI("DeleteCredential start, deviceId: %{public}s, peerUserId: %{public}d", - GetAnonyString(deviceId).c_str(), peerUserId); + LOGI("DeleteCredential start."); JsonObject jsonObj; jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - jsonObj["peerOsAccountId"] = peerUserId; std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { @@ -292,8 +543,18 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 FreeJsonString(returnData); return false; } + std::string returnDataStr = static_cast(returnData); FreeJsonString(returnData); - return DM_OK; + JsonObject jsonObject(returnDataStr); + if (jsonObject.IsDiscarded()) { + LOGE("Decode import return data jsonStr error."); + return false; + } + if (!IsInt32(jsonObject, "result")) { + LOGI("Hichain delete credential result json key is invalid."); + return ERR_DM_FAILED; + } + return jsonObject["result"].Get(); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 0af963094..680c1c4fd 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -28,12 +28,14 @@ #include "json_object.h" #include "parameter.h" #include "system_ability_definition.h" +#include "deviceprofile_connector.h" namespace OHOS { namespace DistributedHardware { const int32_t SOFTBUS_SUBSCRIBE_ID_MASK = 0x0000FFFF; const int32_t SOFTBUS_DISCOVER_DEVICE_INFO_MAX_SIZE = 100; const int32_t SOFTBUS_TRUSTDEVICE_UUIDHASH_INFO_MAX_SIZE = 100; +const int32_t DM_VERSION_5_1_0 = 510; constexpr const char* WIFI_IP = "WIFI_IP"; constexpr const char* WIFI_PORT = "WIFI_PORT"; @@ -41,6 +43,10 @@ constexpr const char* BR_MAC = "BR_MAC"; constexpr const char* BLE_MAC = "BLE_MAC"; constexpr const char* ETH_IP = "ETH_IP"; constexpr const char* ETH_PORT = "ETH_PORT"; +namespace { + const char* TAG_ACL = "accessControlTable"; + const char* TAG_DMVERSION = "dmVersion"; +} std::string SoftbusConnector::remoteUdidHash_ = ""; std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; @@ -55,6 +61,7 @@ SoftbusConnector::SoftbusConnector() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) softbusSession_ = std::make_shared(); + hiChainAuthConnector_ = std::make_shared(); #endif LOGD("SoftbusConnector constructor."); } @@ -64,6 +71,108 @@ SoftbusConnector::~SoftbusConnector() LOGD("SoftbusConnector destructor."); } +void SoftbusConnector::SyncAclList(int32_t userId, std::string credId, + int32_t sessionKeyId, int32_t aclId) +{ + LOGI("SyncAclList userId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", + userId, credId.c_str(), sessionKeyId, aclId); + // 根据skid删除sk,删除skid + int32_t ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, sessionKeyId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteSessionKey failed."); + } + // 删除本条acl + DeviceProfileConnector::GetInstance().DeleteAccessControlById(aclId); + if (hiChainAuthConnector_ != nullptr) { + // 根据凭据id 删除sink端多余的凭据 + ret = hiChainAuthConnector_->DeleteCredential(userId, credId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteCredential failed."); + } + } +} + +int32_t SoftbusConnector::SyncLocalAclList5_1_0(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::vector remoteAclList) +{ + std::vector localAclList = + DeviceProfileConnector::GetInstance().GetAclList(localUdid, localUserId, remoteUdid, remoteUserId); + for (auto &localAcl : localAclList) { + bool res = DeviceProfileConnector::GetInstance().ChecksumAcl(localAcl, remoteAclList); + if (res) { + continue; + } + if (localAcl.GetAccesser().GetAccesserDeviceId() == localUdid && + localAcl.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + LOGI("SyncLocalAclListProcess Src."); + SyncAclList(localAcl.GetAccesser().GetAccesserUserId(), + localAcl.GetAccesser().GetAccesserCredentialIdStr(), + localAcl.GetAccesser().GetAccesserSessionKeyId(), localAcl.GetAccessControlId()); + } + if (localAcl.GetAccesser().GetAccesserDeviceId() == remoteUdid && + localAcl.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("SyncLocalAclListProcess Sink."); + SyncAclList(localAcl.GetAccessee().GetAccesseeUserId(), + localAcl.GetAccessee().GetAccesseeCredentialIdStr(), + localAcl.GetAccessee().GetAccesseeSessionKeyId(), localAcl.GetAccessControlId()); + } + } + return DM_OK; +} + +int32_t SoftbusConnector::ParaseAclChecksumList(const std::string &jsonString, std::string &dmVersion, + std::vector &remoteAclList) +{ + JsonObject aclChecksumjson(jsonString); + if (aclChecksumjson.IsDiscarded()) { + LOGE("ParseSyncMessage aclChecksumjson error"); + return ERR_DM_FAILED; + } + if (!aclChecksumjson[TAG_DMVERSION].IsString()) { + LOGE("ParseSyncMessage TAG_DMVERSION error"); + return ERR_DM_FAILED; + } + dmVersion = aclChecksumjson[TAG_DMVERSION].Get(); + if (!aclChecksumjson[TAG_ACL].IsArray()) { + LOGE("ParseSyncMessage TAG_ACL error"); + return ERR_DM_FAILED; + } + aclChecksumjson[TAG_ACL].Get(remoteAclList); + return DM_OK; +} + +int32_t SoftbusConnector::SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) +{ + std::string dmVersion = ""; + std::vector remoteAclListVec; + int32_t ret = ParaseAclChecksumList(remoteAclList, dmVersion, remoteAclListVec); + if (ret != DM_OK) { + LOGE("ParaseAclChecksumList TAG_ACL and dmversion error"); + return ret; + } + int32_t versionNum = 0; + if (!GetVersionNumber(dmVersion, versionNum)) { + LOGE("ParaseAclChecksumList GetVersionNumber error"); + return ERR_DM_FAILED; + } + switch(versionNum) { + case DM_VERSION_5_1_0: + return SyncLocalAclList5_1_0(localUdid, localUserId, remoteUdid, remoteUserId, remoteAclListVec); + default: + LOGE("versionNum is invaild"); + break; + } + return ERR_DM_FAILED; +} + +int32_t SoftbusConnector::GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + return DeviceProfileConnector::GetInstance().GetAclListHashStr(localUdid, + localUserId, remoteUdid, remoteUserId, aclList); +} + int32_t SoftbusConnector::RegisterConnectorCallback(std::shared_ptr callback) { connectorCallback_ = callback; @@ -92,7 +201,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) { std::string connectAddr; LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("addrInfo is nullptr."); return; @@ -102,26 +211,82 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); return; } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, isForceJoin); + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, isForceJoin); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); + } + return; +} + +void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash) +{ + std::string connectAddr; + LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash.c_str(), remoteUdidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); + return; + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); } return; } +void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash) +{ + LOGI("start, JoinLNNBySkId sessionId: %{public}d, udid: %{public}s.", sessionId, GetAnonyString(udid).c_str()); + std::string connectAddr; + auto addrInfo = GetConnectAddr(udid, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + LOGI("addrInfo->type: %{public}d", addrInfo->type); + if (addrInfo->type == CONNECTION_ADDR_BLE) { + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, udidHash.c_str(), + udidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, udidHash: %{public}s.", GetAnonyString(udidHash).c_str()); + return; + } + } + + addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 + if (sessionKeyId > 0 && remoteSessionKeyId > 0) { + addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 + LOGI("sessionKeyId valid"); + } else { + addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNNBySkId failed, ret: %{public}d.", ret); + } +} + void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId) { LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); ConnectionAddr addrInfo; addrInfo.type = CONNECTION_ADDR_SESSION_WITH_KEY; addrInfo.info.session.sessionId = sessionId; + addrInfo.deviceKeyId.hasDeviceKeyId = true; if (sessionKeyId > 0 && remoteSessionKeyId > 0) { - addrInfo.info.session.localDeviceKeyId = sessionKeyId; - addrInfo.info.session.remoteDeviceKeyId = remoteSessionKeyId; + addrInfo.deviceKeyId.localDeviceKeyId = sessionKeyId; + addrInfo.deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; LOGI("sessionKeyId valid"); } else { - addrInfo.info.session.localDeviceKeyId = 0; - addrInfo.info.session.remoteDeviceKeyId = 0; + addrInfo.deviceKeyId.localDeviceKeyId = 0; + addrInfo.deviceKeyId.remoteDeviceKeyId = 0; } int32_t ret = ::JoinLNN(DM_PKG_NAME, &addrInfo, OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { @@ -172,52 +337,59 @@ ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, C return nullptr; } -ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +std::shared_ptr SoftbusConnector::GetDeviceInfoFromMap(const std::string &deviceId) { - DeviceInfo *deviceInfo = nullptr; - { - std::lock_guard lock(discoveryDeviceInfoMutex_); - auto iter = discoveryDeviceInfoMap_.find(deviceId); - if (iter == discoveryDeviceInfoMap_.end()) { - LOGE("deviceInfo not found by deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - return nullptr; - } - deviceInfo = iter->second.get(); + std::lock_guard lock(discoveryDeviceInfoMutex_); + auto iter = discoveryDeviceInfoMap_.find(deviceId); + if (iter == discoveryDeviceInfoMap_.end()) { + LOGE("deviceInfo not found by deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + return nullptr; } - if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { - LOGE("deviceInfo addrNum not valid, addrNum: %{public}d.", deviceInfo->addrNum); + return iter->second; +} + +std::shared_ptr SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +{ + std::shared_ptr deviceInfo = GetDeviceInfoFromMap(deviceId); + if (deviceInfo == nullptr || deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { + LOGE("deviceInfo addrNum not valid, addrNum: %{public}d.", (deviceInfo != nullptr) ? deviceInfo->addrNum : 0); return nullptr; } JsonObject jsonPara; - ConnectionAddr *addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); + std::shared_ptr connectAddrPtr = std::make_shared(); + ConnectionAddr *addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_ETH); if (addr != nullptr) { + *connectAddrPtr = *addr; LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_WLAN); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = SafetyDump(jsonPara); + connectAddr = jsonPara.Dump(); addr->info.ble.priority = BLE_PRIORITY_HIGH; - return addr; + return connectAddrPtr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); return nullptr; @@ -455,7 +627,8 @@ void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) } } -bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +// isHash:传入的deviceId是否为哈希值 +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash) { LOGI("Check the device is online."); int32_t deviceCount = 0; @@ -472,7 +645,8 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) LOGE("[SOFTBUS]GetNodeKeyInfo failed."); } std::string udid = reinterpret_cast(mUdid); - if (udid == targetDeviceId) { + if ((isHash == false && udid == targetDeviceIdHash) || + (isHash == true && Crypto::Sha256(udid).find(targetDeviceIdHash) == 0)) { LOGI("The device is online."); FreeNodeInfo(nodeInfo); return true; @@ -483,6 +657,11 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) return false; } +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return CheckIsOnline(targetDeviceId, false); +} + DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &deviceId) { LOGI("SoftbusConnector::GetDeviceInfoBydeviceId"); diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index d817d153f..c4aea1706 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -33,48 +33,9 @@ std::shared_ptr SoftbusSession::sessionCallback_ = null constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; constexpr int32_t MAX_DATA_LEN = 65535; -static void OnShutdown(int32_t socket, ShutdownReason reason) -{ - LOGI("[SOFTBUS]OnShutdown socket : %{public}d, reason: %{public}d", socket, (int32_t)reason); - SoftbusSession::OnSessionClosed(socket); -} - -static void OnBytes(int32_t socket, const void *data, uint32_t dataLen) -{ - LOGI("[SOFTBUS]OnBytes socket : %{public}d", socket); - SoftbusSession::OnBytesReceived(socket, data, dataLen); -} - -static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) -{ - LOGI("[SOFTBUS]OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}u", socket, (int32_t)eventId, - qosCount); - if (qosCount > QOS_TYPE_BUTT) { - LOGE("OnQos invalid qosCount"); - return; - } - for (uint32_t idx = 0; idx < qosCount; idx++) { - LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); - } -} - SoftbusSession::SoftbusSession() { LOGD("SoftbusSession constructor."); - if (memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)) != DM_OK) { - LOGE("SoftbusSession::SoftbusSession memset_s failed."); - return; - } - - iSocketListener_.OnShutdown = OnShutdown; - iSocketListener_.OnBytes = OnBytes; - iSocketListener_.OnQos = OnQos; - iSocketListener_.OnFile = nullptr; - iSocketListener_.OnMessage = nullptr; - iSocketListener_.OnBind = nullptr; - iSocketListener_.OnStream = nullptr; - iSocketListener_.OnError = nullptr; - iSocketListener_.OnNegotiate = nullptr; } SoftbusSession::~SoftbusSession() @@ -99,12 +60,12 @@ int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) DmTraceStart(std::string(DM_HITRACE_AUTH_TO_OPPEN_SESSION)); int32_t sessionId = -1; std::string connectAddr; - ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); + auto addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("[SOFTBUS]addrInfo is nullptr. sessionId: %{public}d.", sessionId); return sessionId; } - sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo, 1, nullptr); + sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo.get(), 1, nullptr); if (sessionId < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId); return sessionId; @@ -161,20 +122,6 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("extrasJson error, message: %{public}s.", GetAnonyString(message).c_str()); - return ERR_DM_FAILED; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("SoftbusSession::SendData err json string."); - return ERR_DM_FAILED; - } - int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); - LOGI("start, msgType: %{public}d.", msgType); - if (sessionCallback_->GetIsCryptoSupport()) { - LOGI("SendData Start encryption."); - } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed."); @@ -195,9 +142,13 @@ int32_t SoftbusSession::SendHeartbeatData(int32_t sessionId, std::string &messag int SoftbusSession::OnSessionOpened(int sessionId, int result) { + LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); + if (sessionCallback_ == nullptr) { + LOGD("Session callback is not registered."); + return DM_OK; + } int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); - LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); return DM_OK; } @@ -206,36 +157,7 @@ void SoftbusSession::OnSessionClosed(int sessionId) LOGI("OnSessionClosed, sessionId: %{public}d.", sessionId); CHECK_NULL_VOID(sessionCallback_); sessionCallback_->OnSessionClosed(sessionId); -} - -void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) -{ - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { - LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, - dataLen); - return; - } - LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - if (sessionCallback_->GetIsCryptoSupport()) { - LOGI("Start decryption."); - } - std::string message = std::string(reinterpret_cast(data), dataLen); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DecodeRequestAuth jsonStr error"); - return; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("err json string, first time"); - return; - } - if (jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_REQ_NEGOTIATE || - jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_RESP_NEGOTIATE) { - sessionCallback_->OnAuthDeviceDataReceived(sessionId, message); - } else { - sessionCallback_->OnDataReceived(sessionId, message); - } - LOGI("completed."); + return; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 6772f2ae0..02f43f706 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -15,9 +15,13 @@ #include "device_manager_service_impl.h" +#include +#include +#include #include #include "app_manager.h" +#include "dm_error_type.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -29,25 +33,378 @@ #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" +#include "dm_random.h" #include "common_event_support.h" using namespace OHOS::EventFwk; #endif namespace OHOS { namespace DistributedHardware { + +namespace { + // One year 365 * 24 * 60 * 60 constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +// New protocol field definition. To avoid dependency on the new protocol header file, +// do not directly depend on the new protocol header file. +constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; +constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; +constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; +constexpr int32_t AUTH_SRC_FINISH_STATE = 12; +constexpr int32_t MAX_DATA_LEN = 65535; +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; +constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; +constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; +constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; +// currently, we just support one bind session in one device at same time +constexpr size_t MAX_NEW_PROC_SESSION_COUNT_TEMP = 1; + +static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) +{ + std::string dmVersion = ""; + std::string edition = ""; + if (jsonObject[TAG_DMVERSION].IsString()) { + dmVersion = jsonObject[TAG_DMVERSION].Get(); + } + if (jsonObject[TAG_EDITION].IsString()) { + edition = jsonObject[TAG_EDITION].Get(); + } + dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + + // Assign the physical session version and release the semaphore. + session->version_ = dmVersion; + + // If the version number is higher than 5.0.4 (the highest version of the old protocol), + // there is no need to switch to the old protocol. + if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { + return false; + } + + return true; +} + +std::string CreateTerminateMessage(void) +{ + JsonObject jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; + jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + jsonObject[TAG_AUTH_FINISH] = false; + + return jsonObject.Dump(); +} + +} + +std::condition_variable DeviceManagerServiceImpl::cleanEventCv_; +std::mutex DeviceManagerServiceImpl::cleanEventMutex_; +std::queue DeviceManagerServiceImpl::cleanEventQueue_; + +Session::Session(int sessionId, std::string deviceId) +{ + sessionId_ = sessionId; + deviceId_ = deviceId; +} DeviceManagerServiceImpl::DeviceManagerServiceImpl() { + running_ = true; + thread_ = std::thread(&DeviceManagerServiceImpl::CleanWorker, this); LOGI("DeviceManagerServiceImpl constructor"); } DeviceManagerServiceImpl::~DeviceManagerServiceImpl() { + Stop(); + thread_.join(); LOGI("DeviceManagerServiceImpl destructor"); } +static uint64_t StringToUint64(const std::string& str) +{ + // Calculate the length of the substring, taking the minimum of the string length and 8 + size_t subStrLength = std::min(str.length(), static_cast(8U)); + + // Extract substring + std::string substr = str.substr(str.length() - subStrLength); + + // Convert substring to uint64_t + uint64_t result = 0; + for (size_t i = 0; i < subStrLength; ++i) { + result <<= 8; // Shift left 8 bits + result |= static_cast(substr[i]); + } + + return result; +} + + +static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, std::string &bundleName) +{ + uint64_t tokenId = 0; + if (isSrcSide) { + // src end + tokenId = IPCSkeleton::GetCallingTokenID(); + } else { + // sink end + int64_t tmpTokenId; + // get userId + int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId); + if (targetUserId == -1) { + return tokenId; + } + if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else { + // get deviceId, take the 8 character value as tokenId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = std::string(localDeviceId); + if (deviceId.length() != 0) { + tokenId = StringToUint64(deviceId); + } + } + } + return tokenId; +} + +uint64_t DeviceManagerServiceImpl::FetchCleanEvent() +{ + std::unique_lock lock(cleanEventMutex_); + cleanEventCv_.wait(lock, [&] { + return !running_.load() || !cleanEventQueue_.empty(); + }); + + if (!running_.load()) return 0; + + uint64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + return logicalSessionId; +} + +void DeviceManagerServiceImpl::CleanWorker() +{ + while (running_.load()) { + auto logicalSessionId = FetchCleanEvent(); + LOGI("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}" PRIu64 "", + logicalSessionId); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + LOGI("DeviceManagerServiceImpl::CleanWorker end"); +} + +void DeviceManagerServiceImpl::Stop() +{ + running_.store(false); + cleanEventCv_.notify_all(); + std::lock_guard lock(cleanEventMutex_); + while (!cleanEventQueue_.empty()) { + uint64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } +} + +void DeviceManagerServiceImpl::NotifyCleanEvent(uint64_t logicalSessionId) +{ + LOGI("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}" PRIu64 ".", logicalSessionId); + std::lock_guard lock(cleanEventMutex_); + // Store into the queue + cleanEventQueue_.push(logicalSessionId); + cleanEventCv_.notify_one(); +} + +void DeviceManagerServiceImpl::ImportConfig(std::shared_ptr authMgr, uint64_t tokenId) +{ + // Import configuration + if (configsMap_.find(tokenId) != configsMap_.end()) { + authMgr->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); + authMgr->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); + LOGI("DeviceManagerServiceImpl::ImportConfig import authCode Successful."); + } + return; +} + +int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, + std::shared_ptr session, uint64_t logicalSessionId) +{ + if (session == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + // If version is empty, allow creation for the first time, create a new protocol auth_mgr to negotiate version; + // subsequent creations wait, and directly use version to create the corresponding auth_mgr after release. + if (session->version_ == "") { + bool expected = false; + if (session->flag_.compare_exchange_strong(expected, true)) { + LOGI("The physical link is being created and the dual-end device version is aligned."); + } else { + // Do not allow simultaneous version negotiation, return error directly + LOGE("Version negotiation is not allowed at the same time."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + } + + std::lock_guard lock(authMgrMtx_); + if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { + if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) { + if (authMgrMap_.size() > MAX_NEW_PROC_SESSION_COUNT_TEMP) { + LOGE("Other bind session exist, can not start new one."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + // Create a new auth_mgr, create authMgrMap_[tokenId] + if (isSrcSide) { + // src end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + } else { + // sink end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + } + // Register resource destruction notification function + authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); + LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}" PRId64 ".", tokenId); + ImportConfig(authMgrMap_[tokenId], tokenId); + return DM_OK; + } else { + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr old authMgr."); + if (authMgr_ == nullptr) { + CreateGlobalClassicalAuthMgr(); + } + authMgr_->PrepareSoftbusSessionCallback(); + authMgrMap_[tokenId] = authMgr_; + ImportConfig(authMgr_, tokenId); + // The value of logicalSessionId in the old protocol is always 0. + logicalSessionId2TokenIdMap_[0] = tokenId; + return DM_OK; + } + } + // authMgr_ has been created, indicating that a binding event already exists. + // Other requests are rejected, and an error code is returned. + LOGE("BindTarget failed, this device is being bound. Please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; +} + +void DeviceManagerServiceImpl::CleanSessionMap(int sessionId, std::shared_ptr session) +{ + session->logicalSessionCnt_.fetch_sub(1); + if (session->logicalSessionCnt_.load(std::memory_order_relaxed) == 0) { + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + } + return; +} + +void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId) +{ + if (logicalSessionId2SessionIdMap_.find(logicalSessionId) != logicalSessionId2SessionIdMap_.end()) { + auto sessionId = logicalSessionId2SessionIdMap_[logicalSessionId]; + auto session = GetCurSession(sessionId); + if (session != nullptr) { + CleanSessionMap(sessionId, session); + } + logicalSessionId2SessionIdMap_.erase(logicalSessionId); + } + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + return; +} + +void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId) +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } else { + LOGE("logicalSessionId(%{public}" PRIu64 ") can not find the tokenId.", logicalSessionId); + return; + } + + if (configsMap_.find(tokenId) != configsMap_.end()) { + configsMap_[tokenId] = nullptr; + configsMap_.erase(tokenId); + } + + CleanSessionMapByLogicalSessionId(logicalSessionId); + if (logicalSessionId == 0) { + authMgr_->SetTransferReady(true); + authMgr_->ClearSoftbusSessionCallback(); + } + + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + authMgrMap_[tokenId] = nullptr; + authMgrMap_.erase(tokenId); + } + return; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + return nullptr; +} + +// Needed in the callback function +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) +{ + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + return nullptr; +} + +std::shared_ptr DeviceManagerServiceImpl::GetCurrentAuthMgr() +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(0) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[0]; + } + for (auto &pair : authMgrMap_) { + if (pair.first != tokenId) { + return pair.second; + } + } + return authMgr_; +} + +static uint64_t GenerateRandNum(int sessionId) +{ + // Get the current timestamp + auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now(). + time_since_epoch()).count(); + + // Generate random numbers + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> rand_dis(1, 0xFFFFFFFF); + uint32_t randomNumber = rand_dis(gen); + + // Combination of random numbers + uint64_t randNum = (static_cast(timestamp) << 32) | + (static_cast(sessionId) << 16) | + static_cast(randomNumber); + + return randNum; +} + int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) { LOGI("DeviceManagerServiceImpl Initialize"); @@ -68,14 +425,6 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptrRegisterSoftbusStateCallback(); } - if (authMgr_ == nullptr) { - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener, - hiChainAuthConnector_); - softbusConnector_->RegisterConnectorCallback(authMgr_); - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - } if (credentialMgr_ == nullptr) { credentialMgr_ = std::make_shared(hiChainConnector_, listener); } @@ -84,6 +433,10 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptrClearSoftbusSessionCallback(); + } LOGI("Init success, singleton initialized"); return DM_OK; } @@ -95,9 +448,28 @@ void DeviceManagerServiceImpl::Release() commonEventManager_ = nullptr; #endif softbusConnector_->UnRegisterConnectorCallback(); + softbusConnector_->UnRegisterSoftbusStateCallback(); softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); authMgr_ = nullptr; + for (auto& pair : authMgrMap_) { + pair.second = nullptr; + } + authMgrMap_.clear(); + for (auto& pair : sessionsMap_) { + pair.second = nullptr; + } + sessionsMap_.clear(); + for (auto& pair : configsMap_) { + pair.second = nullptr; + } + configsMap_.clear(); + deviceId2SessionIdMap_.clear(); + deviceIdMutexMap_.clear(); + sessionEnableMutexMap_.clear(); + sessionEnableCvMap_.clear(); + logicalSessionId2TokenIdMap_.clear(); + logicalSessionId2SessionIdMap_.clear(); deviceStateMgr_ = nullptr; softbusConnector_ = nullptr; abilityMgr_ = nullptr; @@ -114,7 +486,16 @@ int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgNam pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr, invoke the old protocal."); + if (authMgr_ == nullptr) { + LOGE("classical authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); + } + return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel); } int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) @@ -123,7 +504,12 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->StopAuthenticateDevice(pkgName); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->StopAuthenticateDevice(pkgName); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -135,7 +521,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const return ERR_DM_INPUT_PARA_INVALID; } std::string extra = ""; - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -146,7 +534,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, @@ -157,12 +547,26 @@ int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t "%{public}s", pkgName.c_str(), params.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ != nullptr) { - authMgr_->OnUserOperation(action, params); + auto authMgr = GetCurrentAuthMgr(); + if (authMgr != nullptr) { + authMgr->OnUserOperation(action, params); } return DM_OK; } +void DeviceManagerServiceImpl::CreateGlobalClassicalAuthMgr() +{ + LOGI("global classical authMgr_ not exit, create one"); + // Create old auth_mar, only create an independent one + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + authMgr_->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + softbusConnector_->RegisterConnectorCallback(authMgr_); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); +} + void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo) { LOGI("DeviceManagerServiceImpl::HandleOffline"); @@ -194,13 +598,13 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; processInfo.userId = item.first; softbusConnector_->SetProcessInfo(processInfo); - } else if (static_cast(item.second) == DEVICE) { + } else if (static_cast(item.second) == USER) { LOGI("The offline device is device bind type."); devInfo.authForm = DmAuthForm::PEER_TO_PEER; processInfo.userId = item.first; softbusConnector_->SetProcessInfo(processInfo); } else if (static_cast(item.second) == SERVICE || static_cast(item.second) == APP) { - LOGI("The offline device is APP_PEER_TO_PEER_TYPE bind type."); + LOGI("The offline device is PEER_TO_PEER_TYPE bind type, %{public}" PRIu32, item.second); std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, item.first); @@ -228,7 +632,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - LOGI("The online device bind type is %{public}d.", bindType); + LOGI("The online device bind type is %{public}" PRIu32, bindType); ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); @@ -241,13 +645,13 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; softbusConnector_->SetProcessInfo(processInfo); - } else if (bindType == APP_PEER_TO_PEER_TYPE) { + } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == SERVICE_PEER_TO_PEER_TYPE) { std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, MultipleUserConnector::GetFirstForegroundUserId()); softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; - } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { + } else if (bindType == APP_ACROSS_ACCOUNT_TYPE || bindType == SERVICE_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, MultipleUserConnector::GetFirstForegroundUserId()); @@ -301,6 +705,10 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { + { + std::lock_guard lock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].notify_all(); + } std::string peerUdid = ""; softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); struct RadarInfo info = { @@ -313,6 +721,15 @@ int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { LOGE("ReportAuthSessionOpenCb failed"); } + + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) == sessionsMap_.end()) { + sessionsMap_[sessionId] = std::make_shared(sessionId, peerUdid); + } + } + return SoftbusSession::OnSessionOpened(sessionId, result); } @@ -321,9 +738,241 @@ void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) SoftbusSession::OnSessionClosed(sessionId); } +static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen) +{ + std::string message = std::string(reinterpret_cast(data), dataLen); + return JsonObject(message); +} + +// When downgrading the version, determine whether it is src or sink based on the message. +// src: Received 90 message. +// sink: Received 80 message. +static bool IsAuthManagerSourceByMessage(int32_t msgType) +{ + return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; +} + +// Get the current session object +std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) +{ + std::shared_ptr curSession = nullptr; + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + curSession = sessionsMap_[sessionId]; + } else { + LOGE("OnBytesReceived, The local session cannot be found."); + } + } + return curSession; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType, + uint64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession) +{ + uint64_t tokenId = 0; + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + if (logicalSessionId != 0) { + curSession->logicalSessionSet_.insert(logicalSessionId); + std::string bundleName; + int32_t displayId = 0; + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } + if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); + } + tokenId = GetTokenId(false, displayId, bundleName); + if (tokenId == 0) { + LOGE("GetAuthMgrByMessage, Get tokenId failed."); + return nullptr; + } + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + LOGE("GetAuthMgrByMessage, logicalSessionId exists in logicalSessionId2TokenIdMap_."); + return nullptr; + } + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + } + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + return nullptr; + } + } else { + if (logicalSessionId != 0) { + if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { + LOGE("GetAuthMgrByMessage, The logical session ID does not exist in the physical session."); + return nullptr; + } + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + + return GetAuthMgrByTokenId(tokenId); +} + +int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr curSession) +{ + // New Old Receive 90, destroy new authMgr, create old authMgr, source side + // The old protocol has only one session, reverse lookup logicalSessionId and tokenId + int sessionId = curSession->sessionId_; + uint64_t logicalSessionId = 0; + uint64_t tokenId = 0; + for (auto& pair : logicalSessionId2SessionIdMap_) { + if (pair.second == sessionId) { + logicalSessionId = pair.first; + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + if (logicalSessionId == 0 || tokenId == 0) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr can not find logicalSessionId and tokenId."); + return ERR_DM_AUTH_FAILED; + } + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + auto authMgr = GetAuthMgrByTokenId(tokenId); + authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); + int32_t authType = -1; + authMgr->ParseAuthType(bindParam, authType); + authMgrMap_.erase(tokenId); + if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId) != DM_OK) { + return ERR_DM_AUTH_FAILED; + } + + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + authMgr_->EnableInsensibleSwitching(); + curSession->logicalSessionSet_.insert(0); + curSession->logicalSessionCnt_.fetch_add(1); + authMgr->OnSessionDisable(); + } else { + authMgr_->DisableInsensibleSwitching(); + // send stop message + // Cannot stop using the new protocol. The new protocol is a signal mechanism and cannot be stopped serially. + // There will be a delay, causing new objects to be created before the stop is complete. + // Then the timeout mechanism of the new protocol will stop SoftBus again. + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + // Close new protocol session + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + authMgr = nullptr; + + if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed"); + return ERR_DM_AUTH_FAILED; + } + + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + int32_t sessionSide = GetSessionSide(curSession->sessionId_); + authMgr_->OnSessionOpened(curSession->sessionId_, sessionSide, 0); + } + + LOGI("DeviceManagerServiceImpl::TransferSrcOldAuthMgr src transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + // Old New Received 80, New Old authMgr, Sink End + std::string bundleName; + if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); + } else if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } else { + LOGE("DeviceManagerServiceImpl::TransferSinkOldAuthMgr can not find bundleName."); + return ERR_DM_AUTH_FAILED; + } + uint64_t tokenId = GetTokenId(false, -1, bundleName); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, 0) != DM_OK) { + // Internal error log printing completed + return ERR_DM_AUTH_FAILED; + } + + // Parameter 2 sessionSide is 0, authMgr_ is empty, it must be the sink end. + // The src end will create the protocol object when BindTarget. + authMgr_->OnSessionOpened(curSession->sessionId_, 0, 0); + LOGI("DeviceManagerServiceImpl::TransferSinkOldAuthMgr sink transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + int ret = DM_OK; + if ((authMgr_ == nullptr || authMgr_->IsTransferReady()) && + (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { + if (IsMessageOldVersion(jsonObject, curSession)) { + if (IsAuthManagerSourceByMessage(msgType)) { + ret = TransferSrcOldAuthMgr(curSession); + } else { + ret = TransferSinkOldAuthMgr(jsonObject, curSession); + } + } + } + + return ret; +} + + void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - SoftbusSession::OnBytesReceived(sessionId, data, dataLen); + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { + LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", + sessionId, dataLen); + return; + } + + LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); + + JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("OnBytesReceived, MSG_TYPE parse failed."); + return; + } + int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); + uint64_t logicalSessionId = 0; + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + } + + std::shared_ptr curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + + std::shared_ptr authMgr = nullptr; + if (logicalSessionId != 0) { + authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession); + if (authMgr == nullptr) { + return; + } + } else { + /** +        Monitor old messages on ports 80/90 +        1. New-to-old: When the src side receives a 90 message and detects a version mismatch, it receives + the 90 message, destroys the current new authMgr, creates a new old protocol authMgr, and re-BindTarget. +        2. Old-to-new: When the sink side receives an 80 message and detects a version mismatch, it receives the 80 + message, directly creates a new old protocol authMgr, and re-OnSessionOpened and OnBytesReceived. +        */ + if (TransferOldAuthMgr(msgType, jsonObject, curSession) != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed"); + return; + } + authMgr = authMgr_; + } + + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } + return; } int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) @@ -458,11 +1107,12 @@ int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkg LOGE("RegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { - LOGE("authMgr_ is nullptr"); + auto authMgr = GetCurrentAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->RegisterUiStateCallback(pkgName); + return authMgr->RegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) @@ -471,11 +1121,12 @@ int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &p LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { - LOGE("authMgr_ is nullptr"); + auto authMgr = GetCurrentAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->UnRegisterUiStateCallback(pkgName); + return authMgr->UnRegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject) @@ -565,6 +1216,15 @@ int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, return DM_OK; } +std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (configsMap_.find(tokenId) == configsMap_.end()) { + configsMap_[tokenId] = std::make_shared(); + } + return configsMap_[tokenId]; +} + int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode) { if (pkgName.empty() || authCode.empty()) { @@ -572,25 +1232,294 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->ImportAuthCode(pkgName, authCode); + LOGI("DeviceManagerServiceImpl::ImportAuthCode pkgName is %{public}s, authCode is %{public}s", + pkgName.c_str(), authCode.c_str()); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->pkgName = pkgName; + config->authCode = authCode; // If registered multiple times, only the last one is kept + return DM_OK; + } + + return authMgr->ImportAuthCode(pkgName, authCode); } int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) { - int32_t ret = authMgr_->GeneratePincode(); + int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); authCode = std::to_string(ret); LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); return DM_OK; } +static JsonObject GetExtraJsonObject(const std::map &bindParam) +{ + std::string extra; + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + extra = iter->second; + } else { + extra = ConvertMapToJsonString(bindParam); + } + + return JsonObject(extra); +} + +static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId) +{ + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", hmlEnable160M); + } + if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { + LOGE("PARAM_KEY_HML_ACTIONID is not string"); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (!IsNumberString(actionIdStr)) { + LOGE("PARAM_KEY_HML_ACTIONID is not number"); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t actionId = std::atoi(actionIdStr.c_str()); + if (actionId <= 0) { + LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); + return ERR_DM_INPUT_PARA_INVALID; + } + hmlActionId = actionId; + return DM_OK; +} + +static bool IsHmlSessionType(const JsonObject &jsonObject) +{ + std::string connSessionType; + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", connSessionType.c_str()); + } + return connSessionType == CONN_SESSION_TYPE_HML; +} + +int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId, + const std::map &bindParam) +{ + bool hmlEnable160M = false; + int32_t hmlActionId = 0; + JsonObject jsonObject = GetExtraJsonObject(bindParam); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return -1; + } + if (IsHmlSessionType(jsonObject)) { + auto ret = GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId); + if (ret != DM_OK) { + LOGE("OpenAuthSession failed, GetHmlInfo failed."); + return ret; + } + LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); + return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + hmlActionId, hmlEnable160M); + } else { + return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } +} + +std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam) +{ + std::shared_ptr instance; + int sessionId = -1; + // Acquire global lock to ensure thread safety for maps + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + } + + // Get the lock corresponding to deviceId + std::mutex& device_mutex = deviceIdMutexMap_[deviceId]; + std::lock_guard lock(device_mutex); + + // Check again whether the corresponding object already exists (because other threads may have created it during + // the lock acquisition in the previous step) + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + + sessionId = OpenAuthSession(deviceId, bindParam); + if (sessionId < 0) { + goto error; + } + + std::unique_lock cvLock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].wait(cvLock); + + instance = std::make_shared(sessionId, deviceId); + deviceId2SessionIdMap_[deviceId] = sessionId; + sessionsMap_[sessionId] = instance; + } + return instance; +error: + LOGE("OpenAuthSession failed, stop the authentication"); + return nullptr; +} + +int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, + std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index) +{ + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) { + LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { + LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { + LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +bool DeviceManagerServiceImpl::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId) +{ + std::string extraInfo = DeviceProfileConnector::GetInstance().IsAuthNewVersion( + bindLevel, localUdid, remoteUdid, tokenId, userId); + JsonObject extraInfoJson(extraInfo); + if (extraInfoJson.IsDiscarded()) { + LOGE("IsAuthNewVersion extraInfoJson error"); + return false; + } + if (!extraInfoJson[TAG_DMVERSION].IsString()) { + LOGE("IsAuthNewVersion PARAM_KEY_OS_VERSION error"); + return false; + } + std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get(); + if (CompareVersion(dmVersion, std::string(DM_VERSION_5_1_0)) || dmVersion == std::string(DM_VERSION_5_1_0)) { + return true; + } + return false; +} + +int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam) +{ + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + + std::shared_ptr deviceInfo = std::make_shared(); + int32_t index = 0; + int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index); + if (ret != DM_OK) { + LOGE("GetDeviceInfo failed, ret: %{public}d", ret); + } + deviceInfo->addrNum = static_cast(index); + if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { + int32_t ret = DM_OK; if (pkgName.empty()) { - LOGE("BindTarget failed, pkgName is empty"); + LOGE("BindTarget failed, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->BindTarget(pkgName, targetId, bindParam); + + std::string deviceId = ""; + PeerTargetId targetIdTmp = const_cast(targetId); + ret = ParseConnectAddr(targetId, deviceId, bindParam); + if (ret == DM_OK) { + targetIdTmp.deviceId = deviceId; + } else { + if (targetId.deviceId.empty()) { + LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + } + // Created only at the source end. The same target device will not be created repeatedly with the new protocol. + std::shared_ptr curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam); + if (curSession == nullptr) { + LOGE("Failed to create the session. Target deviceId: %{public}s.", targetIdTmp.deviceId.c_str()); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + + // Logical session random number + int sessionId = curSession->sessionId_; + uint64_t logicalSessionId = GenerateRandNum(sessionId); + if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { + LOGE("Failed to create the logical session."); + return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + } + + // Create on the src end. + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); + if (ret != DM_OK) { + return ret; + } + curSession->logicalSessionSet_.insert(logicalSessionId); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + authMgr->SetBindTargetParams(targetId); + return authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId); } int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) @@ -665,32 +1594,18 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local softbusConnector_->SetProcessInfo(processInfo); CHECK_NULL_VOID(deviceStateMgr_); deviceStateMgr_->OnDeviceOffline(peerUdid); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(localUserId); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(peerUdid, localUserId, peerUserId); } } -void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) { LOGI("PreUserId %{public}d.", preUserId); char localDeviceId[DEVICE_UUID_LENGTH]; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = reinterpret_cast(localDeviceId); - std::multimap peerUserIdMap; // key: peerUdid value: peerUserId - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId, peerUdids, peerUserIdMap); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId); CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteAllGroup(preUserId); - - if (peerUserIdMap.empty()) { - LOGE("peerUserIdMap is empty"); - return; - } - CHECK_NULL_VOID(hiChainAuthConnector_); - for (const auto &item : peerUserIdMap) { - hiChainAuthConnector_->DeleteCredential(item.first, preUserId, item.second); - } } void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) @@ -701,13 +1616,11 @@ void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std if (localUserIds.empty()) { return; } - CHECK_NULL_VOID(hiChainAuthConnector_); + CHECK_NULL_VOID(hiChainConnector_); std::vector> delInfoVec; for (int32_t localUserId : localUserIds) { delInfoVec.push_back(std::pair(localUserId, remoteUdid)); - hiChainAuthConnector_->DeleteCredential(remoteUdid, localUserId, userId); } - CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds); } @@ -720,18 +1633,21 @@ void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, deviceVec, currentUserId, beforeUserId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(beforeUserId); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); - if (authMgr_ != nullptr) { - authMgr_->OnScreenLocked(); - return; - } else { - LOGE("authMgr_ is null, cannot call OnScreenLocked."); + for (auto& pair : authMgrMap_) { + if (pair.second != nullptr) { + LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}" PRId64 ".", pair.first); + pair.second->OnScreenLocked(); + } } + return; } LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback error."); } @@ -763,8 +1679,9 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) LOGE("HandleDeviceNotTrust udid is empty."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->HandleDeviceNotTrust(udid); + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroupByUdid(udid); } int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, @@ -816,10 +1733,6 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co softbusConnector_->SetProcessInfo(processInfo); CHECK_NULL_VOID(deviceStateMgr_); deviceStateMgr_->OnDeviceOffline(remoteUdid); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(item.second); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId); } } } @@ -840,42 +1753,69 @@ DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) return authForm; } +int32_t DeviceManagerServiceImpl::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceManagerServiceImpl::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + for (const auto &item : groupList) { + std::string groupId = item.groupId; + hiChainConnector_->DeleteGroup(groupId); + } + return DM_OK; +} + void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) { char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); - if (static_cast(bindType) == DM_INVALIED_BINDTYPE) { + DmOfflineParam offlineParam; + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent( + remoteUserId, remoteUdid, localUdid, offlineParam); + if (static_cast(bindType) == DM_INVALIED_TYPE) { LOGE("Invalied bindtype."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + DeleteGroup(DM_PKG_NAME, remoteUdid); + DeleteSkIdAndCredId(offlineParam, userId); } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId) { + LOGI("HandleAppUnBindEvent tokenId = %{public}d.", tokenId); char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + if (offlineParam.leftAclNumber != 0) { - LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); + DeleteSkIdAndCredId(offlineParam, userId); return; } if (offlineParam.leftAclNumber == 0) { - LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); + if (!offlineParam.isLnnAcl) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } else { + DeleteSkIdAndCredId(offlineParam, userId); + } return; } } @@ -887,27 +1827,55 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, - tokenId, localUdid, peerTokenId); + tokenId, localUdid, peerTokenId); + if (offlineParam.leftAclNumber != 0) { - LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); + DeleteSkIdAndCredId(offlineParam, userId); return; } if (offlineParam.leftAclNumber == 0) { - LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); + if (!offlineParam.isLnnAcl) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } else { + DeleteSkIdAndCredId(offlineParam, userId); + } return; } } +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) +{ + LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", + remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t localUserId = MultipleUserConnector::GetCurrentAccountUserID(); + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent( + userId, remoteUdid, localUdid, remoteTokenId); + + CHECK_NULL_VOID(softbusConnector_); + if (offlineParam.isLnnAcl) { + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + } else { + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + } + DeleteSkIdAndCredId(offlineParam, localUserId); +} + void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus) { @@ -973,6 +1941,22 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } +int32_t DeviceManagerServiceImpl::SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) +{ + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + return softbusConnector_->SyncLocalAclListProcess(localUdid, localUserId, remoteUdid, + remoteUserId, remoteAclList); +} + +int32_t DeviceManagerServiceImpl::GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + return softbusConnector_->GetAclListHash(localUdid, + localUserId, remoteUdid, remoteUserId, aclList); +} + void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { @@ -998,7 +1982,7 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i } DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), item.GetAccessee().GetAccesseeDeviceId())); @@ -1044,8 +2028,18 @@ void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::s int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType) { - CHECK_NULL_RETURN(authMgr_, ERR_DM_POINT_NULL); - return authMgr_->RegisterAuthenticationType(authenticationType); + if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && + authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("Invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->authenticationType = authenticationType; // only the last registration is retained + return DM_OK; + } + return authMgr->RegisterAuthenticationType(authenticationType); } void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() @@ -1054,34 +2048,21 @@ void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() std::vector profiles = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); std::string remoteUdid = ""; - int32_t remoteUserId = -1; int64_t currentTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localDeviceId); for (auto &item : profiles) { if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { continue; } if ((currentTime - item.GetLastAuthTime()) > MAX_ALWAYS_ALLOW_SECONDS && item.GetLastAuthTime() > 0) { DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); - if (item.GetAccesser().GetAccesserUserId() == currentUserId && - item.GetAccesser().GetAccesserDeviceId() == localUdid) { - remoteUserId = item.GetAccessee().GetAccesseeUserId(); - } - if (item.GetAccessee().GetAccesseeUserId() == currentUserId && - item.GetAccessee().GetAccesseeDeviceId() == localUdid) { - remoteUserId = item.GetAccesser().GetAccesserUserId(); - } remoteUdid = item.GetTrustDeviceId(); - CheckDeleteCredential(remoteUdid, remoteUserId); + CheckDeleteCredential(remoteUdid); } } } -void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) +void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid) { std::vector profiles = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); @@ -1093,8 +2074,7 @@ void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUd } if (!leftAcl) { LOGI("CheckDeleteCredential delete credential"); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); } } @@ -1109,6 +2089,120 @@ int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &l return DM_OK; } +int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + if (static_cast(bindLevel) == USER) { + DeleteGroup(pkgName, remoteUdid); + } + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); + return ERR_DM_FAILED; + } + if (static_cast(bindLevel) == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DeviceManagerServiceImpl::DeleteSkIdAndCredId(DmOfflineParam offlineParam, int32_t userId) +{ + LOGI("DeleteSkIdAndCredId start."); + int32_t ret = DM_OK; + for (auto skId : offlineParam.skIdVec) { + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId); + if (ret != DM_OK) { + LOGE("Delete Session Key err, userId: %{public}d, skId: %{public}d, ret: %{public}d", userId, skId, ret); + } + } + for (auto credId : offlineParam.credIdVec) { + ret = hiChainAuthConnector_->DeleteCredential(userId, credId); + if (ret != DM_OK) { + LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", userId, credId.c_str(), ret); + } + } + return ret; +} + +int32_t DeviceManagerServiceImpl::DeleteProcAcl(uint32_t tokenId, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra, int32_t userId) +{ + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().DeleteAccessControlListV2( + tokenId, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); + return ERR_DM_FAILED; + } + if (static_cast(bindLevel) == APP || static_cast(bindLevel) == SERVICE) { + if (offlineParam.leftAclNumber != 0) { + LOGI("The tokenId unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + DeleteSkIdAndCredId(offlineParam, userId); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0 && offlineParam.isLnnAcl) { + LOGI("The tokenId unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + DeleteSkIdAndCredId(offlineParam, userId); + return DM_OK; + } + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + DeleteSkIdAndCredId(offlineParam, userId); + return DM_OK; + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0 && offlineParam.isLnnAcl) { + LOGI("Unbind deivce-level, retain null."); + DeleteSkIdAndCredId(offlineParam, userId); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DeviceManagerServiceImpl::DeleteAclV2(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAclV2 pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + uint32_t tokenId = 0; + MultipleUserConnector::GetTokenId(tokenId); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + bool isNewVersion = IsAuthNewVersion(bindLevel, localUdid, remoteUdid, tokenId, userId); + if (!isNewVersion) { + return DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel, extra); + } + return DeleteProcAcl(tokenId, localUdid, remoteUdid, bindLevel, extra, userId); +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 516b29bda..7cabe0aa3 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -499,9 +499,8 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local return; } -void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) { - (void)peerUdids; (void)preUserId; return; } @@ -527,6 +526,28 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } +int32_t DeviceManagerServiceImpl::SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) +{ + (void)localUdid; + (void)localUserId; + (void)remoteUdid; + (void)remoteUserId; + (void)remoteAclList; + return 0; +} + +int32_t DeviceManagerServiceImpl::GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + (void)localUdid; + (void)localUserId; + (void)remoteUdid; + (void)remoteUserId; + (void)aclList; + return 0; +} + void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { @@ -600,10 +621,9 @@ void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() return; } -void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) +void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid) { (void)remoteUdid; - (void)remoteUserId; return; } @@ -615,6 +635,15 @@ int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &l return DM_OK; } +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) +{ + (void)userId; + (void)remoteUdid; + (void)remoteTokenId; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index d88646d7c..736c75c9d 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -306,11 +306,10 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) hiChainConnector_->DeleteTimeOutGroup((idIter->second).c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) DeleteGroupByDP(idIter->second); - int32_t peerUserId = -1; - uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second, peerUserId); + uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second); if (res == 0) { hiChainAuthConnector_->DeleteCredential(idIter->second, - MultipleUserConnector::GetCurrentAccountUserID(), peerUserId); + MultipleUserConnector::GetCurrentAccountUserID()); } #endif stateTimerInfoMap_.erase(iter); diff --git a/services/implementation/src/i18n/dm_language_manager.cpp b/services/implementation/src/i18n/dm_language_manager.cpp index 77f080ee5..316fb1721 100644 --- a/services/implementation/src/i18n/dm_language_manager.cpp +++ b/services/implementation/src/i18n/dm_language_manager.cpp @@ -144,5 +144,55 @@ std::string DmLanguageManager::GetTextBySystemLocale(const cJSON *const textObj, } return ""; } + +std::string DmLanguageManager::GetSystemLanguage() +{ + std::string language = GetSystemParam(SYSTEM_LANGUAGE_KEY); + if (!language.empty()) { + return language; + } + + language = GetSystemParam(SYSTEM_LANGUAGE_LOCALE_KEY); + if (!language.empty()) { + return language; + } + + return DEFAULT_LANGUAGE; +} + +std::string DmLanguageManager::GetTextByLanguage(const std::string &text, const std::string &language) +{ + if (text.empty()) { + return ""; + } + cJSON *textObj = cJSON_Parse(text.c_str()); + if (textObj == NULL) { + LOGE("parse text failed"); + return text; + } + std::string resultText = text; + + cJSON *languageJson = cJSON_GetObjectItem(textObj, language.c_str()); + if (languageJson != NULL && cJSON_IsString(languageJson)) { + resultText = std::string(languageJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON *defaultJson = cJSON_GetObjectItem(textObj, DEFAULT_LANGUAGE.c_str()); + if (defaultJson != NULL && cJSON_IsString(defaultJson)) { + resultText = std::string(defaultJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON *enJson = cJSON_GetObjectItem(textObj, LANGUAGE_EN.c_str()); + if (enJson != NULL && cJSON_IsString(enJson)) { + resultText = std::string(enJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON_Delete(textObj); + return ""; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 8b40da361..b924f1fe6 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -206,6 +206,10 @@ public: void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList); + int32_t GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); void ProcessSyncUserIds(const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, const std::string &remoteUdid); int32_t SetLocalDisplayNameToSoftbus(const std::string &displayName); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 7d2e34906..4fc1b9c06 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -240,13 +240,17 @@ public: const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) = 0; - virtual void HandleUserRemoved(std::vector peerUdids, int32_t preUserId) = 0; + virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; + virtual int32_t SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) = 0; + virtual int32_t GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; virtual void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus) = 0; @@ -258,8 +262,10 @@ public: const std::string &localUdid, int32_t localUserId, const std::string &localAccountId) = 0; virtual int32_t RegisterAuthenticationType(int32_t authenticationType) = 0; virtual void DeleteAlwaysAllowTimeOut() = 0; - virtual void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) = 0; + virtual void CheckDeleteCredential(const std::string &remoteUdid) = 0; virtual int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId) = 0; + virtual void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index d0787d446..cc6409ce1 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -68,6 +68,7 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; bool ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; void ToStopUserPayLoad(uint8_t *&msg, uint32_t &len) const; @@ -76,6 +77,7 @@ struct RelationShipChangeMsg { bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromServiceUnbindPayLoad(const cJSON *payloadJson); bool FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson); bool FromDelUserPayLoad(const cJSON *payloadJson); bool FromStopUserPayLoad(const cJSON *payloadJson); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 55850a37a..248529538 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -74,6 +74,10 @@ public: static int32_t ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, DmDeviceInfo &devInfo); static void UpdateDeviceName(NodeBasicInfo *info); + static int32_t OnSyncLocalAclList(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList); + static int32_t OnGetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); int32_t InitSoftbusListener(); int32_t GetTrustedDeviceList(std::vector &deviceInfoList); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index aa87475de..3992ba4b1 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2154,7 +2154,7 @@ void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) if (!peerUdids.empty()) { // Send UserId Removed broadcast SendUserRemovedBroadCast(peerUdids, removedUserId); - dmServiceImpl_->HandleUserRemoved(peerUdids, removedUserId); + dmServiceImpl_->HandleUserRemoved(removedUserId); } } @@ -2414,7 +2414,7 @@ void DeviceManagerService::SendUnBindBroadCast(const std::vector &p uint64_t tokenId, int32_t bindLevel) { LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { SendDeviceUnBindBroadCast(peerUdids, userId); return; } @@ -2431,7 +2431,7 @@ void DeviceManagerService::SendUnBindBroadCast(const std::vector &p void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel, uint64_t peerTokenId) { - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { SendDeviceUnBindBroadCast(peerUdids, userId); return; } @@ -2527,6 +2527,10 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) static_cast(relationShipMsg.tokenId)); } break; + case RelationShipChangeType::SERVICE_UNBIND: + dmServiceImpl_->HandleServiceUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, + static_cast(relationShipMsg.tokenId)); + break; case RelationShipChangeType::SYNC_USERID: HandleUserIdsBroadCast(relationShipMsg.userIdInfos, relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); @@ -2728,6 +2732,26 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } +int32_t DeviceManagerService::SyncLocalAclListProcess(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) +{ + if (IsDMServiceImplReady()) { + return dmServiceImpl_->SyncLocalAclListProcess(localUdid, localUserId, remoteUdid, + remoteUserId, remoteAclList); + } + return ERR_DM_FAILED; +} + +int32_t DeviceManagerService::GetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + if (IsDMServiceImplReady()) { + return dmServiceImpl_->GetAclListHash(localUdid, + localUserId, remoteUdid, remoteUserId, aclList); + } + return ERR_DM_FAILED; +} + void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index a676b056d..9b23cd5a2 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -116,6 +116,10 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SERVICE_UNBIND: + ToServiceUnbindPayLoad(msg, len); + ret = true; + break; case RelationShipChangeType::SYNC_USERID: ret = ToSyncFrontOrBackUserIdPayLoad(msg, len); break; @@ -152,6 +156,9 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SERVICE_UNBIND: + ret = FromServiceUnbindPayLoad(payloadJson); + break; case RelationShipChangeType::SYNC_USERID: ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); break; @@ -188,6 +195,8 @@ bool RelationShipChangeMsg::IsValid() const ret = (userId != UINT32_MAX); break; case RelationShipChangeType::SERVICE_UNBIND: + ret = (userId != UINT32_MAX); + break; case RelationShipChangeType::APP_UNINSTALL: // current NOT support ret = false; @@ -210,7 +219,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_USERID) || - (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER); + (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER) || + (type == RelationShipChangeType::SERVICE_UNBIND); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) @@ -220,7 +230,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || (type == (uint32_t)RelationShipChangeType::SYNC_USERID) || (type == (uint32_t)RelationShipChangeType::DEL_USER) || - (type == (uint32_t)RelationShipChangeType::STOP_USER); + (type == (uint32_t)RelationShipChangeType::STOP_USER) || + (type == (uint32_t)RelationShipChangeType::SERVICE_UNBIND); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const @@ -263,6 +274,11 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con len = APP_UNBIND_PAYLOAD_LEN; } +void RelationShipChangeMsg::ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + ToAppUnbindPayLoad(msg, len); +} + bool RelationShipChangeMsg::ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const { uint32_t userIdNum = static_cast(userIdInfos.size()); @@ -407,6 +423,11 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } +bool RelationShipChangeMsg::FromServiceUnbindPayLoad(const cJSON *payloadJson) +{ + return FromAppUnbindPayLoad(payloadJson); +} + bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index aa3055c36..4a3729233 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -194,6 +194,20 @@ void SoftbusListener::CredentialAuthStatusProcess(std::string deviceList, uint16 DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } +int32_t SoftbusListener::OnSyncLocalAclList(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string remoteAclList) +{ + return DeviceManagerService::GetInstance().SyncLocalAclListProcess(localUdid, + localUserId, remoteUdid, remoteUserId, remoteAclList); +} + +int32_t SoftbusListener::OnGetAclListHash(const std::string localUdid, int32_t localUserId, + const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) +{ + return DeviceManagerService::GetInstance().GetAclListHash(localUdid, + localUserId, remoteUdid, remoteUserId, aclList); +} + void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, uint16_t deviceTypeId, int32_t errcode) { @@ -1295,7 +1309,7 @@ int32_t SoftbusListener::GetAllTrustedDeviceList(const std::string &pkgName, con #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) (void)extra; std::vector allProfile = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); for (DistributedDeviceProfile::AccessControlProfile profile : allProfile) { if (profile.GetBindType() == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP) { continue; diff --git a/test/commonfuzztest/BUILD.gn b/test/commonfuzztest/BUILD.gn index 4430b898c..c88c67ba2 100644 --- a/test/commonfuzztest/BUILD.gn +++ b/test/commonfuzztest/BUILD.gn @@ -19,12 +19,14 @@ group("fuzztest") { "authenticatedeviceservice_fuzzer:fuzztest", "authenticatedeviceserviceimpl_fuzzer:fuzztest", "dmauthmanager_fuzzer:fuzztest", + "dmauthmanagerv2_fuzzer:fuzztest", "dmcommoneventmanager_fuzzer:fuzztest", "dmcredentialimpl_fuzzer:fuzztest", "generateencrypteduuid_fuzzer:fuzztest", "getdeviceinfo_fuzzer:fuzztest", "hichainconnector_fuzzer:fuzztest", "ondatareceived_fuzzer:fuzztest", + "ondatareceivedv2_fuzzer:fuzztest", "onerror_fuzzer:fuzztest", "onfinish_fuzzer:fuzztest", "onrequest_fuzzer:fuzztest", diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index 0a3087fc2..5c81e1a9f 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -79,7 +79,6 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index e0278c801..1b8ea38d2 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -80,7 +80,6 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn index 1d394b8ad..34dc2e750 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn @@ -58,7 +58,6 @@ ohos_fuzztest("DmAuthManagerFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp index 2e0da79a6..fc9ff5b79 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp @@ -46,6 +46,7 @@ int32_t g_pageId = 1; int32_t g_reason = 1; int32_t g_state = 1; int64_t g_requestId = 1; +int64_t g_localSessionId = 1; std::map g_bindParam; @@ -80,7 +81,7 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->OnSessionOpened(g_sessionId, g_sessionSide, g_result); g_authManager->AuthenticateDevice(str, g_authType, str, str); g_authManager->ImportAuthCode(str, str); - g_authManager->BindTarget(str, g_targetId, g_bindParam); + g_authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); g_authManager->ShowConfigDialog(); g_authManager->ShowAuthInfoDialog(); g_authManager->ShowStartAuthDialog(); diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..d81bcb502 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2023-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DmAuthManagerV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/dmauthmanagerv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication_v2", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "dm_auth_manager_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DmAuthManagerV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":DmAuthManagerV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init new file mode 100644 index 000000000..d9719cafa --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp new file mode 100644 index 000000000..0858f3b67 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_service_listener.h" +#include "auth_manager.h" +#include "dm_auth_manager_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t g_sessionId = 1; +int32_t g_sessionSide = 0; +int32_t g_result = 1; +int32_t g_authType = 1; +int32_t g_status = 1; +int32_t g_pinCode = 1; +int32_t g_action = 1; +int32_t g_userId = 1; +int32_t g_pageId = 1; +int32_t g_reason = 1; +int32_t g_state = 1; +int64_t g_requestId = 1; +int64_t g_operationCode = 1; +int64_t g_localSessionId = 1; + +std::map g_bindParam; + +PeerTargetId g_targetId = { + .deviceId = "deviceId", + .brMac = "brMac", + .bleMac = "bleMac", + .wifiIp = "wifiIp", +}; + +// AuthSrcManager fuzz +void DmAuthSrcManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} + +// AuthSinkManager fuzz +void DmAuthSinkManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::DmAuthSrcManagerFuzzTest(data, size); + OHOS::DistributedHardware::DmAuthSinkManagerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h new file mode 100644 index 000000000..35643d1c4 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 DM_AUTH_MANAGER_FUZZER_H +#define DM_AUTH_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "dmauthmanagerv2_fuzzer" + +#endif // DM_AUTH_MANAGER_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml new file mode 100644 index 000000000..bac4974e9 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn index 17b0edcfd..1a3818c44 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn +++ b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn @@ -59,7 +59,6 @@ ohos_fuzztest("HichainConnectorFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn index dd8015779..b86115727 100644 --- a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn +++ b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn @@ -57,7 +57,6 @@ ohos_fuzztest("OnDataReceivedFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..6ecb86c33 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2023-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("OnDataReceivedV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/ondatareceivedv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "on_data_received_fuzzer.cpp" ] + + deps = [ + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"OnDataReceivedV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":OnDataReceivedV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init new file mode 100644 index 000000000..d9719cafa --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp new file mode 100644 index 000000000..6b1cec0cc --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "auth_manager.h" +#include "device_manager_service_listener.h" +#include "on_data_received_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { +// AuthSrcManager fuzz +void OnDataReceivedSrcFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); +} + +// AuthSinkManager fuzz +void OnDataReceivedSinkFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::OnDataReceivedSrcFuzzTest(data, size); + OHOS::DistributedHardware::OnDataReceivedSinkFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h new file mode 100644 index 000000000..e59b91fda --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_DATA_RECEIVED_FUZZER_H +#define ON_DATA_RECEIVED_FUZZER_H + +#define FUZZ_PROJECT_NAME "ondatareceivedv2_fuzzer" + +#endif // ON_DATA_RECEIVED_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml new file mode 100644 index 000000000..bac4974e9 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonfuzztest/onerror_fuzzer/BUILD.gn b/test/commonfuzztest/onerror_fuzzer/BUILD.gn index 9d9d2801d..2b3aa462a 100644 --- a/test/commonfuzztest/onerror_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onerror_fuzzer/BUILD.gn @@ -56,7 +56,6 @@ ohos_fuzztest("OnErrorFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn index 3881335e7..6883f3964 100644 --- a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn @@ -56,7 +56,6 @@ ohos_fuzztest("OnFinishFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn index 34a301d7a..34ea316f9 100644 --- a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn @@ -57,7 +57,6 @@ ohos_fuzztest("OnRequestFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 432039fdd..d0ed88960 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -39,7 +39,6 @@ using namespace testing; using namespace testing::ext; namespace OHOS { namespace DistributedHardware { -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; namespace { constexpr int32_t PINCODE = 100001; @@ -82,7 +81,12 @@ void DmAuthManagerTest::SetUp() std::shared_ptr(authManager_)); authManager_->timer_ = std::make_shared(); } -void DmAuthManagerTest::TearDown() {} + +void DmAuthManagerTest::TearDown() +{ + Mock::VerifyAndClearExpectations(softbusSessionMock_.get()); +} + void DmAuthManagerTest::SetUpTestCase() { softbusSessionMock_ = std::make_shared(); @@ -100,6 +104,7 @@ void DmAuthManagerTest::SetUpTestCase() cryptoMgrMock_ = std::make_shared(); DmCryptoMgr::dmCryptoMgr = cryptoMgrMock_; } + void DmAuthManagerTest::TearDownTestCase() { DmSoftbusSession::dmSoftbusSession = nullptr; @@ -203,7 +208,7 @@ HWTEST_F(DmAuthManagerTest, StartAuthProcess_001, testing::ext::TestSize.Level1) int32_t action = 0; g_reportAuthConfirmBoxReturnBoolValue = false; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; int32_t ret = authManager_->StartAuthProcess(action); ASSERT_EQ(ret, DM_OK); } @@ -564,7 +569,7 @@ HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Lev { std::string pkgName; std::string udid = "UnAuthenticateDevice_001"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; int32_t ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); EXPECT_NE(ret, DM_OK); @@ -594,7 +599,7 @@ HWTEST_F(DmAuthManagerTest, UnBindDevice_002, testing::ext::TestSize.Level1) { std::string pkgName; std::string udid = "UnBindDevice_002"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; std::string extra = "extraTest"; int32_t ret = authManager_->UnBindDevice(pkgName, udid, bindLevel, extra); EXPECT_NE(ret, DM_OK); @@ -778,9 +783,9 @@ HWTEST_F(DmAuthManagerTest, ImportCredential001, testing::ext::TestSize.Level1) { std::string deviceId = "deviceId"; std::string publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = authManager_->ImportCredential(deviceId, publicKey); - ASSERT_EQ(ret, ERR_DM_AUTH_FAILED); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, ResponseCredential001, testing::ext::TestSize.Level1) @@ -789,13 +794,13 @@ HWTEST_F(DmAuthManagerTest, ResponseCredential001, testing::ext::TestSize.Level1 ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authResponseContext_->publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(DM_OK)); authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -817,6 +822,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit002, testing::ext::TestSize.Level1 authManager_->authResponseState_ = nullptr; uint8_t *data = nullptr; uint32_t dataLen = 0; + EXPECT_CALL(*softbusSessionMock_, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); bool ret = authManager_->AuthDeviceTransmit(requestId, data, dataLen); ASSERT_EQ(ret, false); } @@ -828,6 +834,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit003, testing::ext::TestSize.Level1 authManager_->authRequestState_ = nullptr; uint8_t *data = nullptr; uint32_t dataLen = 0; + EXPECT_CALL(*softbusSessionMock_, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); bool ret = authManager_->AuthDeviceTransmit(requestId, data, dataLen); ASSERT_EQ(ret, false); } @@ -837,6 +844,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit004, testing::ext::TestSize.Level1 int64_t requestId = 0; uint8_t *data = nullptr; uint32_t dataLen = 0; + EXPECT_CALL(*softbusSessionMock_, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); bool ret = authManager_->AuthDeviceTransmit(requestId, data, dataLen); ASSERT_EQ(ret, false); } @@ -1038,13 +1046,6 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceSessionKey001, testing::ext::TestSize.Leve authManager_->GetSessionKeyIdSync(requestId); } -HWTEST_F(DmAuthManagerTest, GetRemoteDeviceId001, testing::ext::TestSize.Level1) -{ - std::string deviceId; - authManager_->GetRemoteDeviceId(deviceId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, CompatiblePutAcl001, testing::ext::TestSize.Level1) { authManager_->authRequestState_ = std::make_shared(); @@ -1498,10 +1499,10 @@ HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level1) authManager_->HandleDeviceNotTrust(udid); int32_t sessionId = 32166; authManager_->ProcIncompatible(sessionId); - + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); int32_t ret = authManager_->GetBindLevel(bindLevel); - ASSERT_EQ(ret, DEVICE); + ASSERT_EQ(ret, USER); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->GetBindLevel(bindLevel); @@ -1696,10 +1697,11 @@ HWTEST_F(DmAuthManagerTest, GetBinderInfo_001, testing::ext::TestSize.Level1) EXPECT_CALL(*appManagerMock_, GetNativeTokenIdByName(_, _)).WillOnce(Return(ERR_DM_FAILED)); EXPECT_CALL(*appManagerMock_, GetHapTokenIdByName(_, _, _, _)).WillOnce(Return(DM_OK)); + authManager_->authResponseContext_->bindLevel = APP; ret = authManager_->GetBinderInfo(); - ASSERT_EQ(ret, ERR_DM_FAILED); + ASSERT_EQ(ret, DM_OK); - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->SetProcessInfo(); authManager_->authResponseContext_->bindLevel = SERVICE; @@ -1832,7 +1834,7 @@ HWTEST_F(DmAuthManagerTest, RequestCredentialDone_003, testing::ext::TestSize.Le ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authResponseContext_->publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); authManager_->RequestCredentialDone(); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1962,7 +1964,7 @@ HWTEST_F(DmAuthManagerTest, RegisterAuthenticationType_001, testing::ext::TestSi { int32_t authenticationType = 1; int32_t ret = authManager_->RegisterAuthenticationType(authenticationType); - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, DM_OK); authenticationType = 0; ret = authManager_->RegisterAuthenticationType(authenticationType); @@ -2073,8 +2075,8 @@ HWTEST_F(DmAuthManagerTest, CheckNeedShowAuthInfoDialog_001, testing::ext::TestS authManager_->authResponseContext_->requestId = 1; authManager_->authMessageProcessor_ = std::make_shared(authManager_); EXPECT_CALL(*cryptoMgrMock_, SaveSessionKey(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, PutSessionKey(_, _)) - .WillOnce(DoAll(SetArgReferee<1>(1), Return(DM_OK))); + EXPECT_CALL(*deviceProfileConnectorMock_, PutSessionKey(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(1), Return(DM_OK))); authManager_->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); authManager_->GetSessionKeyIdSync(requestId); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 89df6d0d3..e1ebd3cfe 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -800,7 +800,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Leve authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; authManager_->ShowStartAuthDialog(); EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); @@ -847,7 +847,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level1) authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; EXPECT_CALL(*hiChainAuthConnectorMock_, AuthDevice(_, _, _, _)).WillOnce(Return(DM_OK)); int32_t ret = authManager_->ProcessPincode(pinCode); @@ -915,7 +915,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_001, testing::ext::TestSize.Level1) std::string pkgName; PeerTargetId targetId; std::map bindParam; - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -924,7 +926,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_002, testing::ext::TestSize.Level1) std::string pkgName = "pkgName"; PeerTargetId targetId; std::map bindParam; - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -936,7 +940,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_004, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "1")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_AUTH_BUSINESS_BUSY); } @@ -948,7 +954,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_005, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "2")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1577,7 +1585,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level authManager_->authResponseContext_->isOnline = true; EXPECT_CALL(*softbusConnectorMock_, CheckIsOnline(_)).WillOnce(Return(true)); - EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _, _)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).WillOnce(Return(true)); authManager_->GetAuthRequestContext(); JsonObject jsonPeerGroupIdObj; @@ -1644,8 +1652,7 @@ HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level1) authManager_->ProcessAuthRequest(sessionId); authManager_->authResponseContext_->haveCredential = true; - EXPECT_CALL(*hiChainAuthConnectorMock_, - QueryCredential(_, _, _)).Times(::testing::AtLeast(2)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).Times(::testing::AtLeast(2)).WillOnce(Return(true)); authManager_->GetAuthRequestContext(); authManager_->authResponseContext_->isOnline = true; @@ -1736,7 +1743,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_006, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "2")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_AUTH_TYPE); } } // namespace diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index 2e644498e..559b079e2 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -344,7 +344,7 @@ HWTEST_F(DmAuthManagerTest, DeleteAccessControlList004, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::string localDeviceId = "localDeviceId"; std::string remoteDeviceId = "remoteDeviceId"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; std::string extra = ""; auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel, extra); diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 9a82df953..88d823b1d 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -686,7 +686,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDmAuthForm_002, testing::ext::TestSiz { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_POINT_TO_POINT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); DmDiscoveryInfo discoveryInfo; int32_t ret = DeviceProfileConnector::GetInstance().HandleDmAuthForm(profiles, discoveryInfo); EXPECT_EQ(ret, PEER_TO_PEER); @@ -724,7 +724,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDmAuthForm_005, testing::ext::TestSiz { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_ACROSS_ACCOUNT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); DmDiscoveryInfo discoveryInfo; int32_t ret = DeviceProfileConnector::GetInstance().HandleDmAuthForm(profiles, discoveryInfo); EXPECT_EQ(ret, ACROSS_ACCOUNT); @@ -944,9 +944,7 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes DmAccessee dmAccessee; int32_t userId = 123456; std::string localDeviceId = "deviceId"; - std::vector peerUdids; - std::multimap peerUserIdMap; - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId, peerUdids, peerUserIdMap); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId); int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); EXPECT_EQ(ret, DM_OK); } @@ -991,7 +989,7 @@ HWTEST_F(DeviceProfileConnectorTest, ProcessBindType_003, testing::ext::TestSize { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_POINT_TO_POINT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); std::string targetDeviceId = "targetDeviceId"; std::string localDeviceId = "localDeviceId"; uint32_t index = 0; @@ -1007,7 +1005,7 @@ HWTEST_F(DeviceProfileConnectorTest, ProcessBindType_004, testing::ext::TestSize { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_ACROSS_ACCOUNT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); std::string targetDeviceId = "targetDeviceId"; std::string localDeviceId = "localDeviceId"; uint32_t index = 0; @@ -1086,8 +1084,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckDevIdInAclForDevBind_001, testing::ext HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_001, testing::ext::TestSize.Level1) { std::string deviceId; - int32_t peerUserId = -1; - uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId, peerUserId); + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); EXPECT_EQ(ret, 0); } @@ -1123,11 +1120,11 @@ HWTEST_F(DeviceProfileConnectorTest, GetAuthForm_001, testing::ext::TestSize.Lev ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); profile.SetBindType(DM_POINT_TO_POINT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, DEVICE_PEER_TO_PEER_TYPE); profile.SetBindType(DM_ACROSS_ACCOUNT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, DEVICE_ACROSS_ACCOUNT_TYPE); profile.SetBindLevel(APP); @@ -1160,33 +1157,33 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_001, testing::ext::TestSize.Le HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_001, testing::ext::TestSize.Level1) { std::string udid = "deviceId"; - int32_t bindType = DEVICE; + int32_t bindType = USER; std::map deviceMap; deviceMap[udid] = APP; DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); - EXPECT_EQ(deviceMap[udid], DEVICE); + EXPECT_EQ(deviceMap[udid], USER); } HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_002, testing::ext::TestSize.Level1) { std::string udid = "deviceId"; - int32_t bindType = DEVICE; + int32_t bindType = USER; std::map deviceMap; DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); - EXPECT_EQ(deviceMap[udid], DEVICE); + EXPECT_EQ(deviceMap[udid], USER); } HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_001, testing::ext::TestSize.Level1) { int32_t remoteUserId = 0; - int32_t bindType = DM_INVALIED_BINDTYPE; + int32_t bindType = DM_INVALIED_TYPE; std::string remoteAccountHash = "remoteAccountHash"; std::string remoteUdid = "1"; std::string localUdid = "localDeviceId"; bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid, localUdid); - EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + EXPECT_EQ(bindType, DM_INVALIED_TYPE); } HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::TestSize.Level1) @@ -1194,10 +1191,11 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::Tes int32_t remoteUserId = 0; std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; - int32_t bindType = DM_INVALIED_BINDTYPE; - - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); - EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + int32_t bindType = DM_INVALIED_TYPE; + DmOfflineParam offlineParam; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); + EXPECT_EQ(bindType, DM_INVALIED_TYPE); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::TestSize.Level1) @@ -1207,14 +1205,15 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, - remoteUdid, tokenId, localUdid); - EXPECT_NE(offlineParam.leftAclNumber, 0); + DmOfflineParam res; + + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ(0, res.processVec.size()); int32_t peerTokenId = 1; - offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid, peerTokenId); - EXPECT_EQ(offlineParam.leftAclNumber, 0); + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, + peerTokenId); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level1) @@ -1230,7 +1229,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindType(DM_POINT_TO_POINT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindLevel(APP); @@ -1240,7 +1239,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindType(DM_ACROSS_ACCOUNT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindLevel(APP); @@ -1256,7 +1255,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfileByUserId_001, testing::ext::TestSize.Level1) { - int32_t userId = DEVICE; + int32_t userId = USER; std::vector profiles; profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); EXPECT_GE(profiles.size(), 0); @@ -1302,12 +1301,12 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteDeviceBindLevel_001, testing::ext::Te std::string remoteUdid="localDeviceId"; GetAccessControlProfiles(profiles); DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); - EXPECT_EQ(offlineParam.bindType, DEVICE); + EXPECT_EQ(offlineParam.bindType, USER); localUdid = "localDeviceId"; remoteUdid="remoteDeviceId"; DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); - EXPECT_EQ(offlineParam.bindType, DEVICE); + EXPECT_EQ(offlineParam.bindType, USER); } HWTEST_F(DeviceProfileConnectorTest, DeleteServiceBindLevel_001, testing::ext::TestSize.Level1) @@ -1341,8 +1340,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_004, testing:: HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_002, testing::ext::TestSize.Level1) { std::string deviceId = "remoteDeviceId"; - int32_t peerUserId = 0; - uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId, peerUserId); + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); EXPECT_EQ(ret, 0); } @@ -1393,7 +1391,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_001, testing::ext::TestS HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext::TestSize.Level1) { int32_t remoteUserId = 0; - int32_t bindType = DM_INVALIED_BINDTYPE; + int32_t bindType = DM_INVALIED_TYPE; std::string remoteAccountHash = "remoteAccountHash"; std::string remoteUdid = "123456"; std::string localUdid = "localDeviceId"; @@ -1420,22 +1418,27 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::Tes int32_t remoteUserId = 0; std::string remoteUdid; std::string localUdid = "localDeviceId"; - int32_t bindType = DM_INVALIED_BINDTYPE; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); - EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + int32_t bindType = DM_INVALIED_TYPE; + DmOfflineParam offlineParam; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); + EXPECT_EQ(bindType, DM_INVALIED_TYPE); remoteUdid = "123456"; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); - EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); + EXPECT_EQ(bindType, DM_INVALIED_TYPE); remoteUdid = "localDeviceId"; remoteUserId = 1234; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); remoteUserId = 456; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); - EXPECT_EQ(bindType, 3); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); + EXPECT_EQ(bindType, DM_INVALIED_TYPE); } HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ext::TestSize.Level1) @@ -1866,25 +1869,23 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_002, testing::ext::Tes std::string remoteUdid = "localDeviceId"; std::string localUdid = "remoteDeviceId"; std::string pkgName = ""; - DmOfflineParam offlineParam; - offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid); - EXPECT_NE(offlineParam.leftAclNumber, 0); + DmOfflineParam res; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ(1, res.processVec.size()); int32_t peerTokenId = 1001; - offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid, peerTokenId); - EXPECT_EQ(offlineParam.leftAclNumber, 0); + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, + peerTokenId); + EXPECT_EQ(1, res.processVec.size()); tokenId = 1002; peerTokenId = tokenId; - offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid); - EXPECT_EQ(offlineParam.leftAclNumber, 0); + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ(1, res.processVec.size()); - offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid, peerTokenId); - EXPECT_EQ(offlineParam.leftAclNumber, 0); + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, + peerTokenId); + EXPECT_EQ(1, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_003, testing::ext::TestSize.Level1) @@ -1895,9 +1896,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_003, testing::ext::Tes std::string localUdid = "localDeviceId"; std::string pkgName = ""; int32_t peerTokenId = 1001; - DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, + DmOfflineParam res; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_NE(offlineParam.leftAclNumber, 0); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_004, testing::ext::TestSize.Level1) @@ -1908,9 +1910,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_004, testing::ext::Tes std::string localUdid = "localDeviceId"; std::string pkgName = ""; int32_t peerTokenId = 1001; - DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, + DmOfflineParam res; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_NE(offlineParam.leftAclNumber, 0); + EXPECT_EQ(2, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, GetTokenIdByNameAndDeviceId_002, testing::ext::TestSize.Level1) @@ -2042,7 +2045,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetParamBindTypeVec_001, testing::ext::Test EXPECT_FALSE(bindTypeVec.empty()); bindTypeVec.clear(); - profiles.SetBindType(DM_INVALIED_BINDTYPE); + profiles.SetBindType(DM_INVALIED_TYPE); DeviceProfileConnector::GetInstance().GetParamBindTypeVec(profiles, requestDeviceId, bindTypeVec, trustUdid); EXPECT_TRUE(bindTypeVec.empty()); } @@ -2218,7 +2221,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_002, testing::ext::TestSize.Le udid = "deviceId"; EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); bindLevel = DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); - EXPECT_EQ(bindLevel, DEVICE); + EXPECT_EQ(bindLevel, USER); int32_t bindType = 256; std::string peerUdid = "123456"; diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 523d6d259..7f777ce50 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -121,7 +121,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfile_201, testing: HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfileByUserId_201, testing::ext::TestSize.Level1) { - int32_t userId = DEVICE; + int32_t userId = USER; std::vector profiles; EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); @@ -149,9 +149,9 @@ HWTEST_F(DeviceProfileConnectorSecondTest, CheckAuthForm_201, testing::ext::Test profiles.SetBindLevel(SERVICE); ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); - EXPECT_EQ(ret, DmAuthForm::INVALID_TYPE); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); } @@ -190,7 +190,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, CheckIdenticalAccount_201, testing::e profile.SetBindType(bindType); profile.SetAccesser(accesser); profile.SetAccessee(accessee); - + int userIds = 12356; std::string remoteUdid = "deviceId"; std::vector remoteFrontUserIds; @@ -296,7 +296,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_002, testing::e std::string remoteUdid = "nonExistentDevice"; EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAllAccessControlProfile(_)).WillOnce(Return(DM_OK)); auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); - + EXPECT_TRUE(result.empty()); } @@ -507,7 +507,8 @@ HWTEST_F(DeviceProfileConnectorSecondTest, PutSessionKey_201, testing::ext::Test { std::vector sessionKeyArray; int32_t sessionKeyId = 1; - int32_t ret = DeviceProfileConnector::GetInstance().PutSessionKey(sessionKeyArray, sessionKeyId); + int32_t userId = 100; + int32_t ret = DeviceProfileConnector::GetInstance().PutSessionKey(userId, sessionKeyArray, sessionKeyId); EXPECT_EQ(ret, ERR_DM_FAILED); sessionKeyArray.push_back('1'); @@ -516,11 +517,11 @@ HWTEST_F(DeviceProfileConnectorSecondTest, PutSessionKey_201, testing::ext::Test sessionKeyArray.push_back('4'); sessionKeyArray.push_back('5'); EXPECT_CALL(*distributedDeviceProfileClientMock_, PutSessionKey(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); - ret = DeviceProfileConnector::GetInstance().PutSessionKey(sessionKeyArray, sessionKeyId); + ret = DeviceProfileConnector::GetInstance().PutSessionKey(userId, sessionKeyArray, sessionKeyId); EXPECT_EQ(ret, ERR_DM_FAILED); EXPECT_CALL(*distributedDeviceProfileClientMock_, PutSessionKey(_, _, _)).WillOnce(Return(DM_OK)); - ret = DeviceProfileConnector::GetInstance().PutSessionKey(sessionKeyArray, sessionKeyId); + ret = DeviceProfileConnector::GetInstance().PutSessionKey(userId, sessionKeyArray, sessionKeyId); EXPECT_EQ(ret, DM_OK); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 805b97404..9058c5861 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -67,18 +67,12 @@ public: (void)sessionKey; (void)sessionKeyLen; } - int32_t GetPinCode(int32_t &code) override + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override { - if (pinCode == 0) { - code = 0; - return DM_OK; - } - code = ERR_DM_AUTH_NOT_START; - return ERR_DM_AUTH_NOT_START; - } - void GetRemoteDeviceId(std::string &deviceId) override - { - (void)deviceId; + (void)requestId; + (void)operationCode; + (void)reqParams; + return nullptr; } private: int32_t pinCode = 0; @@ -162,20 +156,6 @@ HWTEST_F(HiChainAuthConnectorTest, onRequest_003, testing::ext::TestSize.Level1) EXPECT_NE(hiChain_->dmDeviceAuthCallback_, nullptr); } -HWTEST_F(HiChainAuthConnectorTest, onRequest_004, testing::ext::TestSize.Level1) -{ - int64_t requestId = 0; - int operationCode = 0; - char *reqParams = nullptr; - std::shared_ptr hiChainAuthConnector = std::make_shared(); - std::shared_ptr mockCallback = std::make_shared(); - hiChainAuthConnector->dmDeviceAuthCallback_ = mockCallback; - EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) - .Times(1) - .WillOnce(testing::Return(ERR_DM_FAILED)); - EXPECT_NE(hiChainAuthConnector->onRequest(requestId, operationCode, reqParams), nullptr); -} - HWTEST_F(HiChainAuthConnectorTest, onFinish_001, testing::ext::TestSize.Level1) { int64_t requestId = 0; @@ -266,7 +246,7 @@ HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_003, testing::ext::TestSiz g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); - EXPECT_EQ(ret, DM_OK); + EXPECT_NE(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_004, testing::ext::TestSize.Level1) @@ -288,7 +268,7 @@ HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_005, testing::ext::TestSiz g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "key"})"; int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); - EXPECT_EQ(ret, DM_OK); + EXPECT_NE(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_006, testing::ext::TestSize.Level1) @@ -306,8 +286,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_001, testing::ext::TestSize.L { std::string localUdid = "2131351352"; int32_t osAccountId = 0; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); } @@ -318,8 +297,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L jsonObject["publicKey"] = 0; std::string localUdid = SafetyDump(jsonObject); int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); } @@ -332,8 +310,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_FALSE(ret); } @@ -346,9 +323,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); - EXPECT_TRUE(ret); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.Level1) @@ -360,9 +336,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); - EXPECT_TRUE(ret); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.Level1) @@ -374,8 +349,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_FALSE(ret); } @@ -388,9 +362,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); - EXPECT_TRUE(ret); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.Level1) @@ -402,8 +375,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; - int32_t peerOsAccountId = -1; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_TRUE(ret); } @@ -444,7 +416,7 @@ HWTEST_F(HiChainAuthConnectorTest, GetCredential_004, testing::ext::TestSize.Lev g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, GetCredential_005, testing::ext::TestSize.Level1) @@ -455,7 +427,7 @@ HWTEST_F(HiChainAuthConnectorTest, GetCredential_005, testing::ext::TestSize.Lev g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, GetCredential_006, testing::ext::TestSize.Level1) @@ -477,7 +449,7 @@ HWTEST_F(HiChainAuthConnectorTest, GetCredential_007, testing::ext::TestSize.Lev g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, GetCredential_008, testing::ext::TestSize.Level1) @@ -496,8 +468,7 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_001, testing::ext::TestSize. int32_t localUdid = 0; std::string deviceId; std::string publicKey; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); EXPECT_NE(ret, DM_OK); } @@ -506,8 +477,7 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestSize. int32_t localUdid = 0; std::string deviceId = "4513541351"; std::string publicKey = "42125143613"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); EXPECT_NE(ret, DM_OK); } @@ -518,9 +488,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_003, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); - EXPECT_EQ(ret, DM_OK); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize.Level1) @@ -530,9 +499,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); - EXPECT_EQ(ret, DM_OK); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize.Level1) @@ -542,9 +510,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1})"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); - EXPECT_EQ(ret, DM_OK); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize.Level1) @@ -554,8 +521,7 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 0})"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); EXPECT_EQ(ret, DM_OK); } @@ -563,8 +529,7 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_001, testing::ext::TestSize. { std::string deviceId; int32_t userId = 0; - int32_t peerUserId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); EXPECT_EQ(ret, DM_OK); } @@ -572,8 +537,7 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_002, testing::ext::TestSize. { std::string deviceId = "864513535"; int32_t userId = 0; - int32_t peerUserId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); EXPECT_EQ(ret, DM_OK); } @@ -583,8 +547,7 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_003, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); EXPECT_EQ(ret, 0); } @@ -594,9 +557,8 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); - EXPECT_EQ(ret, DM_OK); + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize.Level1) @@ -605,9 +567,8 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 100})"; - int32_t peerUserId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); - EXPECT_EQ(ret, DM_OK); + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, 100); } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_hichain_auth_connector.h b/test/commonunittest/UTTest_hichain_auth_connector.h index 3c708b598..fdff7c0cb 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.h +++ b/test/commonunittest/UTTest_hichain_auth_connector.h @@ -44,8 +44,7 @@ public: MOCK_METHOD(void, AuthDeviceError, (int64_t requestId, int32_t errorCode), (override)); MOCK_METHOD(void, AuthDeviceSessionKey, (int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen), (override)); - MOCK_METHOD(void, GetRemoteDeviceId, (std::string &deviceId), (override)); - MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); + MOCK_METHOD(char *, AuthDeviceRequest, (int64_t requestId, int operationCode, const char *reqParams), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index 21041b11a..160628a41 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -77,7 +77,6 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn b/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn index a7088be2b..8c61184f5 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn @@ -44,7 +44,6 @@ ohos_fuzztest("DeviceProfileConnectorFuzzTest") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", - "init:libbegetutil", "ipc:ipc_single", ] diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index fb5dd1d32..c7875807c 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -63,7 +63,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, localDeviceId); - DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId, userId); + DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId); DeviceProfileConnector::GetInstance().GetTrustNumber(localDeviceId); } } diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index 7c353daa9..78697ead4 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -71,7 +71,6 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index a43f96e63..fb7eeaba4 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -71,7 +71,6 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp index 2d0979540..2fe1110fd 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp @@ -57,11 +57,9 @@ void OnBytesReceivedFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size < sizeof(int))) { return; } - int sessionId = *(reinterpret_cast(data)); std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); - softbusSession->OnBytesReceived(sessionId, data, size); } } } diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn index cb057edf6..680c3e943 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn @@ -64,7 +64,6 @@ ohos_fuzztest("OnSessionOpenedFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", - "init:libbegetutil", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnector_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnector_fuzzer/BUILD.gn index cff815de9..a0f557271 100644 --- a/test/softbusfuzztest/softbusconnector_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnector_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("SoftbusConnectorFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn index 4112453d5..c81460d74 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("SoftbusConnectorCommonFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnectorpublish_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorpublish_fuzzer/BUILD.gn index 048f39fd9..ea4a95756 100644 --- a/test/softbusfuzztest/softbusconnectorpublish_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorpublish_fuzzer/BUILD.gn @@ -51,6 +51,7 @@ ohos_fuzztest("SoftbusConnectorPublishFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn index a1d6a4c28..979275435 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("SoftbusConnectorStateFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnectorstatic_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorstatic_fuzzer/BUILD.gn index ef1a119c6..40169545d 100644 --- a/test/softbusfuzztest/softbusconnectorstatic_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorstatic_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("SoftbusConnectorStaticFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbussession_fuzzer/BUILD.gn b/test/softbusfuzztest/softbussession_fuzzer/BUILD.gn index f31b185a1..afb64d507 100644 --- a/test/softbusfuzztest/softbussession_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbussession_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("SoftbusSessionFuzzTest") { external_deps = [ "bounds_checking_function:libsec_shared", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp index a079a5c9e..9df6f8cdc 100644 --- a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp +++ b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp @@ -70,7 +70,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) softbusSession->OnSessionOpened(result, result); softbusSession->OpenAuthSession(str); softbusSession->CloseAuthSession(sessionId); - softbusSession->OnBytesReceived(result, str.c_str(), str.size()); softbusSession->GetPeerDeviceId(sessionId, str); softbusSession->SendData(sessionId, str); softbusSession->SendHeartbeatData(sessionId, str); diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn index 08fea482c..d42fa8b73 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("SoftbusSessionObjectFuzzTest") { ] external_deps = [ + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp index fe688c42f..3d76c29ca 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp @@ -58,21 +58,8 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) return; } - int32_t socket = *(reinterpret_cast(data)); - QoSEvent eventId = static_cast(1); - uint32_t qosCount = 3; - QosTV qos[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 19000}, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 500 }, - }; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); - softbusSession->iSocketListener_.OnBytes(socket, data, size); - softbusSession->iSocketListener_.OnShutdown(socket, reason); - softbusSession->iSocketListener_.OnQos(socket, eventId, qos, qosCount); } } } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index c510b8492..deb4a4b08 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -220,7 +220,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level1 std::string deviceId; std::string connectAddr; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_EQ(ret, nullptr); } @@ -237,7 +237,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level1 DeviceInfo deviceInfo; deviceInfo.addrNum = -1; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_EQ(ret, nullptr); } @@ -259,7 +259,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_003, testing::ext::TestSize.Level1 deviceInfo->addr[0].info.ip.port = 0; SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -282,7 +282,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_004, testing::ext::TestSize.Level1 deviceInfo->addr[0].info.ip.port = 0; SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -304,7 +304,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_005, testing::ext::TestSize.Level1 (void)strncpy_s(deviceInfo->addr[0].info.br.brMac, IP_STR_MAX_LEN, brMac, strlen(brMac)); SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -326,7 +326,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_006, testing::ext::TestSize.Level1 (void)strncpy_s(deviceInfo->addr[0].info.ble.bleMac, IP_STR_MAX_LEN, bleMac, strlen(bleMac)); SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index e5618bb35..3559e9d18 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -80,7 +80,7 @@ HWTEST_F(SoftbusSessionTest, OpenAuthSession_002, testing::ext::TestSize.Level1) /** * @tc.name: SendData_001 - * @tc.desc: set message null and return ERR_DM_FAILED + * @tc.desc: set message null but sessionId is invalid, return SOFTBUS_INVALID_PARAM * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -92,7 +92,7 @@ HWTEST_F(SoftbusSessionTest, SendData_001, testing::ext::TestSize.Level1) softbusSession = std::make_shared(); } int ret = softbusSession->SendData(sessionId, message); - EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); } /** @@ -119,7 +119,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level1) /** * @tc.name: SendData_003 - * @tc.desc: set jsonObject[TAG_MSG_TYPE] is string and return ERR_DM_FAILED + * @tc.desc: set jsonObject[TAG_MSG_TYPE] is string but not openAuthSession, return SOFTBUS_TRANS_UDP_GET_CHANNEL_FAILED * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -135,7 +135,7 @@ HWTEST_F(SoftbusSessionTest, SendData_003, testing::ext::TestSize.Level1) softbusSession = std::make_shared(); } int32_t ret = softbusSession->SendData(sessionId, message); - EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_EQ(ret, SOFTBUS_TRANS_SESSION_SERVER_NOINIT); } /** @@ -241,12 +241,7 @@ HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level1) softbusSession->RegisterSessionCallback(discoveryMgr); int sessionId = 1; int result = 0; - void *data = nullptr; - unsigned int dataLen = 1; - softbusSession->OnBytesReceived(sessionId, data, dataLen); - softbusSession->OnBytesReceived(sessionId, data, -1); - sessionId = -1; - softbusSession->OnBytesReceived(sessionId, data, dataLen); + int ret = softbusSession->OnSessionOpened(sessionId, result); softbusSession->OnSessionClosed(sessionId); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 4d11ca407..eba271921 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -92,6 +92,9 @@ group("unittest") { ":UTTest_softbus_listener_two", ":UTTest_softbus_publish", ":UTTest_softbus_session", + ":UTTest_auth_pin_auth_state", + ":UTTest_auth_credential_state", + ":UTTest_auth_negotiate_state", ] } @@ -1199,7 +1202,6 @@ ohos_unittest("UTTest_device_manager_service_impl") { module_out_path = module_out_path sources = [ - "${devicemanager_path}/commondependency/src/multiple_user_connector.cpp", "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", "mock/deviceprofile_connector_mock.cpp", @@ -1982,6 +1984,99 @@ ohos_unittest("UTTest_json_object") { ## UnitTest UTTest_json_object }}} +## UnitTest UTTest_auth_pin_auth_state {{{ + +ohos_unittest("UTTest_auth_pin_auth_state") { + module_out_path = module_out_path + + include_dirs = [ + + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_pin_auth_state.cpp", + "${devicemanager_path}/test/unittest/mock/hichain_auth_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_state_machine_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "dsoftbus:softbus_client", + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_pin_auth_state }}} + +## UnitTest UTTest_auth_credential_state {{{ + +ohos_unittest("UTTest_auth_credential_state") { + module_out_path = module_out_path + + include_dirs = [ + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_credential_state.cpp", + "${devicemanager_path}/test/unittest/mock/hichain_auth_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_state_machine_mock.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_session_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_message_processor_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "dsoftbus:softbus_client", + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_credential_state }}} + +## UnitTest UTTest_auth_negotiate_state {{{ + +ohos_unittest("UTTest_auth_negotiate_state") { + module_out_path = module_out_path + + include_dirs = [ + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_negotiate_state.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_session_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "dsoftbus:softbus_client", + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_negotiate_state }}} + ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ diff --git a/test/unittest/UTTest_auth_credential_state.cpp b/test/unittest/UTTest_auth_credential_state.cpp new file mode 100644 index 000000000..519690d9b --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.cpp @@ -0,0 +1,1003 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_state.h" +#include "UTTest_auth_credential_state.h" +#include "dm_auth_message_processor_mock.h" +#include "device_manager_service_listener.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char *TEST_NONE_EMPTY_STRING = "test"; + +void AuthCredentialStateTest::SetUpTestCase() +{ + LOGI("AuthCredentialStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = dmHiChainAuthConnectorMock; + DmSoftbusSession::dmSoftbusSession = dmSoftbusSessionMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = dmAuthStateMachineMock; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = std::make_shared(); +} + +void AuthCredentialStateTest::TearDownTestCase() +{ + LOGI("AuthCredentialStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + dmHiChainAuthConnectorMock = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; + dmSoftbusSessionMock = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + dmAuthStateMachineMock = nullptr; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = nullptr; +} + +void AuthCredentialStateTest::SetUp() +{ + LOGI("AuthCredentialStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + +} + +void AuthCredentialStateTest::TearDown() +{ + LOGI("AuthCredentialStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; + Mock::VerifyAndClearExpectations(&*DmHiChainAuthConnector::dmHiChainAuthConnector); + Mock::VerifyAndClearExpectations(&*DmSoftbusSession::dmSoftbusSession); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); + Mock::VerifyAndClearExpectations(&*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->isOnline = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->isOnline = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->isOnline = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->isOnline = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->isOnline = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_008, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_009, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_006, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_007, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_008, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->direction == DM_AUTH_SOURCE; + context->accesser.isAuthed = false; + context->needAgreeCredential = true; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_006, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_007, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_008, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_001, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_002, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + context->accesser.isGenerateLnnCredential == true; + context->isAppCredentialVerified = false; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_003, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_004, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_005, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_006, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_007, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_008, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_009, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return("")); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_0010, testing::ext::TestSize.Level1) +{ + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + std::shared_ptr authState = std::make_shared(); + context->transmitData = "test"; + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_credential_state.h b/test/unittest/UTTest_auth_credential_state.h new file mode 100644 index 000000000..ba2893051 --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 UTTEST_AUTH_CREDENTIAL_STATE_H +#define UTTEST_AUTH_CREDENTIAL_STATE_H + +#include +#include "hichain_auth_connector_mock.h" +#include "softbus_session_mock.h" +#include "dm_auth_state_machine_mock.h" +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthCredentialStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr dmHiChainAuthConnectorMock = + std::make_shared(); + static inline std::shared_ptr dmSoftbusSessionMock = + std::make_shared(); + static inline std::shared_ptr dmAuthStateMachineMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.cpp b/test/unittest/UTTest_auth_negotiate_state.cpp new file mode 100644 index 000000000..5d276478c --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_manager_service_listener.h" +#include "dm_auth_state.h" +#include "UTTest_auth_negotiate_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char* TEST_STRING = "test_string"; +constexpr int32_t TEST_NEGATIVE = -1; +constexpr int32_t TEST_POSITIVE = 1; + +void AuthNegotiateStateTest::SetUpTestCase() +{ + LOGI("AuthNegotiateStateTest::SetUpTestCase start."); + + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock; + DmSoftbusSession::dmSoftbusSession = softbusSessionMock; +} + +void AuthNegotiateStateTest::TearDownTestCase() +{ + LOGI("AuthNegotiateStateTest::TearDownTestCase done."); + softbusConnectorMock = nullptr; + softbusSessionMock = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; +} + +void AuthNegotiateStateTest::SetUp() +{ + LOGI("AuthNegotiateStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + softbusSession = std::make_shared(); + + Mock::VerifyAndClearExpectations(&*softbusConnectorMock); + Mock::VerifyAndClearExpectations(&*softbusSessionMock); +} + +void AuthNegotiateStateTest::TearDown() +{ + LOGI("AuthNegotiateStateTest::TearDown done."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; + softbusSession = nullptr; +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_START_STATE); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession) + .WillOnce(Return(softbusSession)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE); +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.h b/test/unittest/UTTest_auth_negotiate_state.h new file mode 100644 index 000000000..d385723bc --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 UTTEST_AUTH_NEGOTIATE_STATE_H +#define UTTEST_AUTH_NEGOTIATE_STATE_H + +#include "gtest/gtest.h" +#include "auth_manager.h" +#include "softbus_connector_mock.h" +#include "softbus_session_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthNegotiateStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr softbusConnectorMock = + std::make_shared(); + static inline std::shared_ptr softbusSessionMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; + std::shared_ptr softbusSession; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.cpp b/test/unittest/UTTest_auth_pin_auth_state.cpp new file mode 100644 index 000000000..acd9376ee --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.cpp @@ -0,0 +1,420 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_state_machine_mock.h" +#include "UTTest_auth_pin_auth_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +void AuthPinAuthStateTest::SetUpTestCase() +{ + LOGI("AuthPinAuthStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = std::make_shared(); +} + +void AuthPinAuthStateTest::TearDownTestCase() +{ + LOGI("AuthPinAuthStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + hiChainAuthConnectorMock = nullptr; +} + +void AuthPinAuthStateTest::SetUp() +{ + LOGI("AuthPinAuthStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + + Mock::VerifyAndClearExpectations(&*hiChainAuthConnectorMock); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); +} + +void AuthPinAuthStateTest::TearDown() +{ + LOGI("AuthPinAuthStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_EQ(authState->Action(context), DM_OK); +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.h b/test/unittest/UTTest_auth_pin_auth_state.h new file mode 100644 index 000000000..6d4fee840 --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 UTTEST_AUTH_PIN_AUTH_STATE_H +#define UTTEST_AUTH_PIN_AUTH_STATE_H + +#include +#include "device_manager_service_listener.h" +#include "hichain_auth_connector_mock.h" +#include "auth_manager.h" +#include "dm_negotiate_process.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthPinAuthStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr hiChainAuthConnectorMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index e711089af..90514cea8 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -68,17 +68,22 @@ void DeviceManagerImplTest::SetUp() void DeviceManagerImplTest::TearDown() { + testing::Mock::VerifyAndClearExpectations(deviceManagerNotifyMock_.get()); + testing::Mock::VerifyAndClearExpectations(ipcClientProxyMock_.get()); } void DeviceManagerImplTest::SetUpTestCase() { DmDeviceManagerNotify::dmDeviceManagerNotify = deviceManagerNotifyMock_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxyMock_; } void DeviceManagerImplTest::TearDownTestCase() { DmDeviceManagerNotify::dmDeviceManagerNotify = nullptr; deviceManagerNotifyMock_ = nullptr; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; + ipcClientProxyMock_ = nullptr; } namespace { @@ -203,6 +208,8 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceNetWorkId_101, testing::ext::TestS { std::string packName; std::string networkId; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalDeviceNetWorkId(packName, networkId); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -241,6 +248,8 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceId_101, testing::ext::TestSize.Lev { std::string packName; std::string deviceId; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalDeviceId(packName, deviceId); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -279,6 +288,8 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceName_101, testing::ext::TestSize.L { std::string packName; std::string deviceName; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalDeviceName(packName, deviceName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -318,6 +329,8 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceType_101, testing::ext::TestSize.L { std::string packName; int32_t deviceType = 0; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalDeviceType(packName, deviceType); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -396,6 +409,8 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceName_103, testing::ext::TestSize.Level0 std::string packName = "com.ohos.test"; std::string networkId = "networkId"; std::string deviceName; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetDeviceName(packName, networkId, deviceName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -476,14 +491,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceType_103, testing::ext::TestSize.Level0 std::string packName = "com.ohos.test"; std::string networkId = "networkId"; int32_t deviceType = 0; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetDeviceType(packName, networkId, deviceType); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -556,14 +567,10 @@ HWTEST_F(DeviceManagerImplTest, UnBindDevice_103, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; std::string deviceId = "deviceId"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().UnBindDevice(packName, deviceId); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -670,14 +677,10 @@ HWTEST_F(DeviceManagerImplTest, BindDevice_103, testing::ext::TestSize.Level0) std::string deviceId = "deviceId"; std::string bindParam = "{\"status\":1}"; std::shared_ptr callback = nullptr; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().BindDevice(packName, bindType, deviceId, bindParam, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -846,12 +849,9 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_101, testing::ext::TestSize std::string extra = ""; DmSubscribeInfo subscribeInfo; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, extra, callback); ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeInfo.subscribeId); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -871,12 +871,9 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_102, testing::ext::TestSize std::string extra = "{\"findDeviceMode\":1}"; DmSubscribeInfo subscribeInfo; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, extra, callback); ASSERT_EQ(ret, DM_OK); ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeInfo.subscribeId); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -897,12 +894,9 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_103, testing::ext::TestSize uint16_t subscribeId = 0; std::string filterOptions; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeId, filterOptions, callback); ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -925,6 +919,8 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_104, testing::ext::TestSize std::shared_ptr callback = std::make_shared(); DmDeviceInfo deviceInfo; callback->OnDeviceFound(subscribeId, deviceInfo); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeId, filterOptions, callback); ASSERT_NE(ret, DM_OK); } @@ -946,11 +942,8 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_101, testing::ext::TestSize. std::string extra = ""; DmSubscribeInfo subscribeInfo; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeInfo.subscribeId); ASSERT_NE(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -996,11 +989,8 @@ HWTEST_F(DeviceManagerImplTest, PublishDeviceDiscovery_101, testing::ext::TestSi std::string packName = "com.ohos.helloworld"; DmPublishInfo publishInfo; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().PublishDeviceDiscovery(packName, publishInfo, callback); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1018,11 +1008,8 @@ HWTEST_F(DeviceManagerImplTest, UnPublishDeviceDiscovery_101, testing::ext::Test std::string packName = "com.ohos.test"; int32_t publishId = 0; std::shared_ptr callback = std::make_shared(); - auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(packName, publishId); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1185,14 +1172,10 @@ HWTEST_F(DeviceManagerImplTest, InitDeviceManager_003, testing::ext::TestSize.Le // set dmInitCallback not null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy Init return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; // 3. call DeviceManagerImpl::InitDeviceManager with parameter int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1264,14 +1247,10 @@ HWTEST_F(DeviceManagerImplTest, UnInitDeviceManager_002, testing::ext::TestSize. // 1. set packName not null std::string packName = "com.ohos.test"; // 2. call DeviceManagerImpl::InitDeviceManager with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); + EXPECT_CALL(*ipcClientProxyMock_, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(packName); // 3. check ret is ERR_DM_FAILED ASSERT_EQ(ret, ERR_DM_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1311,14 +1290,10 @@ HWTEST_F(DeviceManagerImplTest, UnInitDeviceManager_004, testing::ext::TestSize. // 1. set packNamen not null std::string packName = "com.ohos.test"; // 2. call DeviceManagerImpl::InitDeviceManager with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); + EXPECT_CALL(*ipcClientProxyMock_, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(packName); // 3. check ret is ERR_DM_FAILED ASSERT_EQ(ret, ERR_DM_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1336,14 +1311,10 @@ HWTEST_F(DeviceManagerImplTest, UnInitDeviceManager_005, testing::ext::TestSize. // 1. set packName not null std::string packName = "com.ohos.test"; // 2. call DeviceManagerImpl::InitDeviceManager with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); + EXPECT_CALL(*ipcClientProxyMock_, UnInit(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(packName); // 3. check ret is ERR_DM_FAILED ASSERT_EQ(ret, ERR_DM_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1392,16 +1363,12 @@ HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_002, testing::ext::TestSize // set deviceList null std::vector deviceList; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_IPC_SEND_REQUEST_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); // 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, extra, deviceList); // 3. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1453,16 +1420,12 @@ HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_004, testing::ext::TestSize // set deviceList null std::vector deviceList; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, extra, deviceList); // 3. check ret is DEVICEMANAGER_IPC_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1552,6 +1515,8 @@ HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_008, testing::ext::TestSize int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); packName = "packNameTest"; + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); } @@ -1589,11 +1554,11 @@ HWTEST_F(DeviceManagerImplTest, ImportCredential_001, testing::ext::TestSize.Lev pkgName = "pkgNameTest"; ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); ASSERT_NE(ret, ERR_DM_TIME_OUT); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(3).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)) + .WillOnce(testing::Return(DM_OK)).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, DM_OK); ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); @@ -1665,9 +1630,6 @@ HWTEST_F(DeviceManagerImplTest, GenerateEncryptedUuid_001, testing::ext::TestSiz pkgName = "pkgNameTest"; ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); ASSERT_EQ(ret, DM_OK); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); ASSERT_EQ(ret, DM_OK); } @@ -1699,9 +1661,6 @@ HWTEST_F(DeviceManagerImplTest, GetNetworkTypeByNetworkId_001, testing::ext::Tes pkgName = "pkgNameTest"; ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); ASSERT_EQ(ret, DM_OK); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); ASSERT_EQ(ret, DM_OK); } @@ -1882,16 +1841,12 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo_002, testing::ext::TestSize.L // set extra null DmDeviceInfo info; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_IPC_SEND_REQUEST_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); // 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter int32_t ret = DeviceManager::GetInstance().GetLocalDeviceInfo(packName, info); // 3. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1940,16 +1895,12 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo_004, testing::ext::TestSize.L // set extra null DmDeviceInfo info; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter int32_t ret = DeviceManager::GetInstance().GetLocalDeviceInfo(packName, info); // 3. check ret is DEVICEMANAGER_IPC_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1970,16 +1921,12 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDeviceInfo_005, testing::ext::TestSize.L // set extra null DmDeviceInfo info; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter int32_t ret = DeviceManager::GetInstance().GetLocalDeviceInfo(packName, info); // 3. check ret is DEVICEMANAGER_IPC_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -2306,16 +2253,12 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_003, testing::ext::TestSize std::string extra = "test"; std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, extra, callback); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -2340,16 +2283,12 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_004, testing::ext::TestSize // set callback not null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); // 3. call DeviceManagerImpl::StartDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, extra, callback); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -2374,16 +2313,12 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_005, testing::ext::TestSize // set callback not null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::StartDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeInfo, extra, callback); // 4. check ret is DEVICEMANAGER_IPC_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -2481,9 +2416,6 @@ HWTEST_F(DeviceManagerImplTest, CreatePinHolder_001, testing::ext::TestSize.Leve payload.resize(10); ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); ASSERT_EQ(ret, DM_OK); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); ASSERT_EQ(ret, DM_OK); } @@ -2518,9 +2450,6 @@ HWTEST_F(DeviceManagerImplTest, DestoryPinHolder_001, testing::ext::TestSize.Lev payload.resize(10); ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); ASSERT_EQ(ret, DM_OK); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); ASSERT_EQ(ret, DM_OK); } @@ -2542,9 +2471,6 @@ HWTEST_F(DeviceManagerImplTest, DpAclAdd_001, testing::ext::TestSize.Level0) bindType = IDENTICAL_ACCOUNT; ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); ASSERT_EQ(ret, DM_OK); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); ASSERT_EQ(ret, DM_OK); } @@ -2583,74 +2509,58 @@ HWTEST_F(DeviceManagerImplTest, GetAllTrustedDeviceList_001, testing::ext::TestS ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); pkgName = "p*******lo"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); ret = DeviceManager::GetInstance().GetAllTrustedDeviceList(pkgName, extra, deviceList); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().GetAllTrustedDeviceList(pkgName, extra, deviceList); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, RegisterLocalServiceInfo_001, testing::ext::TestSize.Level0) { DMLocalServiceInfo info; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().RegisterLocalServiceInfo(info); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().RegisterLocalServiceInfo(info); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnRegisterLocalServiceInfo_001, testing::ext::TestSize.Level0) { std::string bundleName = "b*********kl"; int32_t pinExchangeType = 1; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().UnRegisterLocalServiceInfo(bundleName, pinExchangeType); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().UnRegisterLocalServiceInfo(bundleName, pinExchangeType); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UpdateLocalServiceInfo_001, testing::ext::TestSize.Level0) { DMLocalServiceInfo info; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().UpdateLocalServiceInfo(info); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().UpdateLocalServiceInfo(info); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetLocalServiceInfoByBundleNameAndPinExchangeType_001, testing::ext::TestSize.Level0) @@ -2658,21 +2568,17 @@ HWTEST_F(DeviceManagerImplTest, GetLocalServiceInfoByBundleNameAndPinExchangeTyp std::string bundleName = "b*********kl"; int32_t pinExchangeType = 1; DMLocalServiceInfo info; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(bundleName, pinExchangeType, info); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(bundleName, pinExchangeType, info); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index 05550beeb..21c5bdfbc 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -39,6 +39,7 @@ public: static inline std::shared_ptr deviceManagerNotifyMock_ = std::make_shared(); + static inline std::shared_ptr ipcClientProxyMock_ = std::make_shared(); }; class DeviceDiscoveryCallbackTest : public DiscoveryCallback { diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 952cbe49d..b09860eee 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -84,15 +84,11 @@ HWTEST_F(DeviceManagerImplTest, RequestCredential_002, testing::ext::TestSize.Le } )"; std::string returnJsonStr; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().RequestCredential(packName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -112,12 +108,15 @@ HWTEST_F(DeviceManagerImplTest, RequestCredential_003, testing::ext::TestSize.Le std::string reqJsonStr = R"( { "version":"1.0.0.1", - "userId":"4269DC28B639681698809A67EDAD08E39F207900038F91EFF95DD042FE2874E4" + "userId":"4269DC28B639681698809A67EDAD08E39F207900038F91EFF95DD042FE2874E4", + "CREDENTIAL_TYPE":"MINE", } )"; std::string returnJsonStr; std::shared_ptr callback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, callback); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RequestCredential(packName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, DM_OK); @@ -145,15 +144,11 @@ HWTEST_F(DeviceManagerImplTest, RequestCredential_004, testing::ext::TestSize.Le } )"; std::string returnJsonStr; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().RequestCredential(packName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -207,14 +202,10 @@ HWTEST_F(DeviceManagerImplTest, ImportCredential_002, testing::ext::TestSize.Lev ] } )"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().ImportCredential(packName, credentialInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -250,14 +241,10 @@ HWTEST_F(DeviceManagerImplTest, ImportCredential_003, testing::ext::TestSize.Lev ] } )"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().ImportCredential(packName, credentialInfo); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -293,14 +280,10 @@ HWTEST_F(DeviceManagerImplTest, ImportCredential_004, testing::ext::TestSize.Lev ] } )"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().ImportCredential(packName, credentialInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -336,14 +319,10 @@ HWTEST_F(DeviceManagerImplTest, DeleteCredential_002, testing::ext::TestSize.Lev { std::string packName = "com.ohos.test"; std::string deleteInfo = R"({"processType":1,"authType":1,"userId":"123"})"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().DeleteCredential(packName, deleteInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -361,14 +340,10 @@ HWTEST_F(DeviceManagerImplTest, DeleteCredential_003, testing::ext::TestSize.Lev { std::string packName = "com.ohos.test"; std::string deleteInfo = R"({"processType":1,"authType":1,"userId":"123"})"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().DeleteCredential(packName, deleteInfo); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -386,14 +361,10 @@ HWTEST_F(DeviceManagerImplTest, DeleteCredential_004, testing::ext::TestSize.Lev { std::string packName = "com.ohos.test"; std::string deleteInfo = R"({"processType":1,"authType":1,"userId":"123"})"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().DeleteCredential(packName, deleteInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -430,6 +401,8 @@ HWTEST_F(DeviceManagerImplTest, RegisterCredentialCallback_002, testing::ext::Te std::shared_ptr callback = std::make_shared(); std::shared_ptr initCallback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, initCallback); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RegisterCredentialCallback(packName, callback); ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().UnInitDeviceManager(packName); @@ -499,14 +472,10 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_001, testing::ext:: HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_002, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialCallback(packName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -523,14 +492,10 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_003, testing::ext:: { // 1. set packName null std::string packName = "com.ohos.test"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialCallback(packName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -547,6 +512,8 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_004, testing::ext:: std::string packName = "com.ohos.test"; std::shared_ptr callback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, callback); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialCallback(packName); ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().UnInitDeviceManager(packName); @@ -563,12 +530,8 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_004, testing::ext:: */ HWTEST_F(DeviceManagerImplTest, OnDmServiceDied_001, testing::ext::TestSize.Level0) { - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; int32_t ret = DeviceManagerImpl::GetInstance().OnDmServiceDied(); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -583,15 +546,11 @@ HWTEST_F(DeviceManagerImplTest, OnDmServiceDied_001, testing::ext::TestSize.Leve HWTEST_F(DeviceManagerImplTest, OnDmServiceDied_002, testing::ext::TestSize.Level0) { // 1. mock IpcClientProxy - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, OnDmServiceDied()).Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); + EXPECT_CALL(*ipcClientProxyMock_, OnDmServiceDied()).Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 2. call DeviceManagerImpl::OnDmServiceDied int32_t ret = DeviceManagerImpl::GetInstance().OnDmServiceDied(); // 3. check ret is DM_OK ASSERT_EQ(ret, ERR_DM_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -607,14 +566,10 @@ HWTEST_F(DeviceManagerImplTest, NotifyEvent_001, testing::ext::TestSize.Level0) std::string packName = "com.ohos.test"; int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; std::string event = R"({"extra": {"deviceId": "123"})"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().NotifyEvent(packName, eventId, event); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1192,14 +1147,10 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_301, testing::ext::TestSize.Level0) diff --git a/test/unittest/UTTest_device_manager_impl_two.cpp b/test/unittest/UTTest_device_manager_impl_two.cpp index ea0aa57f4..885ddbee1 100644 --- a/test/unittest/UTTest_device_manager_impl_two.cpp +++ b/test/unittest/UTTest_device_manager_impl_two.cpp @@ -82,19 +82,17 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_002, testing::ext::TestSize. { // 1. set packName not null std::string packName = "com.ohos.test"; - // set subscribeInfo is 0 - uint16_t subscribeId = 0; + // set subscribeInfo is 1 + uint16_t subscribeId = 1; + std::string pkgNameTemp = ComposeStr(packName, 1); + DeviceManagerImpl::GetInstance().pkgName2SubIdMap_[pkgNameTemp] = 10; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -112,20 +110,18 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_003, testing::ext::TestSize. { // 1. set packName not null std::string packName = "com.ohos.test"; - // set subscribeInfo is 0 - uint16_t subscribeId = 0; + // set subscribeInfo is 1 + uint16_t subscribeId = 1; + std::string pkgNameTemp = ComposeStr(packName, 1); + DeviceManagerImpl::GetInstance().pkgName2SubIdMap_[pkgNameTemp] = 10; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); std::shared_ptr callback = std::make_shared(); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -146,14 +142,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_004, testing::ext::TestSize. // set subscribeInfo is 0 uint16_t subscribeId = 0; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_NE(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -174,14 +166,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_005, testing::ext::TestSize. // set subscribeInfo is 0 uint16_t subscribeId = 0; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_NE(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -253,16 +241,12 @@ HWTEST_F(DeviceManagerImplTest, PublishDeviceDiscovery_003, testing::ext::TestSi DmPublishInfo publishInfo; std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::PublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().PublishDeviceDiscovery(packName, publishInfo, callback); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -286,16 +270,12 @@ HWTEST_F(DeviceManagerImplTest, PublishDeviceDiscovery_004, testing::ext::TestSi // set callback not null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); // 3. call DeviceManagerImpl::PublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().PublishDeviceDiscovery(packName, publishInfo, callback); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -319,16 +299,12 @@ HWTEST_F(DeviceManagerImplTest, PublishDeviceDiscovery_005, testing::ext::TestSi // set callback not null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - std::shared_ptr mockInstance = std::make_shared(); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::PublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().PublishDeviceDiscovery(packName, publishInfo, callback); // 4. check ret is DEVICEMANAGER_IPC_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -370,16 +346,12 @@ HWTEST_F(DeviceManagerImplTest, UnPublishDeviceDiscovery_002, testing::ext::Test // set subscribeInfo is 0 int32_t publishId = 0; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::UnPublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(packName, publishId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -400,16 +372,12 @@ HWTEST_F(DeviceManagerImplTest, UnPublishDeviceDiscovery_003, testing::ext::Test // set subscribeInfo is 0 int32_t publishId = 0; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); // 3. call DeviceManagerImpl::UnPublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(packName, publishId); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -430,16 +398,12 @@ HWTEST_F(DeviceManagerImplTest, UnPublishDeviceDiscovery_004, testing::ext::Test // set publishId is 0 int32_t publishId = 0; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::UnPublishDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(packName, publishId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -460,16 +424,12 @@ HWTEST_F(DeviceManagerImplTest, UnPublishDeviceDiscovery_005, testing::ext::Test // set publishId is 0 int32_t publishId = 0; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().UnPublishDeviceDiscovery(packName, publishId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -528,16 +488,12 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_002, testing::ext::TestSize.L // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(packName, authType, dmDeviceInfo, extra, callback); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -567,16 +523,12 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_003, testing::ext::TestSize.L // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(packName, authType, dmDeviceInfo, extra, callback); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -606,16 +558,12 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_004, testing::ext::TestSize.L // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(packName, authType, dmDeviceInfo, extra, callback); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -645,16 +593,12 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_005, testing::ext::TestSize.L // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(packName, authType, dmDeviceInfo, extra, callback); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -732,16 +676,12 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_003, testing::ext::TestSize // set callback null std::shared_ptr callback = nullptr; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -769,16 +709,12 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_004, testing::ext::TestSize deviceInfo.networkId[2] = '\0'; std::shared_ptr callback = nullptr; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -806,16 +742,12 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_005, testing::ext::TestSize deviceInfo.networkId[2] = '\0'; std::shared_ptr callback = nullptr; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::AuthenticateDevice with parameter int32_t ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -834,7 +766,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_001, testing::ext::TestSize.Lev std::string packName = ""; // set authParam null int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; // 2. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 3. check ret is ERR_DM_INPUT_PARA_INVALID @@ -858,18 +790,14 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_002, testing::ext::TestSize.Lev std::string packName = "com.ohos.test"; // set authParam null int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -889,7 +817,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_003, testing::ext::TestSize.Lev std::string packName = "com.ohos.test"; // set authParam null int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; // 2. MOCK IpcClientProxy SendRequest return DM_OK std::shared_ptr callback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); @@ -917,18 +845,14 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_004, testing::ext::TestSize.Lev std::string packName = "com.ohos.test"; // set authParam null int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -948,18 +872,14 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_005, testing::ext::TestSize.Lev std::string packName = "com.ohos.test"; // set authParam null int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1004,16 +924,12 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_002, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1035,17 +951,13 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUdidByNetworkId with parameter int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); // DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1067,16 +979,12 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_004, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1098,16 +1006,12 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_005, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1152,16 +1056,12 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_002, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1183,16 +1083,12 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUuidByNetworkId with parameter int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1214,16 +1110,12 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_004, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1245,16 +1137,12 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_005, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::SetUserOperation with parameter int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1297,15 +1185,11 @@ HWTEST_F(DeviceManagerImplTest, RegisterDeviceManagerFaCallback_002, testing::ex // set callback null std::shared_ptr callback = std::make_shared(); // 2. call DeviceManagerImpl::RegisterDeviceManagerFaCallback with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(packName, callback); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1407,15 +1291,11 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_002, testing:: // 1. set packName null std::string packName = "com.ohos.test"; // 2. call DeviceManagerImpl::RegisterDeviceManagerFaCallback with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(packName); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1440,10 +1320,7 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_003, testing:: // set callback not null std::shared_ptr callback = std::make_shared(); // 2. call DeviceManager RegisterDeviceManagerFaCallback with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); // 3. check ret is DM_OK @@ -1455,14 +1332,13 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_003, testing:: // 5. check checkMap not null ASSERT_NE(checkMap, nullptr); // 6. call DeviceManager UnRegisterDeviceManagerFaCallback with parameter - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); // 7. Get checkMap from pkgName checkMap = DeviceManagerNotify::GetInstance().dmUiCallback_[pkgName]; // 8 check checkMap null ASSERT_EQ(checkMap, nullptr); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1487,15 +1363,11 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_004, testing:: // set callback not null std::shared_ptr callback = std::make_shared(); // 2. call DeviceManager RegisterDeviceManagerFaCallback with parameter - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DM_OK)); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(testing::AtLeast(1)).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; // 4. set checkMap null std::shared_ptr checkMap = nullptr; // 5. Get checkMap from DeviceManagerNotify @@ -1595,14 +1467,10 @@ HWTEST_F(DeviceManagerImplTest, StopAuthenticateDevice_201, testing::ext::TestSi ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); pkgName = "pkgName"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().StopAuthenticateDevice(pkgName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, VerifyAuthentication_201, testing::ext::TestSize.Level0) @@ -1657,42 +1525,30 @@ HWTEST_F(DeviceManagerImplTest, RequestCredential_201, testing::ext::TestSize.Le std::string pkgName = "pkgName"; std::string reqJsonStr = "reqJsonStr"; std::string returnJsonStr = ""; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().RequestCredential(pkgName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, ImportCredential_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::string credentialInfo = "credentialInfo"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().ImportCredential(pkgName, credentialInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, DeleteCredential_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::string deleteInfo = "deleteInfo"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().DeleteCredential(pkgName, deleteInfo); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, RegisterCredentialCallback_201, testing::ext::TestSize.Level0) @@ -1709,14 +1565,10 @@ HWTEST_F(DeviceManagerImplTest, RegisterCredentialCallback_201, testing::ext::Te pkgName = "pkgName"; callback = std::make_shared(); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().RegisterCredentialCallback(pkgName, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_201, testing::ext::TestSize.Level0) @@ -1726,14 +1578,10 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback_201, testing::ext:: ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); pkgName = "pkgName"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().UnRegisterCredentialCallback(pkgName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, NotifyEvent_201, testing::ext::TestSize.Level0) @@ -1750,14 +1598,10 @@ HWTEST_F(DeviceManagerImplTest, NotifyEvent_201, testing::ext::TestSize.Level0) ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().NotifyEvent(pkgName, eventId, event); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, OnDmServiceDied_201, testing::ext::TestSize.Level0) @@ -1768,26 +1612,18 @@ HWTEST_F(DeviceManagerImplTest, OnDmServiceDied_201, testing::ext::TestSize.Leve HWTEST_F(DeviceManagerImplTest, CheckAPIAccessPermission_201, testing::ext::TestSize.Level0) { - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, CheckNewAPIAccessPermission_201, testing::ext::TestSize.Level0) { - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnBindDevice_201, testing::ext::TestSize.Level0) @@ -1795,14 +1631,10 @@ HWTEST_F(DeviceManagerImplTest, UnBindDevice_201, testing::ext::TestSize.Level0) std::string pkgName = "pkgName_201"; std::string deviceId = "deviceId201"; std::string extra = "extra"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().UnBindDevice(pkgName, deviceId, extra); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, ImportAuthCode_201, testing::ext::TestSize.Level0) @@ -1813,14 +1645,10 @@ HWTEST_F(DeviceManagerImplTest, ImportAuthCode_201, testing::ext::TestSize.Level ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); authCode = "123456"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, StartAdvertising_201, testing::ext::TestSize.Level0) @@ -1926,13 +1754,9 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_201, test DeviceManagerImpl::GetInstance().SyncCallbackToService(dmCommonNotifyEvent, pkgName); dmCommonNotifyEvent = DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); DeviceManagerImpl::GetInstance().SyncCallbackToService(dmCommonNotifyEvent, pkgName); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, RegisterSinkBindCallback_201, testing::ext::TestSize.Level0) @@ -1972,14 +1796,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceProfileInfoList_201, testing::ext::Test EXPECT_CALL(*deviceManagerNotifyMock_, RegisterGetDeviceProfileInfoListCallback(_, _)) .WillOnce(Return(DM_OK)); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().GetDeviceProfileInfoList(pkgName, filterOptions, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetDeviceProfileInfoList_202, testing::ext::TestSize.Level0) @@ -1990,14 +1810,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceProfileInfoList_202, testing::ext::Test std::make_shared(); EXPECT_CALL(*deviceManagerNotifyMock_, RegisterGetDeviceProfileInfoListCallback(_, _)) .WillOnce(Return(DM_OK)); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().GetDeviceProfileInfoList(pkgName, filterOptions, callback); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetDeviceIconInfo_201, testing::ext::TestSize.Level0) @@ -2012,14 +1828,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceIconInfo_201, testing::ext::TestSize.Le EXPECT_CALL(*deviceManagerNotifyMock_, RegisterGetDeviceIconInfoCallback(_, _, _)) .WillOnce(Return(DM_OK)); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); ret = DeviceManager::GetInstance().GetDeviceIconInfo(pkgName, filterOptions, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetDeviceIconInfo_202, testing::ext::TestSize.Level0) @@ -2029,27 +1841,19 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceIconInfo_202, testing::ext::TestSize.Le std::shared_ptr callback = std::make_shared(); EXPECT_CALL(*deviceManagerNotifyMock_, RegisterGetDeviceIconInfoCallback(_, _, _)) .WillOnce(Return(DM_OK)); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().GetDeviceIconInfo(pkgName, filterOptions, callback); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, StopAuthenticateDevice_202, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().StopAuthenticateDevice(pkgName); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnBindDevice_202, testing::ext::TestSize.Level0) @@ -2057,28 +1861,20 @@ HWTEST_F(DeviceManagerImplTest, UnBindDevice_202, testing::ext::TestSize.Level0) std::string pkgName = "pkgName_201"; std::string deviceId = "deviceId201"; std::string extra = "extra"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().UnBindDevice(pkgName, deviceId, extra); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnBindDevice_203, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName_201"; std::string deviceId = "deviceId201"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().UnBindDevice(pkgName, deviceId); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_201, testing::ext::TestSize.Level0) @@ -2087,15 +1883,11 @@ HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_201, testing::ext::Tes std::map discoverParam; std::map filterOptions; std::shared_ptr callback = std::make_shared(); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, discoverParam, filterOptions, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_202, testing::ext::TestSize.Level0) @@ -2104,15 +1896,11 @@ HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_202, testing::ext::Tes std::map discoverParam; std::map filterOptions; std::shared_ptr callback = std::make_shared(); - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, discoverParam, filterOptions, callback); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnRegisterDiscoveryCallback_201, testing::ext::TestSize.Level0) @@ -2120,14 +1908,10 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDiscoveryCallback_201, testing::ext::T std::string pkgName = "pkgName"; std::string pkgNameTemp = ComposeStr(pkgName, 0); DeviceManagerImpl::GetInstance().pkgName2SubIdMap_[pkgNameTemp] = 10; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, UnRegisterDiscoveryCallback_202, testing::ext::TestSize.Level0) @@ -2135,14 +1919,10 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDiscoveryCallback_202, testing::ext::T std::string pkgName = "pkgName"; std::string pkgNameTemp = ComposeStr(pkgName, 0); DeviceManagerImpl::GetInstance().pkgName2SubIdMap_[pkgNameTemp] = 10; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, StopAdvertising_201, testing::ext::TestSize.Level0) @@ -2150,14 +1930,10 @@ HWTEST_F(DeviceManagerImplTest, StopAdvertising_201, testing::ext::TestSize.Leve std::string packName = "pkgName"; std::map advertiseParam; advertiseParam[PARAM_KEY_PUBLISH_ID] = "10"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManager::GetInstance().StopAdvertising(packName, advertiseParam); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, StopAdvertising_202, testing::ext::TestSize.Level0) @@ -2165,42 +1941,30 @@ HWTEST_F(DeviceManagerImplTest, StopAdvertising_202, testing::ext::TestSize.Leve std::string packName = "pkgName"; std::map advertiseParam; advertiseParam[PARAM_KEY_PUBLISH_ID] = "10"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().StopAdvertising(packName, advertiseParam); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) { DmAccessCaller caller; DmAccessCallee callee; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INPUT_PARA_INVALID)); bool ret = DeviceManager::GetInstance().CheckIsSameAccount(caller, callee); ASSERT_FALSE(ret); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) { DmAccessCaller caller; DmAccessCallee callee; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); bool ret = DeviceManager::GetInstance().CheckIsSameAccount(caller, callee); ASSERT_TRUE(ret); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, SetDnPolicy_202, testing::ext::TestSize.Level0) @@ -2209,14 +1973,10 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy_202, testing::ext::TestSize.Level0) std::map policy; policy["policy01"] = "101"; policy["policy02"] = "102"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(pkgName, policy); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, SetDnPolicy_203, testing::ext::TestSize.Level0) @@ -2225,14 +1985,10 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy_203, testing::ext::TestSize.Level0) std::map policy; policy["policy01"] = "101"; policy["policy02"] = "102"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(pkgName, policy); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_201, testing::ext::TestSize.Level0) @@ -2249,14 +2005,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_202, testing::ext::TestSiz std::string pkgName = "pkgName"; std::string networkId = "networkId"; int32_t screenStatus = 1; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_203, testing::ext::TestSize.Level0) @@ -2264,14 +2016,10 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_203, testing::ext::TestSiz std::string pkgName = "pkgName"; std::string networkId = "networkId"; int32_t screenStatus = 1; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetNetworkIdByUdid_202, testing::ext::TestSize.Level0) @@ -2279,14 +2027,10 @@ HWTEST_F(DeviceManagerImplTest, GetNetworkIdByUdid_202, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::string udid = "udid"; std::string networkId = "networkId"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(DM_OK)); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) + .Times(testing::AtLeast(1)).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; std::map> callbackMap; DeviceManagerImpl::GetInstance().SyncCallbacksToService(callbackMap); @@ -2301,28 +2045,20 @@ HWTEST_F(DeviceManagerImplTest, PutDeviceProfileInfoList_201, testing::ext::Test { std::string pkgName = "pkgName"; std::vector deviceProfileInfoList; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().PutDeviceProfileInfoList(pkgName, deviceProfileInfoList); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, PutDeviceProfileInfoList_202, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::vector deviceProfileInfoList; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); int32_t ret = DeviceManager::GetInstance().PutDeviceProfileInfoList(pkgName, deviceProfileInfoList); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } HWTEST_F(DeviceManagerImplTest, GetLocalDisplayDeviceName_201, testing::ext::TestSize.Level0) @@ -2330,19 +2066,15 @@ HWTEST_F(DeviceManagerImplTest, GetLocalDisplayDeviceName_201, testing::ext::Tes std::string pkgName = "pkgName"; int32_t maxNameLength = 1; std::string displayName = "displayName"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().GetLocalDisplayDeviceName(pkgName, maxNameLength, displayName); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(testing::_, testing::_, testing::_)) .Times(1).WillOnce(testing::Return(DM_OK)); ret = DeviceManager::GetInstance().GetLocalDisplayDeviceName(pkgName, maxNameLength, displayName); ASSERT_EQ(ret, DM_OK); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index a9073b049..310b00c3b 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -61,6 +61,16 @@ void DeviceManagerServiceTest::SetUp() void DeviceManagerServiceTest::TearDown() { + Mock::VerifyAndClearExpectations(permissionManagerMock_.get()); + Mock::VerifyAndClearExpectations(softbusListenerMock_.get()); + Mock::VerifyAndClearExpectations(kVAdapterManagerMock_.get()); + Mock::VerifyAndClearExpectations(appManagerMock_.get()); + Mock::VerifyAndClearExpectations(deviceManagerServiceImplMock_.get()); + Mock::VerifyAndClearExpectations(softbusCacheMock_.get()); + Mock::VerifyAndClearExpectations(cryptoMock_.get()); + Mock::VerifyAndClearExpectations(multipleUserConnectorMock_.get()); + Mock::VerifyAndClearExpectations(dMCommToolMock_.get()); + Mock::VerifyAndClearExpectations(deviceProfileConnectorMock_.get()); } void DeviceManagerServiceTest::SetUpTestCase() @@ -281,15 +291,12 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; EXPECT_CALL(*multipleUserConnectorMock_, GetAccountInfoByUserId(_)).WillOnce(Return(dmAccountInfo)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(curMultiMap)); DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(curMultiMap)); DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)) - .WillOnce(Return(curMultiMap)).WillOnce(Return(curMultiMap)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, pkgName); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(curMultiMap)); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); @@ -768,7 +775,7 @@ HWTEST_F(DeviceManagerServiceTest, SetUserOperation_001, testing::ext::TestSize. DeletePermission(); std::string pkgName = "com.ohos.test"; int32_t action = 0; - const std::string param = "extra"; + const std::string param = "{\"test\": \"extra\"}";; int ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action, param); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } @@ -784,7 +791,7 @@ HWTEST_F(DeviceManagerServiceTest, SetUserOperation_002, testing::ext::TestSize. { std::string pkgName = ""; int32_t action = 0; - const std::string param = "extra"; + const std::string param = "{\"test\": \"extra\"}"; int ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action, param); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -816,7 +823,7 @@ HWTEST_F(DeviceManagerServiceTest, SetUserOperation_004, testing::ext::TestSize. { std::string pkgName = "pkgName"; int32_t action = 0; - const std::string param = "extra"; + const std::string param = R"({"test":"extra"})"; int ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action, param); EXPECT_EQ(ret, DM_OK); } @@ -1425,7 +1432,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_002, testing::ext::Te { std::string pkgName = "pkgName"; int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_003, testing::ext::TestSize.Level1) @@ -1447,7 +1454,7 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_002, testing::ext:: { std::string pkgName = "pkgName"; int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext::TestSize.Level1) @@ -1657,7 +1664,7 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_004, testing::ext:: std::string netWorkId = "netWorkId"; int32_t networkType = 0; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)).Times(::testing::AtLeast(2)) + EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)) .WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetNetworkTypeByNetworkId(pkgName, netWorkId, networkType); DeviceManagerService::GetInstance().softbusListener_ = nullptr; @@ -1731,8 +1738,6 @@ HWTEST_F(DeviceManagerServiceTest, StartDiscovering_003, testing::ext::TestSize. std::map discoverParam; std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); - EXPECT_CALL(*softbusListenerMock_, StopRefreshSoftbusLNN(_)).Times(::testing::AtLeast(1)) - .WillOnce(Return(SOFTBUS_NETWORK_NOT_INIT)); int32_t ret = DeviceManagerService::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions); EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == DM_OK || ret == SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL); ret = DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); @@ -1780,8 +1785,6 @@ HWTEST_F(DeviceManagerServiceTest, StopDiscovering_003, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::map discoverParam; DeviceManagerService::GetInstance().InitDMServiceListener(); - EXPECT_CALL(*softbusListenerMock_, StopRefreshSoftbusLNN(_)).Times(::testing::AtLeast(1)) - .WillOnce(Return(SOFTBUS_NETWORK_NOT_INIT)); int32_t ret = DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManagerService::GetInstance().UninitDMServiceListener(); @@ -1856,7 +1859,6 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::T std::string pkgName = "pkgName"; std::map extraParam; DeviceManagerService::GetInstance().InitDMServiceListener(); - EXPECT_CALL(*softbusListenerMock_, StopRefreshSoftbusLNN(_)).WillOnce(Return(SOFTBUS_NETWORK_NOT_INIT)); int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManagerService::GetInstance().UninitDMServiceListener(); @@ -2159,7 +2161,6 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).Times(::testing::AtLeast(2)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } @@ -2211,7 +2212,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level std::vector peerUdids; int32_t userId = 1; uint64_t tokenId = 87; - DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, USER); DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); @@ -2408,7 +2409,7 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_003, testing::ext::TestSiz std::string pkgName = "pkgName_003"; std::string udid = "sewdwed98897"; std::string networkId = "networkIdTest_003"; - EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)).Times(::testing::AtLeast(2)) + EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)) .WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index b8b947ac7..37672cddf 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -30,11 +30,16 @@ void DeviceManagerServiceImplTest::SetUp() deviceManagerServiceImpl_ = std::make_shared(); } deviceManagerServiceImpl_->Initialize(listener_); + auto session = std::make_shared(0, ""); + session->version_ = DM_VERSION_5_0_OLD_MAX; + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + deviceManagerServiceImpl_->InitAndRegisterAuthMgr(true, tokenId, session, 0); } const std::string testID("111111"); void DeviceManagerServiceImplTest::TearDown() { + Mock::VerifyAndClearExpectations(deviceProfileConnectorMock_.get()); } void DeviceManagerServiceImplTest::SetUpTestCase() @@ -69,7 +74,7 @@ void AddAccessControlProfileFirst(std::vector& accessContr int32_t userId = 123456; int32_t bindType = 4; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -120,7 +125,7 @@ void AddAccessControlProfileSecond(std::vector& accessCont int32_t userId = 123456; int32_t bindType = 1; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -171,7 +176,7 @@ void AddAccessControlProfileThird(std::vector& accessContr int32_t userId = 123456; int32_t bindType = 4; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -844,7 +849,7 @@ HWTEST_F(DeviceManagerServiceImplTest, SetUserOperation_001, testing::ext::TestS { std::string pkgName = ""; int32_t action = 1; - const std::string params = "params"; + const std::string params = R"({"test":"extra"})"; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -861,7 +866,7 @@ HWTEST_F(DeviceManagerServiceImplTest, SetUserOperation_002, testing::ext::TestS { std::string pkgName = "com.ohos.test"; int32_t action = 1; - const std::string params = "paramsTest"; + const std::string params = R"({"test":"extra"})"; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -1402,17 +1407,16 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::T HWTEST_F(DeviceManagerServiceImplTest, CheckDeleteCredential_001, testing::ext::TestSize.Level1) { std::string remoteUdid = "123456"; - int32_t remoteUserId = -1; std::vector profiles; AddAccessControlProfileFirst(profiles); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); std::vector profiles1; AddAccessControlProfileFirst(profiles1); remoteUdid = "666678"; EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles1)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); } HWTEST_F(DeviceManagerServiceImplTest, DeleteAlwaysAllowTimeOut_001, testing::ext::TestSize.Level1) @@ -1509,11 +1513,10 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); int32_t userId = 100; std::string accountId = "60008"; - std::vector peerUdids; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); - deviceManagerServiceImpl_->HandleUserRemoved(peerUdids, userId); + deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1566,7 +1569,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetBindLevel_101, testing::ext::TestSize. HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_101, testing::ext::TestSize.Level1) { - int32_t bindType = DM_INVALIED_BINDTYPE; + int32_t bindType = DM_INVALIED_TYPE; DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); EXPECT_EQ(authForm, DmAuthForm::INVALID_TYPE); } @@ -1662,7 +1665,6 @@ HWTEST_F(DeviceManagerServiceImplTest, CheckIsSameAccount_001, testing::ext::Tes deviceManagerServiceImpl_->Initialize(listener_); } std::vector profiles; - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); int ret = deviceManagerServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1677,7 +1679,6 @@ HWTEST_F(DeviceManagerServiceImplTest, CheckAccessControl_001, testing::ext::Tes deviceManagerServiceImpl_->Initialize(listener_); } std::vector profiles; - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); int ret = deviceManagerServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1702,7 +1703,6 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceScreenStatusChange_001, testi std::vector profiles; EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1756,12 +1756,10 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize. std::vector profiles; EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1780,14 +1778,12 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize std::map userIdAndBindLevel; userIdAndBindLevel[1] = INVALIED_TYPE; - userIdAndBindLevel[2] = DEVICE; + userIdAndBindLevel[2] = USER; userIdAndBindLevel[3] = SERVICE; userIdAndBindLevel[4] = APP; std::vector profiles; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); EXPECT_CALL(*deviceProfileConnectorMock_, GetUserIdAndBindLevel(_, _)).WillOnce(Return(userIdAndBindLevel)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()) - .WillOnce(Return(profiles)).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } @@ -1901,16 +1897,19 @@ HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::T EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + ProcessInfo processInfo; + processInfo.pkgName = "pkgName"; + dmOfflineParam.processVec.push_back(processInfo); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _, _)).WillOnce(Return(DM_INVALIED_TYPE)); deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); if (deviceManagerServiceImpl_->authMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } @@ -1941,7 +1940,6 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndBindLevel_001, testing::ext { int32_t userId = 123456; std::vector profiles; - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); auto ret = deviceManagerServiceImpl_->GetDeviceIdAndBindLevel(userId); EXPECT_TRUE(ret.empty()); } @@ -1950,7 +1948,6 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_002, testing::ext::T { int32_t localUserId = 123456; std::vector profiles; - EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); auto ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(localUserId); EXPECT_TRUE(ret.empty()); } @@ -1975,10 +1972,13 @@ HWTEST_F(DeviceManagerServiceImplTest, GetTokenIdByNameAndDeviceId_001, testing: std::string remoteUdid = "remoteDeviceId"; int32_t tokenId = 0; int32_t peerTokenId = 1; + ProcessInfo processInfo; DmOfflineParam dmOfflineParam; EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, peerTokenId); + processInfo.pkgName = "pkgName"; + dmOfflineParam.processVec.push_back(processInfo); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } @@ -2059,15 +2059,14 @@ HWTEST_F(DeviceManagerServiceImplTest, DeleteCredential_010, testing::ext::TestS deviceManagerServiceImpl_->DeleteAlwaysAllowTimeOut(); std::string remoteUdid = "remoteUdid"; - int32_t remoteUserId = -1; profiles.clear(); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); accessProfile.SetTrustDeviceId(remoteUdid); profiles.push_back(accessProfile); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 33ca98925..275518afe 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -60,6 +60,10 @@ void DeviceManagerServiceThreeTest::SetUp() void DeviceManagerServiceThreeTest::TearDown() { + Mock::VerifyAndClearExpectations(deviceManagerServiceMock_.get()); + Mock::VerifyAndClearExpectations(permissionManagerMock_.get()); + Mock::VerifyAndClearExpectations(softbusListenerMock_.get()); + Mock::VerifyAndClearExpectations(deviceManagerServiceImplMock_.get()); } void DeviceManagerServiceThreeTest::SetUpTestCase() @@ -298,7 +302,6 @@ HWTEST_F(DeviceManagerServiceThreeTest, BindTarget_301, testing::ext::TestSize.L EXPECT_EQ(ret, ERR_DM_NOT_INIT); bindParam.insert(std::make_pair(PARAM_KEY_META_TYPE, pkgName)); - EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(true)); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterResidentLoad()).WillOnce(Return(false)); ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); @@ -380,9 +383,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSi int32_t userId = 0; std::string accountId; std::string accountName; - EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterSoLoaded()).WillOnce(Return(false)); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); - EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterResidentLoad()).WillOnce(Return(false)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); int32_t curUserId = 0; @@ -479,6 +480,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, PutDeviceProfileInfoList_301, testing::e std::string pkgName = "pkgName"; std::vector deviceProfileInfoList; EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterResidentLoad()).WillOnce(Return(false)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidPutDeviceProfileInfoList(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().PutDeviceProfileInfoList(pkgName, deviceProfileInfoList); EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); } diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index dce554a66..72cb2c66d 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -521,12 +521,12 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level1 std::string value = "186"; bindParam.insert(std::make_pair(key, value)); int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_AUTH_OPEN_SESSION_FAILED); targetId.wifiIp = "178.168.1.2"; EXPECT_CALL(*softbusListenerMock_, GetIPAddrTypeFromCache(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_AUTH_OPEN_SESSION_FAILED); } HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Level1) @@ -768,16 +768,23 @@ HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ex JsonObject msgJsonObj; msgJsonObj["networkId"] = "networkId_001"; - msgJsonObj["discoverType"] = 0; + msgJsonObj["discoverType"] = 0b0100; + msgJsonObj["ischange"] = true; msg = msgJsonObj.Dump(); + std::vector foregroundUserVec; + foregroundUserVec.push_back(101); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(foregroundUserVec), Return(DM_OK))); EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); - EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))) - .WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(foregroundUserVec), Return(DM_OK))); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + Mock::VerifyAndClearExpectations(multipleUserConnectorMock_.get()); - msgJsonObj["discoverType"] = 1; + msgJsonObj["discoverType"] = 0; msg = msgJsonObj.Dump(); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); } @@ -1088,14 +1095,14 @@ HWTEST_F(DeviceManagerServiceTest, NotifyRemoteLocalUserSwitch_201, testing::ext std::vector backgroundUserIds; DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserIds, backgroundUserIds); - + peerUdids.push_back("peerUdid001"); peerUdids.push_back("peerUdid002"); DeviceManagerService::GetInstance().softbusListener_ = nullptr; DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserIds, backgroundUserIds); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); - + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)).Times(::testing::AtLeast(2)) .WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); @@ -1105,7 +1112,7 @@ HWTEST_F(DeviceManagerServiceTest, NotifyRemoteLocalUserSwitch_201, testing::ext EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)).Times(::testing::AtLeast(2)) .WillOnce(DoAll(SetArgReferee<1>("networkId"), Return(DM_OK))); - EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)).Times(::testing::AtLeast(2)) + EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)) .WillOnce(DoAll(SetArgReferee<1>(0), Return(ERR_DM_FAILED))); DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserIds, backgroundUserIds); @@ -1115,7 +1122,7 @@ HWTEST_F(DeviceManagerServiceTest, NotifyRemoteLocalUserSwitch_201, testing::ext EXPECT_CALL(*dMCommToolMock_, SendUserIds(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)).Times(::testing::AtLeast(2)) .WillOnce(DoAll(SetArgReferee<1>("networkId"), Return(DM_OK))); - EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)).Times(::testing::AtLeast(2)) + EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)) .WillOnce(DoAll(SetArgReferee<1>(1), Return(DM_OK))); DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserIds, backgroundUserIds); @@ -1123,7 +1130,7 @@ HWTEST_F(DeviceManagerServiceTest, NotifyRemoteLocalUserSwitch_201, testing::ext EXPECT_CALL(*softbusCacheMock_, GetNetworkIdFromCache(_, _)).Times(::testing::AtLeast(2)) .WillOnce(DoAll(SetArgReferee<1>("networkId"), Return(DM_OK))); - EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)).Times(::testing::AtLeast(2)) + EXPECT_CALL(*softbusListenerMock_, GetNetworkTypeByNetworkId(_, _)) .WillOnce(DoAll(SetArgReferee<1>(4), Return(DM_OK))); DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitch(curUserId, preUserId, peerUdids, foregroundUserIds, backgroundUserIds); @@ -1281,11 +1288,11 @@ HWTEST_F(DeviceManagerServiceTest, RegisterAuthenticationType_202, testing::ext: backgroundUserIds.push_back(102); msgJsonObj["discoverType"] = 1; msg = msgJsonObj.Dump(); - EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(_)) .WillOnce(DoAll(SetArgReferee<0>(foregroundUserIds), Return(DM_OK))); EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)) .WillOnce(DoAll(SetArgReferee<0>(backgroundUserIds), Return(DM_OK))); + EXPECT_CALL(*dMCommToolMock_, SendUserIds(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); } @@ -1336,6 +1343,7 @@ HWTEST_F(DeviceManagerServiceTest, PutDeviceProfileInfoList_202, testing::ext::T { std::string pkgName = "pkgName"; std::vector deviceProfileInfoList; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidPutDeviceProfileInfoList(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().PutDeviceProfileInfoList(pkgName, deviceProfileInfoList); EXPECT_TRUE(ret == ERR_DM_UNSUPPORTED_METHOD || ret == ERR_DM_INPUT_PARA_INVALID); } @@ -1448,8 +1456,9 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_202, testing::ext::TestSize.Lev EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)) .WillOnce(DoAll(SetArgReferee<1>("peerDeviceId"), Return(DM_OK))); EXPECT_CALL(*deviceProfileConnectorMock_, CheckDeviceInfoPermission(_, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnGetDeviceInfo(_)).WillOnce(Return(true)); EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, deviceInfo); EXPECT_EQ(ret, DM_OK); @@ -1491,7 +1500,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterLocalServiceInfo_201, testing::ext::T DeviceManagerService::GetInstance().hichainListener_ = std::make_shared(); DeviceManagerService::GetInstance().UpdateAclAndDeleteGroup(localUdid, deviceVec, foregroundUserIds, backgroundUserIds); - + std::string pkgName = "pkgName"; DeviceManagerService::GetInstance().ClearPublishIdCache(pkgName); DeviceManagerService::GetInstance().hichainListener_ = nullptr; @@ -1549,7 +1558,7 @@ HWTEST_F(DeviceManagerServiceTest, UpdateLocalServiceInfo_201, testing::ext::Tes EXPECT_CALL(*dMCommToolMock_, SendUserIds(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitchByWifi(localUdid, wifiDevices, foregroundUserIds, backgroundUserIds); - + GTEST_LOG_(INFO) << "NotifyRemoteLocalUserSwitchByWifi SendUserIds is ok" ; EXPECT_CALL(*dMCommToolMock_, SendUserIds(_, _, _)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().NotifyRemoteLocalUserSwitchByWifi(localUdid, wifiDevices, @@ -1697,7 +1706,7 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_202, testing::ext::TestSiz EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidModifyLocalDeviceName(_)).WillOnce(Return(false)); ret = DeviceManagerService::GetInstance().SetLocalDeviceName(pkgName, deviceName); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidModifyLocalDeviceName(_)).WillOnce(Return(true)); @@ -1727,7 +1736,7 @@ HWTEST_F(DeviceManagerServiceTest, SetRemoteDeviceName_202, testing::ext::TestSi EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidModifyRemoteDeviceName(_)).WillOnce(Return(false)); ret = DeviceManagerService::GetInstance().SetRemoteDeviceName(pkgName, deviceId, deviceName); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidModifyRemoteDeviceName(_)).WillOnce(Return(true)); @@ -1781,7 +1790,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceNetworkIdList_202, testing::ext::Tes int32_t stopUserId = 1; std::map deviceMap; EXPECT_CALL(*deviceProfileConnectorMock_, GetDeviceIdAndBindLevel(_, _)) - .Times(::testing::AtLeast(3)).WillRepeatedly(Return(deviceMap)); + .WillOnce(Return(deviceMap)); DeviceManagerService::GetInstance().InitDMServiceListener(); DeviceManagerService::GetInstance().HandleUserStopEvent(stopUserId); diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index ab8fb40a0..cecb212ce 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -26,10 +26,10 @@ std::vector DeviceProfileConnect } int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - const std::string &localUdid) + const std::string &localUdid, DmOfflineParam &offlineParam) { return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleDevUnBindEvent(remoteUserId, remoteUdid, - localUdid); + localUdid, offlineParam); } int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, @@ -125,9 +125,10 @@ int32_t DeviceProfileConnector::GetLocalServiceInfoByBundleNameAndPinExchangeTyp bundleName, pinExchangeType, serviceInfo); } -int32_t DeviceProfileConnector::PutSessionKey(const std::vector &sessionKeyArray, int32_t &sessionKeyId) +int32_t DeviceProfileConnector::PutSessionKey(int32_t userId, const std::vector &sessionKeyArray, + int32_t &sessionKeyId) { - return DmDeviceProfileConnector::dmDeviceProfileConnector->PutSessionKey(sessionKeyArray, sessionKeyId); + return DmDeviceProfileConnector::dmDeviceProfileConnector->PutSessionKey(userId, sessionKeyArray, sessionKeyId); } int32_t DeviceProfileConnector::PutLocalServiceInfo( diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index e02141369..5fa664674 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -29,7 +29,7 @@ public: public: virtual std::vector GetAllAccessControlProfile() = 0; virtual int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - const std::string &localUdid) = 0; + const std::string &localUdid, DmOfflineParam &offlineParam) = 0; virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) = 0; virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; @@ -56,7 +56,8 @@ public: virtual int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId) = 0; virtual int32_t GetLocalServiceInfoByBundleNameAndPinExchangeType(const std::string& bundleName, int32_t pinExchangeType, DistributedDeviceProfile::LocalServiceInfo &serviceInfo) = 0; - virtual int32_t PutSessionKey(const std::vector &sessionKeyArray, int32_t &sessionKeyId) = 0; + virtual int32_t PutSessionKey(int32_t userId, const std::vector &sessionKeyArray, + int32_t &sessionKeyId) = 0; virtual int32_t PutLocalServiceInfo(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo) = 0; virtual int32_t DeleteLocalServiceInfo(const std::string &bundleName, int32_t pinExchangeType) = 0; virtual int32_t UpdateLocalServiceInfo(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo) = 0; @@ -71,7 +72,7 @@ public: class DeviceProfileConnectorMock : public DmDeviceProfileConnector { public: MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); - MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &, DmOfflineParam &)); MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); @@ -94,7 +95,7 @@ public: MOCK_METHOD(int32_t, CheckDeviceInfoPermission, (const std::string &, const std::string &)); MOCK_METHOD(int32_t, GetLocalServiceInfoByBundleNameAndPinExchangeType, (const std::string&, int32_t, DistributedDeviceProfile::LocalServiceInfo &serviceInfo)); - MOCK_METHOD(int32_t, PutSessionKey, (const std::vector &, int32_t&)); + MOCK_METHOD(int32_t, PutSessionKey, (int32_t, const std::vector &, int32_t&)); MOCK_METHOD(int32_t, PutLocalServiceInfo, (const DistributedDeviceProfile::LocalServiceInfo &)); MOCK_METHOD(int32_t, DeleteLocalServiceInfo, (const std::string &, int32_t)); MOCK_METHOD(int32_t, UpdateLocalServiceInfo, (const DistributedDeviceProfile::LocalServiceInfo &)); diff --git a/test/unittest/mock/dm_auth_message_processor_mock.cpp b/test/unittest/mock/dm_auth_message_processor_mock.cpp new file mode 100644 index 000000000..8d5ce21ed --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_message_processor_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t userId, int32_t &skId) +{ + return DmAuthMessageProcessorMock::dmAuthMessageProcessorMock->SaveSessionKeyToDP(userId, skId); +} + +std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) +{ + return DmAuthMessageProcessorMock::dmAuthMessageProcessorMock->CreateMessage(msgType, context); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_message_processor_mock.h b/test/unittest/mock/dm_auth_message_processor_mock.h new file mode 100644 index 000000000..89a79689e --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 DM_AUTH_MESSAGE_PROCESSOR_MOCK_H +#define DM_AUTH_MESSAGE_PROCESSOR_MOCK_H + +#include +#include "dm_auth_message_processor.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthMessageProcessorMock { +public: + MOCK_METHOD(int32_t, SaveSessionKeyToDP, (int32_t, int32_t &)); + MOCK_METHOD(std::string, CreateMessage, (DmMessageType, std::shared_ptr)); + static inline std::shared_ptr dmAuthMessageProcessorMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.cpp b/test/unittest/mock/dm_auth_state_machine_mock.cpp new file mode 100644 index 000000000..49da4bfb2 --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "dm_auth_state_machine_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) +{ + return DmAuthStateMachineMock::dmAuthStateMachineMock->WaitExpectEvent(eventType); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.h b/test/unittest/mock/dm_auth_state_machine_mock.h new file mode 100644 index 000000000..9489d08fd --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 DM_AUTH_STATE_MACHINE_MOCK_H +#define DM_AUTH_STATE_MACHINE_MOCK_H + +#include +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachineMock { +public: + MOCK_METHOD(DmEventType, WaitExpectEvent, (DmEventType)); + static inline std::shared_ptr dmAuthStateMachineMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index 3a7a416c2..dd7f98ffb 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -19,9 +19,9 @@ namespace OHOS { namespace DistributedHardware { -bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) { - return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId, peerOsAccountId); + return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); } int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) @@ -29,11 +29,47 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthDevice(pinCode, osAccountId, udid, requestId); } -int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, - std::string publicKey) +int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) { - return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, peerOsAccountId, deviceId, - publicKey); + return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, deviceId, publicKey); } + +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ProcessCredData(authReqId, data); +} + +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AddCredential(osAccountId, authParams, creId); +} + +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); +} + +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, authParams, credId); +} + +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->DeleteCredential(osAccountId, creId); +} + +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredential(osAccountId, authReqId, credId, pinCode); +} + +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredentialPinCode(osAccountId, authReqId, pinCode); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index bdcd74fd6..d0de67f9e 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -26,19 +26,37 @@ class DmHiChainAuthConnector { public: virtual ~DmHiChainAuthConnector() = default; public: - virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) = 0; - virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) = 0; - virtual int32_t ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, - std::string publicKey) = 0; + virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId) = 0; + virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, + std::string udid, int64_t requestId) = 0; + virtual int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) = 0; + + virtual int32_t ProcessCredData(int64_t authReqId, const std::string &data) = 0; + virtual int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) = 0; + virtual int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) = 0; + virtual int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId) = 0; + virtual int32_t DeleteCredential(int32_t osAccountId, const std::string &creId) = 0; + virtual int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) = 0; + virtual int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) = 0; public: static inline std::shared_ptr dmHiChainAuthConnector = nullptr; }; class HiChainAuthConnectorMock : public DmHiChainAuthConnector { public: - MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t, int32_t)); + MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); MOCK_METHOD(int32_t, AuthDevice, (int32_t, int32_t, std::string, int64_t)); - MOCK_METHOD(int32_t, ImportCredential, (int32_t, int32_t, std::string, std::string)); + MOCK_METHOD(int32_t, ImportCredential, (int32_t, std::string, std::string)); + + MOCK_METHOD(int32_t, ProcessCredData, (int64_t, const std::string &)); + MOCK_METHOD(int32_t, AddCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, ExportCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, AgreeCredential, (int32_t, const std::string, const std::string &, std::string &)); + MOCK_METHOD(int32_t, DeleteCredential, (int32_t, const std::string &)); + MOCK_METHOD(int32_t, AuthCredential, (int32_t, int64_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, AuthCredentialPinCode, (int32_t, int64_t, int32_t)); }; } } diff --git a/test/unittest/mock/os_account_manager_mock.cpp b/test/unittest/mock/os_account_manager_mock.cpp index 50f194432..7a237c25e 100644 --- a/test/unittest/mock/os_account_manager_mock.cpp +++ b/test/unittest/mock/os_account_manager_mock.cpp @@ -41,5 +41,10 @@ ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &localId) { return IOsAccountManager::GetOrCreateOsAccountManager()->GetForegroundOsAccountLocalId(localId); } + +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId) +{ + return IOsAccountManager::GetOrCreateOsAccountManager()->GetForegroundOsAccountLocalId(displayId, localId); +} } // namespace AccountSA } // namespace OHOS diff --git a/test/unittest/mock/os_account_manager_mock.h b/test/unittest/mock/os_account_manager_mock.h index bbaedbb89..3575e978b 100644 --- a/test/unittest/mock/os_account_manager_mock.h +++ b/test/unittest/mock/os_account_manager_mock.h @@ -26,6 +26,7 @@ public: virtual ~IOsAccountManager() = default; virtual ErrCode GetForegroundOsAccountLocalId(int32_t &localId) = 0; + virtual ErrCode GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId) = 0; static std::shared_ptr GetOrCreateOsAccountManager(); static void ReleaseAccountManager(); private: @@ -35,6 +36,7 @@ private: class OsAccountManagerMock : public IOsAccountManager { public: MOCK_METHOD(ErrCode, GetForegroundOsAccountLocalId, (int32_t &)); + MOCK_METHOD(ErrCode, GetForegroundOsAccountLocalId, (const uint64_t, int32_t &)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/permission_manager_mock.cpp b/test/unittest/mock/permission_manager_mock.cpp index b6ce63c77..84d251e9d 100644 --- a/test/unittest/mock/permission_manager_mock.cpp +++ b/test/unittest/mock/permission_manager_mock.cpp @@ -54,5 +54,11 @@ bool PermissionManager::CheckProcessNameValidModifyRemoteDeviceName(const std::s { return DmPermissionManager::dmPermissionManager->CheckProcessNameValidModifyRemoteDeviceName(processName); } + +bool PermissionManager::CheckProcessNameValidPutDeviceProfileInfoList(const std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->CheckProcessNameValidPutDeviceProfileInfoList(processName); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h index 69879f418..ef8f53df8 100644 --- a/test/unittest/mock/permission_manager_mock.h +++ b/test/unittest/mock/permission_manager_mock.h @@ -33,6 +33,7 @@ public: virtual bool CheckProcessNameValidOnGetDeviceInfo(const std::string &processName) = 0; virtual bool CheckProcessNameValidModifyLocalDeviceName(const std::string &processName) = 0; virtual bool CheckProcessNameValidModifyRemoteDeviceName(const std::string &processName) = 0; + virtual bool CheckProcessNameValidPutDeviceProfileInfoList(const std::string &processName) = 0; public: static inline std::shared_ptr dmPermissionManager = nullptr; }; @@ -46,6 +47,7 @@ public: MOCK_METHOD(bool, CheckProcessNameValidOnGetDeviceInfo, (const std::string &)); MOCK_METHOD(bool, CheckProcessNameValidModifyLocalDeviceName, (const std::string &)); MOCK_METHOD(bool, CheckProcessNameValidModifyRemoteDeviceName, (const std::string &)); + MOCK_METHOD(bool, CheckProcessNameValidPutDeviceProfileInfoList, (const std::string &)); }; } } diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index 171311d9e..77c65ea49 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -39,5 +39,10 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device { return DmSoftbusConnector::dmSoftbusConnector->GetDeviceInfoByDeviceId(deviceId); } + +std::shared_ptr SoftbusConnector::GetSoftbusSession() +{ + return DmSoftbusConnector::dmSoftbusConnector->GetSoftbusSession(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index fa25cade0..a8caf1492 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -30,6 +30,7 @@ public: virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; virtual std::vector GetProcessInfo() = 0; virtual DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId) = 0; + virtual std::shared_ptr GetSoftbusSession(); public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -40,6 +41,7 @@ public: MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); MOCK_METHOD(std::vector, GetProcessInfo, ()); MOCK_METHOD(DmDeviceInfo, GetDeviceInfoByDeviceId, (const std::string &deviceId)); + MOCK_METHOD(std::shared_ptr, GetSoftbusSession, ()); }; } } diff --git a/test/unittest/mock/softbus_session_mock.cpp b/test/unittest/mock/softbus_session_mock.cpp index 1c657174e..c85d7045d 100644 --- a/test/unittest/mock/softbus_session_mock.cpp +++ b/test/unittest/mock/softbus_session_mock.cpp @@ -25,5 +25,20 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI return DmSoftbusSession::dmSoftbusSession->GetPeerDeviceId(sessionId, peerDevId); } +int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) +{ + return DmSoftbusSession::dmSoftbusSession->SendData(sessionId, message); +} + +int32_t SoftbusSession::OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSessionWithPara(deviceId, actionId, isEnable160m); +} + +int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSession(deviceId); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_session_mock.h b/test/unittest/mock/softbus_session_mock.h index 732174ef4..9f386d183 100644 --- a/test/unittest/mock/softbus_session_mock.h +++ b/test/unittest/mock/softbus_session_mock.h @@ -27,6 +27,10 @@ public: virtual ~DmSoftbusSession() = default; public: virtual int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) = 0; + virtual int32_t SendData(int32_t sessionId, std::string &message) = 0; + virtual int32_t OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) = 0; + virtual int32_t OpenAuthSession(const std::string &deviceId) = 0; + public: static inline std::shared_ptr dmSoftbusSession = nullptr; }; @@ -34,6 +38,9 @@ public: class SoftbusSessionMock : public DmSoftbusSession { public: MOCK_METHOD(int32_t, GetPeerDeviceId, (int32_t, std::string &)); + MOCK_METHOD(int32_t, SendData, (int32_t, std::string &)); + MOCK_METHOD(int32_t, OpenAuthSessionWithPara, (const std::string &, int32_t, bool)); + MOCK_METHOD(int32_t, OpenAuthSession, (const std::string &)); }; } } diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 6d2ec638d..015adfa62 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -245,7 +245,7 @@ EXPORT int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, EXPORT int32_t Crypto::ConvertUdidHashToAnoyDeviceId(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) { - LOGI("start."); + LOGD("start."); if (GetAnoyDeviceInfo(appId, udidHash, kvValue) == DM_OK) { return DM_OK; } @@ -254,7 +254,7 @@ EXPORT int32_t Crypto::ConvertUdidHashToAnoyDeviceId(const std::string &appId, int32_t Crypto::GetAnoyDeviceInfo(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) { - LOGI("start"); + LOGD("start"); std::string udidPrefix = appId + DB_KEY_DELIMITER + udidHash; if (KVAdapterManager::GetInstance().Get(udidPrefix, kvValue) != DM_OK) { LOGI("Get kv value from DB failed"); @@ -266,7 +266,7 @@ int32_t Crypto::GetAnoyDeviceInfo(const std::string &appId, const std::string &u int32_t Crypto::ConvertUdidHashToAnoyGenerate(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) { - LOGI("start."); + LOGD("start."); std::string salt = GetSecSalt(); std::string udidTemp = appId + DB_KEY_DELIMITER + udidHash + DB_KEY_DELIMITER + salt; char anoyDeviceId[DM_MAX_DEVICE_ID_LEN] = {0}; -- Gitee From d0c80a4ff9fbb860d80203390d917ff901430390 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 14 Apr 2025 17:38:57 +0800 Subject: [PATCH 02/38] =?UTF-8?q?=E4=BF=AE=E5=A4=8DUT=E3=80=81fuzz?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_manager_fuzzer.cpp | 10 +- .../on_data_received_fuzzer.cpp | 10 +- test/unittest/BUILD.gn | 1 + .../unittest/UTTest_auth_credential_state.cpp | 103 +++++++++--------- test/unittest/UTTest_auth_credential_state.h | 1 + .../UTTest_auth_message_processor.cpp | 1 - test/unittest/UTTest_auth_negotiate_state.cpp | 3 +- test/unittest/UTTest_auth_negotiate_state.h | 1 + test/unittest/UTTest_auth_pin_auth_state.cpp | 11 +- test/unittest/UTTest_auth_pin_auth_state.h | 1 + 10 files changed, 76 insertions(+), 66 deletions(-) diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp index 0858f3b67..018ed3697 100644 --- a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp @@ -55,11 +55,12 @@ void DmAuthSrcManagerFuzzTest(const uint8_t* data, size_t size) std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener = std::make_shared(); std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); FuzzedDataProvider fdp(data, size); std::string str(reinterpret_cast(data), size); int32_t bindLevel = fdp.ConsumeIntegral(); - std::shared_ptr authManager = std::make_shared(softbusConnector, listener, - hiChainAuthConnector); + std::shared_ptr authManager = std::make_shared(softbusConnector, hiChainConnector, + listener, hiChainAuthConnector); authManager->OnUserOperation(g_action, str); authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); @@ -87,11 +88,12 @@ void DmAuthSinkManagerFuzzTest(const uint8_t* data, size_t size) std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener = std::make_shared(); std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); FuzzedDataProvider fdp(data, size); std::string str(reinterpret_cast(data), size); int32_t bindLevel = fdp.ConsumeIntegral(); - std::shared_ptr authManager = std::make_shared(softbusConnector, listener, - hiChainAuthConnector); + std::shared_ptr authManager = std::make_shared(softbusConnector, hiChainConnector, + listener, hiChainAuthConnector); authManager->OnUserOperation(g_action, str); authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp index 6b1cec0cc..6ad3053b3 100644 --- a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp @@ -31,8 +31,9 @@ void OnDataReceivedSrcFuzzTest(const uint8_t* data, size_t size) std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener = std::make_shared(); std::shared_ptr hiChainAuthConnector = std::make_shared(); - std::shared_ptr authManager = std::make_shared(softbusConnector, listener, - hiChainAuthConnector); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, hiChainConnector, + listener, hiChainAuthConnector); FuzzedDataProvider fdp(data, size); int32_t sessionId = fdp.ConsumeIntegral(); std::string message(reinterpret_cast(data), size); @@ -50,8 +51,9 @@ void OnDataReceivedSinkFuzzTest(const uint8_t* data, size_t size) std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener = std::make_shared(); std::shared_ptr hiChainAuthConnector = std::make_shared(); - std::shared_ptr authManager = std::make_shared(softbusConnector, listener, - hiChainAuthConnector); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, hiChainConnector, + listener, hiChainAuthConnector); FuzzedDataProvider fdp(data, size); int32_t sessionId = fdp.ConsumeIntegral(); std::string message(reinterpret_cast(data), size); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index eba271921..6aaa00459 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1938,6 +1938,7 @@ ohos_unittest("UTTest_advertise_manager") { external_deps = [ "cJSON:cjson", + "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", diff --git a/test/unittest/UTTest_auth_credential_state.cpp b/test/unittest/UTTest_auth_credential_state.cpp index 519690d9b..bc555230e 100644 --- a/test/unittest/UTTest_auth_credential_state.cpp +++ b/test/unittest/UTTest_auth_credential_state.cpp @@ -52,6 +52,7 @@ void AuthCredentialStateTest::SetUp() softbusConnector = std::make_shared(); listener = std::make_shared(); hiChainAuthConnector = std::make_shared(); + hiChainConnector = std::make_shared(); } @@ -71,7 +72,7 @@ void AuthCredentialStateTest::TearDown() HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -80,7 +81,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_001, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -97,7 +98,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_002, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -113,7 +114,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_003, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -132,7 +133,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_004, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -152,7 +153,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_005, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_006, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -173,7 +174,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_006, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_007, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -194,7 +195,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_007, testing::e HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -203,7 +204,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_001, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -227,7 +228,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_002, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -240,7 +241,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_003, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -260,7 +261,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_004, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -277,7 +278,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_005, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_006, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -299,7 +300,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_006, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_007, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -319,7 +320,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_007, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_008, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -341,7 +342,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_008, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_009, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -365,7 +366,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_009, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -374,7 +375,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_001, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -397,7 +398,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_002, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -413,7 +414,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_003, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -430,7 +431,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_005, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_006, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -449,7 +450,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_006, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_007, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -470,7 +471,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_007, testing:: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_008, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -493,7 +494,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_008, testing:: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -502,7 +503,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_001, testing: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -522,7 +523,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_002, testing: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -535,7 +536,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_003, testing: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -550,7 +551,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_004, testing: HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -570,7 +571,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_005, testing: HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -579,7 +580,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_001, testi HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -599,7 +600,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_002, testi HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -612,7 +613,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_003, testi HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -627,7 +628,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_004, testi HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -647,7 +648,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_005, testi HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -656,7 +657,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_001, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -682,7 +683,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_002, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -695,7 +696,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_003, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -711,7 +712,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_004, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -733,7 +734,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_005, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_006, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -755,7 +756,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_006, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_007, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -781,7 +782,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_007, test HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_008, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -802,7 +803,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_008, test HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_001, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -811,7 +812,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_001, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_002, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -841,7 +842,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_002, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_003, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -854,7 +855,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_003, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_004, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -870,7 +871,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_004, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_005, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -887,7 +888,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_005, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_006, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -905,7 +906,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_006, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_007, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -925,7 +926,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_007, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_008, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -947,7 +948,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_008, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_009, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); @@ -973,7 +974,7 @@ HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_009, testing::e HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_0010, testing::ext::TestSize.Level1) { - authManager = std::make_shared(softbusConnector, listener, + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); std::shared_ptr authState = std::make_shared(); diff --git a/test/unittest/UTTest_auth_credential_state.h b/test/unittest/UTTest_auth_credential_state.h index ba2893051..0ca5fa31f 100644 --- a/test/unittest/UTTest_auth_credential_state.h +++ b/test/unittest/UTTest_auth_credential_state.h @@ -41,6 +41,7 @@ private: std::shared_ptr softbusConnector; std::shared_ptr listener; std::shared_ptr hiChainAuthConnector; + std::shared_ptr hiChainConnector; std::shared_ptr authManager; std::shared_ptr context; }; diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 21c03d7ce..21fd2b8de 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -29,7 +29,6 @@ namespace OHOS { namespace DistributedHardware { constexpr const char* TAG_APP_THUMBNAIL = "APPTHUM"; -constexpr const char* TAG_HOST = "HOST"; using namespace testing; using namespace testing::ext; diff --git a/test/unittest/UTTest_auth_negotiate_state.cpp b/test/unittest/UTTest_auth_negotiate_state.cpp index 5d276478c..b40df8fb6 100644 --- a/test/unittest/UTTest_auth_negotiate_state.cpp +++ b/test/unittest/UTTest_auth_negotiate_state.cpp @@ -49,7 +49,8 @@ void AuthNegotiateStateTest::SetUp() softbusConnector = std::make_shared(); listener = std::make_shared(); hiChainAuthConnector = std::make_shared(); - authManager = std::make_shared(softbusConnector, listener, + hiChainConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_negotiate_state.h b/test/unittest/UTTest_auth_negotiate_state.h index d385723bc..5b7aafe9c 100644 --- a/test/unittest/UTTest_auth_negotiate_state.h +++ b/test/unittest/UTTest_auth_negotiate_state.h @@ -38,6 +38,7 @@ private: std::shared_ptr softbusConnector; std::shared_ptr listener; std::shared_ptr hiChainAuthConnector; + std::shared_ptr hiChainConnector; std::shared_ptr authManager; std::shared_ptr context; std::shared_ptr softbusSession; diff --git a/test/unittest/UTTest_auth_pin_auth_state.cpp b/test/unittest/UTTest_auth_pin_auth_state.cpp index acd9376ee..c12e59660 100644 --- a/test/unittest/UTTest_auth_pin_auth_state.cpp +++ b/test/unittest/UTTest_auth_pin_auth_state.cpp @@ -43,7 +43,8 @@ void AuthPinAuthStateTest::SetUp() softbusConnector = std::make_shared(); listener = std::make_shared(); hiChainAuthConnector = std::make_shared(); - authManager = std::make_shared(softbusConnector, listener, + hiChainConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); context = authManager->GetAuthContext(); @@ -125,7 +126,7 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_001, testing::ext::Test HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::TestSize.Level1) { std::shared_ptr authState = std::make_shared(); - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) @@ -140,7 +141,7 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::Test HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_003, testing::ext::TestSize.Level1) { std::shared_ptr authState = std::make_shared(); - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) @@ -155,7 +156,7 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_003, testing::ext::Test HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::TestSize.Level1) { std::shared_ptr authState = std::make_shared(); - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) @@ -167,7 +168,7 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::Test HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_005, testing::ext::TestSize.Level1) { std::shared_ptr authState = std::make_shared(); - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authTypeList.push_back(DmAuthType::AUTH_TYPE_PIN); EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) diff --git a/test/unittest/UTTest_auth_pin_auth_state.h b/test/unittest/UTTest_auth_pin_auth_state.h index 6d4fee840..bef236cc1 100644 --- a/test/unittest/UTTest_auth_pin_auth_state.h +++ b/test/unittest/UTTest_auth_pin_auth_state.h @@ -37,6 +37,7 @@ private: std::shared_ptr softbusConnector; std::shared_ptr listener; std::shared_ptr hiChainAuthConnector; + std::shared_ptr hiChainConnector; std::shared_ptr authManager; std::shared_ptr context; }; -- Gitee From d82f030682765c552e9413c7f22f17004cdeaaab Mon Sep 17 00:00:00 2001 From: zhangyunrui6 Date: Mon, 14 Apr 2025 11:42:50 +0800 Subject: [PATCH 03/38] style:fix NUM_x Signed-off-by: zhangyunrui6 --- .../authentication_v2/dm_auth_context.h | 2 +- .../auth_stages/auth_confirm.cpp | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index e744a4163..5026b2642 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -176,7 +176,7 @@ struct DmAuthContext { DmMessageType msgType; int32_t sessionId; int64_t requestId; // HiChain authentication ID - int32_t authBoxType{1}; // Authentication box type + DMLocalServiceInfoAuthBoxType authBoxType{DMLocalServiceInfoAuthBoxType::STATE3}; // Authentication box type UiAction pinInputResult; // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) UiAction confirmOperation{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 4d201c719..421269c60 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -582,7 +582,8 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex LOGI("AuthSinkConfirmState::ReadServiceInfo found"); // ServiceInfo found context->serviceInfoFound = true; - context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType + // read authBoxType + context->authBoxType = static_cast(srvInfo.GetAuthBoxType()); if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { std::string pinCode = srvInfo.GetPinCode(); // read pincode if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { @@ -591,13 +592,13 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex srvInfo.SetPinCode("******"); DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(srvInfo); } - if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box + if (context->authBoxType == DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { // no authorization box int32_t confirmOperation = srvInfo.GetAuthType(); // read confirmOperation - if (confirmOperation == 0) { + if (confirmOperation == static_cast(DMLocalServiceInfoAuthType::TRUST_ONETIME)) { context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; - } else if (confirmOperation == OHOS::DistributedDeviceProfile::NUM_1) { + } else if (confirmOperation == static_cast(DMLocalServiceInfoAuthType::CANCEL)) { context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; - } else if (confirmOperation == OHOS::DistributedDeviceProfile::NUM_6) { + } else if (confirmOperation == static_cast(DMLocalServiceInfoAuthType::TRUST_ALWAYS)) { context->confirmOperation = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; } else { context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; @@ -607,11 +608,11 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { // only special scenarios can import pincode - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box + context->authBoxType = DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM; // no authorization box } else { // not special scenarios, reset confirmOperation to cancel context->confirmOperation = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box + context->authBoxType = DMLocalServiceInfoAuthBoxType::STATE3; // default: tristate box } } @@ -654,12 +655,12 @@ int32_t AuthSinkConfirmState::ProcessBindAuthorize(std::shared_ptrauthType); if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && (context->serviceInfoFound || AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) && - context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { + context->authBoxType == DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } - if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_1) { + if (context->authBoxType == DMLocalServiceInfoAuthBoxType::STATE3) { context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); if (ShowConfigDialog(context) != DM_OK) { LOGE("ShowConfigDialog failed"); -- Gitee From 3b3cd0fcd0f9a1f3d9bba02b36434b5ebaff478d Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 14 Apr 2025 19:35:57 +0800 Subject: [PATCH 04/38] modify imput letter error Signed-off-by: hwzhangchuang --- .../include/authentication_v2/dm_negotiate_process.h | 4 ++-- .../src/authentication_v2/dm_negotiate_process.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_negotiate_process.h b/services/implementation/include/authentication_v2/dm_negotiate_process.h index f8a21a9f0..8a5938d40 100644 --- a/services/implementation/include/authentication_v2/dm_negotiate_process.h +++ b/services/implementation/include/authentication_v2/dm_negotiate_process.h @@ -120,10 +120,10 @@ public: virtual ~ShareCredNoAclInputAuthType() {}; }; -class ShareCredNoAclImputAuthType : public NegotiateHandler { +class ShareCredNoAclImportAuthType : public NegotiateHandler { public: int32_t NegotiateHandle(std::shared_ptr context) override; - virtual ~ShareCredNoAclImputAuthType() {}; + virtual ~ShareCredNoAclImportAuthType() {}; }; class ShareCredShareAclInputAuthType : public NegotiateHandler { diff --git a/services/implementation/src/authentication_v2/dm_negotiate_process.cpp b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp index 8111934cf..f882e584a 100644 --- a/services/implementation/src/authentication_v2/dm_negotiate_process.cpp +++ b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp @@ -77,7 +77,7 @@ NegotiateProcess::NegotiateProcess() handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = std::make_unique(); handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = - std::make_unique(); + std::make_unique(); handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_INPUT_PINCODE)] = std::make_unique(); handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = @@ -232,7 +232,7 @@ int32_t ShareCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +int32_t ShareCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) { CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); return PinBindAndCredAuth(context); -- Gitee From f820c6712c11cf14048836a131f884fa63a3a1c6 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 14 Apr 2025 19:20:18 +0800 Subject: [PATCH 05/38] statemachine bugfix Signed-off-by: xw1997-clike <2247596987@qq.com> --- .../authentication_v2/dm_auth_state_machine.h | 4 ++ .../src/authentication_v2/auth_manager.cpp | 2 +- .../dm_auth_message_processor.cpp | 12 +++++ .../dm_auth_state_machine.cpp | 51 ++++++++++++------- 4 files changed, 49 insertions(+), 20 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 00a4c80e2..37ce83c8d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -84,7 +84,11 @@ private: bool CheckStateTransitValid(DmAuthStateType nextState); + void NotifyEventWait(); + void NotifyStateWait(); + DmAuthStateType curState_; + DmAuthStateType preState_{DmAuthStateType::AUTH_IDLE_STATE}; // Previous push state // State transition table for normal state transitions (all state transitions to the Finish state are valid) StateTransitionTable stateTransitionTable_; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7edf86dc6..4da2ce36d 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -145,7 +145,7 @@ AuthManager::~AuthManager() { if (context_ != nullptr) { context_->successFinished = true; - context_->authStateMachine = nullptr; // Release statemMachine + context_->authStateMachine->Stop(); // Stop statemMachine thread context_->timer->DeleteAll(); } bindParam_.clear(); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index bc87c07c6..d61305abb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -855,6 +855,12 @@ int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObj if (jsonObject[TAG_REASON].IsNumberInteger()) { context->reason = jsonObject[TAG_REASON].Get(); } + + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + if (context->reason != DM_OK) { + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -872,6 +878,12 @@ int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObje if (jsonObject[TAG_REASON].IsNumberInteger()) { context->reason = jsonObject[TAG_REASON].Get(); } + + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + if (context->reason != DM_OK) { + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 6cef7a6dc..f0520393c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -48,7 +48,6 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) DmAuthStateMachine::~DmAuthStateMachine() { Stop(); - thread_.join(); } void DmAuthStateMachine::InsertSrcTransTable() @@ -164,24 +163,33 @@ void DmAuthStateMachine::InsertSinkTransTable() // Notification status transition. The execution status corresponds to specific actions and exception handling. int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { + // The states after the finish status are illegal states. + if (preState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || + preState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + LOGE("DmAuthStateMachine::TransitionTo next state is invalid."); + return ERR_DM_NEXT_STATE_INVALID; + } + int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); { std::lock_guard lock(stateMutex_); if (this->CheckStateTransitValid(nextState)) { - LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", - statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", preState_, nextState); statesQueue_.push(state); + preState_ = nextState; } else { // The state transition is invalid. LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", - statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + preState_, nextState); ret = ERR_DM_NEXT_STATE_INVALID; reason = ERR_DM_NEXT_STATE_INVALID; if (direction_ == DM_AUTH_SOURCE) { statesQueue_.push(std::make_shared()); + preState_ = DmAuthStateType::AUTH_SRC_FINISH_STATE; } else { statesQueue_.push(std::make_shared()); + preState_ = DmAuthStateType::AUTH_SINK_FINISH_STATE; } } } @@ -298,14 +306,29 @@ std::optional> DmAuthStateMachine::FetchAndSetCurSt return state; } -void DmAuthStateMachine::Stop() +void DmAuthStateMachine::NotifyStateWait() { std::lock_guard lock(stateMutex_); // Use locking to prevent signal loss running_.store(false); stateCv_.notify_all(); +} + +void DmAuthStateMachine::NotifyEventWait() +{ + std::lock_guard lock(stateMutex_); // Use locking to prevent signal loss + running_.store(false); eventCv_.notify_all(); } +void DmAuthStateMachine::Stop() +{ + NotifyStateWait(); + NotifyEventWait(); + if (thread_.joinable()) { // Prevent dobule join + thread_.join(); + } +} + void DmAuthStateMachine::SetCurState(DmAuthStateType state) { LOGI("DmAuthStateMachine::SetCurState state: %{public}d", state); @@ -320,15 +343,8 @@ DmAuthStateType DmAuthStateMachine::GetCurState() // Verify the validity of the next state transition. bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) { - if (curState_ == nextState || curState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || - curState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { - return false; - } - - /* - Check whether the next state is AuthSrcFinishState or AuthSinkFinishState - which can directly switch to the state and return. - */ + // Check whether the next state is AuthSrcFinishState or AuthSinkFinishState + // which can directly switch to the state and return. if (direction_ == DM_AUTH_SOURCE) { if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE) { return true; @@ -338,12 +354,9 @@ bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) return true; } } + // Check whether the state transition table is met. - DmAuthStateType state = curState_; - if (!statesQueue_.empty()) { - state = statesQueue_.back()->GetStateType(); - } - auto it = stateTransitionTable_.find(state); + auto it = stateTransitionTable_.find(preState_); if (it != stateTransitionTable_.end()) { const std::set& allowedStates = it->second; return allowedStates.find(nextState) != allowedStates.end(); -- Gitee From 14a5b085d9d06b8b80aca643c325812bfbfd4db2 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Mon, 14 Apr 2025 20:09:10 +0800 Subject: [PATCH 06/38] modify compile error Signed-off-by: hwzhangchuang --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7edf86dc6..5d6181a3b 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -499,7 +499,7 @@ int32_t GetBindLevel(int32_t bindLevel) std::string processName = ""; int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { + if (ret == DM_OK && DmAuthState::CheckProcessNameInWhiteList(processName)) { return USER; } #endif -- Gitee From 0c00ef7cf72918e39129b106abac7adf9d123484 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 14 Apr 2025 20:24:16 +0800 Subject: [PATCH 07/38] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xw1997-clike <2247596987@qq.com> --- .../authentication_v2/dm_auth_state_machine.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index f0520393c..8756d054d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -163,17 +163,16 @@ void DmAuthStateMachine::InsertSinkTransTable() // Notification status transition. The execution status corresponds to specific actions and exception handling. int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { - // The states after the finish status are illegal states. - if (preState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || - preState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { - LOGE("DmAuthStateMachine::TransitionTo next state is invalid."); - return ERR_DM_NEXT_STATE_INVALID; - } - int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); { std::lock_guard lock(stateMutex_); + // The states after the finish status are illegal states. + if (preState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || + preState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + LOGE("DmAuthStateMachine::TransitionTo next state is invalid."); + return ERR_DM_NEXT_STATE_INVALID; + } if (this->CheckStateTransitValid(nextState)) { LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", preState_, nextState); statesQueue_.push(state); @@ -315,7 +314,7 @@ void DmAuthStateMachine::NotifyStateWait() void DmAuthStateMachine::NotifyEventWait() { - std::lock_guard lock(stateMutex_); // Use locking to prevent signal loss + std::lock_guard lock(eventMutex_); // Use locking to prevent signal loss running_.store(false); eventCv_.notify_all(); } -- Gitee From 0601c92a0e0c89eef5f1947b65d91d806d54ec62 Mon Sep 17 00:00:00 2001 From: BrainL Date: Mon, 14 Apr 2025 21:09:55 +0800 Subject: [PATCH 08/38] Ultrasonic PIN Signed-off-by: BrainL --- bundle.json | 3 +- services/implementation/BUILD.gn | 3 + .../authentication_v2/dm_auth_context.h | 8 +- .../authentication_v2/dm_auth_manager_base.h | 1 + .../dm_auth_message_processor.h | 20 +++ .../include/authentication_v2/dm_auth_state.h | 98 +++++++++++---- .../authentication_v2/dm_auth_state_machine.h | 2 + .../MSDP/spatial_location_callback_impl.h | 39 ++++++ .../src/authentication/dm_auth_manager.cpp | 2 +- .../src/authentication_v2/auth_manager.cpp | 15 ++- .../dm_auth_manager_base.cpp | 1 + .../dm_auth_message_processor.cpp | 117 +++++++++++++++++- .../dm_auth_state_machine.cpp | 46 +++++-- .../MSDP/spatial_location_callback_impl.cpp | 66 ++++++++++ 14 files changed, 379 insertions(+), 42 deletions(-) create mode 100644 services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h create mode 100644 services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp diff --git a/bundle.json b/bundle.json index 2f4868a16..0edbf8e3d 100644 --- a/bundle.json +++ b/bundle.json @@ -60,7 +60,8 @@ "wifi", "screenlock_mgr", "mbedtls", - "zlib" + "zlib", + "spatial_awareness" ], "third_party": [] }, diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 6ace5a13e..1972bb1c8 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -126,6 +126,7 @@ if (defined(ohos_lite)) { "include/dependency/multipleuser", "include/dependency/hichain", "include/dependency/softbus", + "include/dependency/MSDP", "include/i18n", "${common_path}/include", "${common_path}/include/dfx", @@ -205,6 +206,7 @@ if (defined(ohos_lite)) { "src/dependency/hichain/mine_hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", + "src/depemdency/MSDP/spatial_local_callback_impl.cpp", "src/device_manager_service_impl.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/i18n/dm_language_manager.cpp", @@ -253,6 +255,7 @@ if (defined(ohos_lite)) { "resource_management:resmgr_napi_core", "samgr:samgr_proxy", "zlib:shared_libz", + "spatial_awareness:spatial_awareness_client", ] if (support_screenlock && device_manager_feature_product == "default") { diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 5026b2642..794b55c57 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -49,8 +49,8 @@ enum DmAuthType : int32_t { AUTH_TYPE_NFC, AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code - AUTH_TYPE_UNKNOW, // Not used in the new protocol AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code + AUTH_TYPE_UNKNOW, // Not used in the new protocol }; enum DmAuthDirection { @@ -114,6 +114,11 @@ struct DmPeerTarget { DmPeerTargetAddress peerTargetAddress; }; +struct DmUltrasonicInfo{ + DM_Ultrasonic_Forward = 0; + DM_Ultrasonic_Reverse, +} + struct DmAccess { std::string deviceName; int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. @@ -210,6 +215,7 @@ struct DmAuthContext { DmAuthDirection direction; // Indicator of authentication direction ProcessInfo processInfo; DmPeerTarget peerTarget; + DmUltransonicInfo ultrasonicInfo; DmAccess accesser; DmAccess accessee; std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 49915a2c2..fb1707baa 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -97,6 +97,7 @@ extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; extern const int32_t CLONE_CONFIRM_TIMEOUT; extern const int32_t CLONE_NEGOTIATE_TIMEOUT; extern const int32_t CLONE_ADD_TIMEOUT; +extern const char* GET_ULTRALSONIC_PIN_TIMEOUT_TASK; extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4565b12df..f4264437e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -113,6 +113,11 @@ enum DmMessageType { MSG_TYPE_RESP_DATA_SYNC = 190, MSG_TYPE_AUTH_REQ_FINISH = 200, MSG_TYPE_AUTH_RESP_FINISH = 201, + MSG_TYPE_REVERSE_ULTRASONIC_START = 102, + MSG_TYPE_REVERSE_ULTRASONIC_DONE = 112, + MSG_TYPE_FORWARD_ULTRASONIC_START = 101, + MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE = 111, + MSG_TYPE_FORWARD_ULTRASONIC_DONE = 103, }; struct DmAccessControlTable { @@ -235,6 +240,16 @@ private: int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); // Parse the 201 message int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 102 message + int32_t ParseMessageReverseUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 112 message + int32_t ParseMessageReverseUltrasonicDone(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 101 message + int32_t ParseMessageForwardUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 111 message + int32_t ParseMessageForwardUltrasonicNegotiate(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 103 message + int32_t ParseMessageForwardUltrasonicDone(const JsonObject &jsonObject, std::shared_ptr context); // Create the 80 message int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); @@ -279,6 +294,11 @@ private: // Parse the sync message int32_t ParseSyncMessage(std::shared_ptr &context, DmAccess &access, JsonObject &jsonObject); + int32_t CreateMessageForwardUltrasonicStart(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageReverseUltrasonicStart(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageForwardUltrasonicNegotiate(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageReverseUltrasonicDone(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageForwardUltrasonicDone(std::shared_ptr context, JsonObject &jsonObject); std::string Base64Encode(std::string &inputStr); std::string Base64Decode(std::string &inputStr); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 896bd4cb2..1509f9bcf 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -44,16 +44,19 @@ enum class DmAuthStateType { AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message // or rollback or 90 jump AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN - AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 6, // Ultrasonic PIN negotiation - AUTH_SRC_PIN_AUTH_START_STATE = 7, // Start authentication and send 120 message. - AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 8, // Receive 130 authentication PIN result message, send 121 message - AUTH_SRC_PIN_AUTH_DONE_STATE = 9, // Receive 131 authentication PIN result message, call processData - AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 10, // Trigger the Onfinish callback event and send a 140 message - AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 11, // Received 150 encrypted messages, sent 160 messages - AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 12, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 13, // Received 170 credential authentication message, sent 161 message - AUTH_SRC_DATA_SYNC_STATE = 14, // Received 190 message, sent 200 message - AUTH_SRC_FINISH_STATE = 15, // Received 201 message + AUTH_SRC_REVERSE_ULTRASONIC_START_STATE = 6, + AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE = 7, + AUTH_SRC_FORWARD_ULTRASONIC_START_STATE = 8, + AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE = 9, + AUTH_SRC_PIN_AUTH_START_STATE = 10, // Start authentication and send 120 message. + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 11, // Receive 130 authentication PIN result message, send 121 message + AUTH_SRC_PIN_AUTH_DONE_STATE = 12, // Receive 131 authentication PIN result message, call processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 13, // Trigger the Onfinish callback event and send a 140 message + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 14, // Received 150 encrypted messages, sent 160 messages + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 15, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 16, // Received 170 credential authentication message, sent 161 message + AUTH_SRC_DATA_SYNC_STATE = 17, // Received 190 message, sent 200 message + AUTH_SRC_FINISH_STATE = 18, // Received 201 message // sink end state AUTH_SINK_START_STATE = 50, // Bus trigger OnSessionOpened @@ -61,17 +64,18 @@ enum class DmAuthStateType { AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN - AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 55, // Negotiate ultrasonic PIN status passive trigger or - // other status active migration to enter ultrasonic - AUTH_SINK_PIN_AUTH_START_STATE = 56, // Receive 120 authentication PIN message, send 130 message - AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 57, // Received 121 authentication PIN message, send 131 message - AUTH_SINK_PIN_AUTH_DONE_STATE = 58, // Trigger the Onfinish callback event - AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 59, // Received 140 encrypted messages, sent 150 messages - AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 60, // Receive 160 authentication message, send 170 message - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 61, // Received 161 credential negotiation message, - // reply with 171 message - AUTH_SINK_DATA_SYNC_STATE = 62, // Received 180 synchronization message, send 190 message - AUTH_SINK_FINISH_STATE = 63, // Received 200 end message, send 201 message + AUTH_SINK_REVERSE_ULTRASONIC_START_STATE = 55, + AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE = 56, + AUTH_SINK_FORWARD_ULTRASONIC_START_STATE = 57, + AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE = 58, + AUTH_SINK_PIN_AUTH_START_STATE = 59, // Receive 120 authentication PIN message, send 130 message + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 60, // Received 121 authentication PIN message, send 131 message + AUTH_SINK_PIN_AUTH_DONE_STATE = 61, // Trigger the Onfinish callback event + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 62, // Received 140 encrypted messages, sent 150 messages + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 63, // Receive 160 authentication message, send 170 message + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 64, // Received 161 credential negotiation message, + AUTH_SINK_DATA_SYNC_STATE = 65, // Received 180 synchronization message, send 190 message + AUTH_SINK_FINISH_STATE = 66, // Received 200 end message, send 201 message }; // Credential Addition Method @@ -162,7 +166,7 @@ protected: bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); }; -class AuthSrcConfirmState : public DmAuthState { +class AuthSrcConfirmState : public DmAuthState {tate : public DmAuthState { public: virtual ~AuthSrcConfirmState() {}; DmAuthStateType GetStateType() override; @@ -251,16 +255,58 @@ public: int32_t Action(std::shared_ptr context) override; }; -class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +class AuthSrcReverseUltrasonicStartState : public DmAuthState { public: - virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + virtual ~AuthSrcReverseUltrasonicStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; -class AuthSinkPinNegotiateUltrasonicPinState : public DmAuthState { +class AuthSrcReverseUltrasonicDoneState : public DmAuthState { public: - virtual ~AuthSinkPinNegotiateUltrasonicPinState() {}; +virtual ~AuthSrcReverseUltrasonicDoneState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AurhSrcForwardUltrasonicStartState : public DmAuthState { +public: +virtual ~AurhSrcForwardUltrasonicStartState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcForwardUltrasonicDoneState : public DmAuthState { +public: +virtual ~AuthSrcForwardUltrasonicDoneState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkReverseUltrasonicStartState : public DmAuthState { +public: +virtual ~AuthSinkReverseUltrasonicStartState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkReverseUltrasonicDoneState : public DmAuthState { +public: +virtual ~AuthSinkReverseUltrasonicDoneState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkForwardUltrasonicStartState : public DmAuthState { +public: +virtual ~AuthSinkForwardUltrasonicStartState() {}; +DmAuthStateType GetStateType() override; +int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkForwardUltrasonicDoneState : public DmAuthState { +public: +virtual ~AuthSinkForwardUltrasonicDoneState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 37ce83c8d..57f3a76d8 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -40,6 +40,8 @@ enum DmEventType { ON_REQUEST, ON_FINISH, ON_ERROR, + ON_ULTRASONIC_PIN_CHANGED, + ON_ULTRASONIC_PIN_TIMEOUT, ON_TIMEOUT, ON_USER_OPERATION, diff --git a/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h new file mode 100644 index 000000000..e79704e5d --- /dev/null +++ b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H + #define OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H + + #include "spatial_location_callback_stub.h" + #include "dm_auth_state.h" + #include "dm_auth_context.h" + #include "spatial_awareness_mgr_client.h" + + namespace OHOS { + namespace DistributedHardware { + class SpatialLocationCallbackImpl : public Msdp::SpatialLocationCallbackStub { + public: + SpatialLocationCallbackImpl(std::shared_ptr context); + ~SpatialLocationCallbackImpl(); + void OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) override; + + private: + bool IsValidPinCodeStr(const std::string &pinCodeStr); + std::shared_ptr context_ = nullptr; + }; + } // namespace DistributedHardware + } // namespace OHOS + + #endif // OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H \ No newline at end of file diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f56184951..185883aae 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -59,7 +59,7 @@ const int32_t MIN_PIN_TOKEN = 10000000; const int32_t MAX_PIN_TOKEN = 90000000; const int32_t MIN_PIN_CODE = 100000; const int32_t MAX_PIN_CODE = 999999; -const int32_t DM_AUTH_TYPE_MAX = 5; +const int32_t DM_AUTH_TYPE_MAX = 6; const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7816d9fba..0ff991f34 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -43,6 +43,8 @@ namespace { constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; +constexpr int32_t DM_ULTRASONIC_FORWARD = 0; +constexpr int32_t DM_ULTRASONIC_REVERSE = 1; int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) { @@ -462,6 +464,15 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); } + if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { + int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); + if (tempInfo == DM_ULTRASONIC_FORWARD ){ + context_->ultransonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + } else if (tempInfo == DM_ULTRASONIC_REVERSE) { + context_->ultransonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } + LOGI("ultrasonic side is %{public}d", context_->ultransonicInfo); + } ParseHmlInfoInJsonObject(jsonObject); return; } @@ -1005,7 +1016,9 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c JsonObject jsonObj; DmAuthStateType curState = context_->authStateMachine->GetCurState(); - if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE|| + curState == DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE) { int32_t pinCode = INVALID_PINCODE; if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 24d710867..32826d973 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -78,6 +78,7 @@ const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +const char* GET_ULTRALSONIC_PIN_TIMEOUT_TASK = "deviceManagerTimer:getUltrasonicPin"; const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d61305abb..336e5b5a3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -94,6 +94,7 @@ const char* TAG_IS_AUTHED = "isAuthed"; const char* TAG_CREDENTIAL_INFO = "credentialInfo"; const char* TAG_CERT_INFO = "certInfo"; const char* TAG_LANGUAGE = "language"; +const char* DM_TAG_ULTRASONIC_SIDE = "ultrasonicSide"; namespace { @@ -270,8 +271,12 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, - &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE,&DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START,&DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_DONE,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicDone}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, @@ -293,6 +298,11 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START,&DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_DONE,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicDone}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, @@ -559,6 +569,7 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.extraInfo; jsonObject[TAG_PEER_BUNDLE_NAME_V2] = context->accessee.bundleName; + jsonObject[TAG_ULTRASONIC_SIDE] = static_cast(context->ultrasonicSide); jsonObject[TAG_PEER_DISPLAY_ID] = context->accessee.displayId; jsonObject[TAG_PEER_PKG_NAME] = context->accessee.pkgName; @@ -936,6 +947,15 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_BUNDLE_NAME_V2].IsString()) { context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME_V2].Get(); } + if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { + int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); + if (tempInfo == DM_ULTRASONIC_FORWARD) { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + } else if (tempInfo == DM_ULTRASONIC_REVERSE) { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } + LOGI("DmAuthMessageProcessor::ParseNegotiateMessage ultrasonicInfo=%{public}d", context->ultrasonicInfo); + } if (jsonObject[TAG_EXTRA_INFO].IsString()) { context->accesser.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); } @@ -1050,6 +1070,17 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js if (json[TAG_DATA].IsString()) { context->transmitData = json[TAG_DATA].Get(); } + if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Reverse){ + LOGI("DmAuthMessageProcessor::ParseMessageReqPinAuthStart transmitDatao=%{public}s", + context->transmitData.c_str()); + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { + LOGI("DmAuthMessageProcessor::ParseMessageReqPinAuthStart transmitDatao=%{public}s", + context->transmitData.c_str()); + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + context->authStateMachine->TransitionTo(std::make_shared()); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -1075,6 +1106,53 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject return DM_OK; } +int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart(const JsonObject &json, + std::shared_ptr context) +{ + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_REPLY].IsNumber()) { + context->reply = json[TAG_REPLY].Get(); + } + if (context == DM_OK){ + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + context->authStateMachine->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart(const JsonObject &json, + std::shared_ptr context) +{ + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate(const JsonObject &json, + std::shared_ptr context) +{ + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicDone(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_REPLY].IsNumber()) { + context->reply = json[TAG_REPLY].Get(); + } + if (context != DM_OK){ + context->authStateMachine->TransitionTo(std::make_shared()); + } + return DM_OK; +} + int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[TAG_AUTH_TYPE] = context->authType; @@ -1121,6 +1199,41 @@ int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_pt return DM_OK; } +int32_t DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_REPLY] = context->reply; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_REPLY] = context->reply; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_REPLY] = context->reply; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_REPLY] = context->reply; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageForwardUltrasonicDone(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_REPLY] = context->reply; + return DM_OK; +} + void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) { auto message = CreateMessage(msgType, context); diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 8756d054d..bfb376ef9 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -30,6 +30,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) DmEventType::ON_TIMEOUT, DmEventType::ON_FAIL, // Authentication failed DmEventType::ON_SCREEN_LOCKED, + DmEventType::ON_ULTRASONIC_PIN_TIMEOUT, }; running_ = true; @@ -57,23 +58,35 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, + {DmAuthStateTyoe::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, { + DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, }}, + {DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_START_STATE, { + DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE, + }}, + {DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, - DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, + DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_START_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, }}, {DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, { DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, }}, - {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, - }}, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, { DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, @@ -121,16 +134,29 @@ void DmAuthStateMachine::InsertSinkTransTable() }}, {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, - DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_START_STATE, + DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_START_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, }}, - {DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, { - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + {DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_START_STATE, { + DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, - {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + {DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_START_STATE, { + DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE, DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, + {DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, { DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, diff --git a/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp new file mode 100644 index 000000000..7ec3d5ae4 --- /dev/null +++ b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "spatial_location_callback_impl.h" + #include "dm_auth_state.h" + #include "multiple_user_connector.h" + #include "dm_auth_state_machine.h" + + namespace OHOS { + namespace DistributedHardware { + constexpr int32_t pinCodeLength = 6; + + SpatialLocationCallbackImpl::SpatialLocationCallbackImpl(std::shared_ptr context) + { + LOGI("SpatialLocationCallbackImpl Init."); + context_ = context; + } + + SpatialLocationCallbackImpl::~SpatialLocationCallbackImpl() + { + LOGI("SpatialLocationCallbackImpl End."); + } + + void SpatialLocationCallbackImpl::OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) + { + LOGI("SpatialLocationCallbackImpl::OnPinCodeChanged Start."); + if (pinCodeResponse.pincode.length() != pinCodeLength) { + LOGE("OnPinCodeChanged pincode length error."); + return; + } + if (!IsValidPinCodeStr(pinCodeResponse.pincode)) { + LOGE("OnPinCodeChanged pincode is invalid, pinCode = %{public}s.", pinCodeResponse.pincode.c_str()); + return; + } + if (context_ == nullptr) { + LOGE("OnPinCodeChanged context_ empty."); + return; + } + int32_t pinCode = std::stoi(pinCodeResponse.pincode); + context_->pinCode = pinCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_CHANGED); + } + + bool SpatialLocationCallbackImpl::IsValidPinCodeStr(const std::string &pinCodeStr) + { + for (auto &digit : pinCodeStr) { + if (digit < '0' || digit > '9') { + return false; + } + } + return true; + } + } // namespace DistributedHardware + } // namespace OHOS \ No newline at end of file -- Gitee From 2248d7a4bfa7f25c3d8723b0eb93f5aa4cffae83 Mon Sep 17 00:00:00 2001 From: BrainL Date: Mon, 14 Apr 2025 21:35:31 +0800 Subject: [PATCH 09/38] modify Signed-off-by: BrainL --- services/implementation/BUILD.gn | 2 +- .../include/authentication_v2/dm_auth_context.h | 2 +- .../include/authentication_v2/dm_auth_manager_base.h | 2 +- .../authentication_v2/dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 6 +++--- .../src/authentication_v2/auth_manager.cpp | 6 +++--- .../src/authentication_v2/dm_auth_manager_base.cpp | 2 +- .../authentication_v2/dm_auth_message_processor.cpp | 10 ++++------ .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 9 files changed, 16 insertions(+), 17 deletions(-) diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 1972bb1c8..4dffb527f 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -206,7 +206,7 @@ if (defined(ohos_lite)) { "src/dependency/hichain/mine_hichain_connector.cpp", "src/dependency/softbus/softbus_connector.cpp", "src/dependency/softbus/softbus_session.cpp", - "src/depemdency/MSDP/spatial_local_callback_impl.cpp", + "src/dependency/MSDP/spatial_location_callback_impl.cpp", "src/device_manager_service_impl.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/i18n/dm_language_manager.cpp", diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 794b55c57..5c3f257e0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -215,7 +215,7 @@ struct DmAuthContext { DmAuthDirection direction; // Indicator of authentication direction ProcessInfo processInfo; DmPeerTarget peerTarget; - DmUltransonicInfo ultrasonicInfo; + DmUltrasonicInfo ultrasonicInfo; DmAccess accesser; DmAccess accessee; std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index fb1707baa..e6ae1f48c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -97,7 +97,7 @@ extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; extern const int32_t CLONE_CONFIRM_TIMEOUT; extern const int32_t CLONE_NEGOTIATE_TIMEOUT; extern const int32_t CLONE_ADD_TIMEOUT; -extern const char* GET_ULTRALSONIC_PIN_TIMEOUT_TASK; +extern const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK; extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index f4264437e..5e8a3b84e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -85,6 +85,7 @@ extern const char* TAG_IS_AUTHED; extern const char* TAG_CREDENTIAL_INFO; extern const char* TAG_CERT_INFO; extern const char* TAG_LANGUAGE; +extern const char* TAG_ULTRASONIC_SIDE; // Logical Session Tag constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 1509f9bcf..2f9fbf2eb 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -166,7 +166,7 @@ protected: bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); }; -class AuthSrcConfirmState : public DmAuthState {tate : public DmAuthState { +class AuthSrcConfirmState : public DmAuthState { public: virtual ~AuthSrcConfirmState() {}; DmAuthStateType GetStateType() override; @@ -269,9 +269,9 @@ DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; -class AurhSrcForwardUltrasonicStartState : public DmAuthState { +class AuthSrcForwardUltrasonicStartState : public DmAuthState { public: -virtual ~AurhSrcForwardUltrasonicStartState() {}; +virtual ~AuthSrcForwardUltrasonicStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 0ff991f34..cf8fa4017 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -467,11 +467,11 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); if (tempInfo == DM_ULTRASONIC_FORWARD ){ - context_->ultransonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; } else if (tempInfo == DM_ULTRASONIC_REVERSE) { - context_->ultransonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; } - LOGI("ultrasonic side is %{public}d", context_->ultransonicInfo); + LOGI("ultrasonic side is %{public}d", context_->ultrasonicInfo); } ParseHmlInfoInJsonObject(jsonObject); return; diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 32826d973..7afd5ea30 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -78,7 +78,7 @@ const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -const char* GET_ULTRALSONIC_PIN_TIMEOUT_TASK = "deviceManagerTimer:getUltrasonicPin"; +const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK = "deviceManagerTimer:getUltrasonicPin"; const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 336e5b5a3..d37e7c56a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1081,8 +1081,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js } else { context->authStateMachine->TransitionTo(std::make_shared()); } - - context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -1116,10 +1114,10 @@ int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart(const JsonObj int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone(const JsonObject &json, std::shared_ptr context) { - if (json[TAG_REPLY].IsNumber()) { + if (json[TAG_REPLY].IsNumberInteger()) { context->reply = json[TAG_REPLY].Get(); } - if (context == DM_OK){ + if (context->reply == DM_OK){ context->authStateMachine->TransitionTo(std::make_shared()); } else { context->authStateMachine->TransitionTo(std::make_shared()); @@ -1144,10 +1142,10 @@ int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate(const Jso int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicDone(const JsonObject &json, std::shared_ptr context) { - if (json[TAG_REPLY].IsNumber()) { + if (json[TAG_REPLY].IsNumberInteger()) { context->reply = json[TAG_REPLY].Get(); } - if (context != DM_OK){ + if (context->reply != DM_OK){ context->authStateMachine->TransitionTo(std::make_shared()); } return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index bfb376ef9..d40420143 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -58,7 +58,7 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, - {DmAuthStateTyoe::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, { + {DmAuthStattType::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, { DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, -- Gitee From 90f046854697b19a78c9cdc1093281ae010a51d3 Mon Sep 17 00:00:00 2001 From: BrainL Date: Mon, 14 Apr 2025 22:15:34 +0800 Subject: [PATCH 10/38] modify Signed-off-by: BrainL --- .../include/device_manager_service_impl.h | 1 + .../src/device_manager_service_impl.cpp | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 8365fe874..4353822b4 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -204,6 +204,7 @@ private: const std::map &bindParam); std::shared_ptr GetConfigByTokenId(); int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); + int32_t ChangeUltrasonicTypeToPin(std::map &bindParam); std::shared_ptr GetAuthMgrByMessage(int32_t msgType, uint64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 02f43f706..1cb4daad4 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -54,10 +54,12 @@ constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; constexpr int32_t AUTH_SRC_FINISH_STATE = 12; constexpr int32_t MAX_DATA_LEN = 65535; +constexpr int32_t ULTRASONIC_AUTHTYPE = 6; constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; +constexpr const char* CHANGE_PINTYPE = "1"; // currently, we just support one bind session in one device at same time constexpr size_t MAX_NEW_PROC_SESSION_COUNT_TEMP = 1; @@ -844,6 +846,12 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr curSession->logicalSessionSet_.insert(0); curSession->logicalSessionCnt_.fetch_add(1); authMgr->OnSessionDisable(); + } else if (authType == ULTRASONIC_AUTHTYPE) { + int32_t ret = ChangeUltrasonicTypeToPin(bindParam); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr ChangeUltrasonicTypeToPin failed."); + return ret; + } } else { authMgr_->DisableInsensibleSwitching(); // send stop message @@ -872,6 +880,18 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr return DM_OK; } +int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + iter->second = CHANGE_PINTYPE; + LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bind param %{public}s change to PIN_TYPE.", PARAM_KEY_AUTH_TYPE); + return DM_OK; +} + int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject, std::shared_ptr curSession) { -- Gitee From e8eb9dce6bd01195cc1c39ed2207974beef62ad1 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 09:10:32 +0800 Subject: [PATCH 11/38] modify Signed-off-by: BrainL --- .../include/authentication_v2/dm_auth_state.h | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 2f9fbf2eb..23f68131b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -264,49 +264,49 @@ public: class AuthSrcReverseUltrasonicDoneState : public DmAuthState { public: -virtual ~AuthSrcReverseUltrasonicDoneState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSrcReverseUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSrcForwardUltrasonicStartState : public DmAuthState { public: -virtual ~AuthSrcForwardUltrasonicStartState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSrcForwardUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSrcForwardUltrasonicDoneState : public DmAuthState { public: -virtual ~AuthSrcForwardUltrasonicDoneState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSrcForwardUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSinkReverseUltrasonicStartState : public DmAuthState { public: -virtual ~AuthSinkReverseUltrasonicStartState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSinkReverseUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSinkReverseUltrasonicDoneState : public DmAuthState { public: -virtual ~AuthSinkReverseUltrasonicDoneState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSinkReverseUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSinkForwardUltrasonicStartState : public DmAuthState { public: -virtual ~AuthSinkForwardUltrasonicStartState() {}; -DmAuthStateType GetStateType() override; -int32_t Action(std::shared_ptr context) override; + virtual ~AuthSinkForwardUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; class AuthSinkForwardUltrasonicDoneState : public DmAuthState { public: -virtual ~AuthSinkForwardUltrasonicDoneState() {}; + virtual ~AuthSinkForwardUltrasonicDoneState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; -- Gitee From 797ba66d737f456d1ce09db3138f90214292b4be Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 10:03:39 +0800 Subject: [PATCH 12/38] modify Signed-off-by: BrainL --- .../dm_auth_message_processor.h | 4 - .../auth_stages/auth_pin_auth.cpp | 254 +++++++++++++++++- .../dm_auth_message_processor.cpp | 21 -- 3 files changed, 244 insertions(+), 35 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5e8a3b84e..4810d4a6a 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -118,7 +118,6 @@ enum DmMessageType { MSG_TYPE_REVERSE_ULTRASONIC_DONE = 112, MSG_TYPE_FORWARD_ULTRASONIC_START = 101, MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE = 111, - MSG_TYPE_FORWARD_ULTRASONIC_DONE = 103, }; struct DmAccessControlTable { @@ -249,8 +248,6 @@ private: int32_t ParseMessageForwardUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); // Parse the 111 message int32_t ParseMessageForwardUltrasonicNegotiate(const JsonObject &jsonObject, std::shared_ptr context); - // Parse the 103 message - int32_t ParseMessageForwardUltrasonicDone(const JsonObject &jsonObject, std::shared_ptr context); // Create the 80 message int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); @@ -299,7 +296,6 @@ private: int32_t CreateMessageReverseUltrasonicStart(std::shared_ptr context, JsonObject &jsonObject); int32_t CreateMessageForwardUltrasonicNegotiate(std::shared_ptr context, JsonObject &jsonObject); int32_t CreateMessageReverseUltrasonicDone(std::shared_ptr context, JsonObject &jsonObject); - int32_t CreateMessageForwardUltrasonicDone(std::shared_ptr context, JsonObject &jsonObject); std::string Base64Encode(std::string &inputStr); std::string Base64Decode(std::string &inputStr); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index f53c7162e..970d3a15d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -28,11 +28,14 @@ #include "hichain_auth_connector.h" #include "multiple_user_connector.h" #include "service_info_profile.h" +#include "spatial_location_callback_impl.h" +#include "spatial_awareness_mgr_client.h" namespace OHOS { namespace DistributedHardware { constexpr int32_t MAX_AUTH_INPUT_PIN_FAIL_TIMES = 3; +constexpr int32_t GET_ULTRASONIC_PIN_TIMEOUT = 4; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; constexpr const char* UNVALID_CREDTID = "invalidCredId"; @@ -204,6 +207,9 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c { LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (context->authtype == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { + context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); + } if (ret != DM_OK) { LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err."); return ret; @@ -362,8 +368,10 @@ int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptrauthType == DmAuthType::AUTH_TYPE_PIN) { context->authStateMachine->TransitionTo(std::make_shared()); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && + context->ultrasonicInfo == DM_Ultrasonic_Forward) { + LOGI("AuthSrcPinNegotiateStartState ultrasonic forward"); + context->authStateMachine->TransitionTo(std::make_shared()); } else { LOGE("authType not support"); return ERR_DM_FAILED; @@ -457,6 +465,8 @@ int32_t AuthSrcPinNegotiateStartState::ProcessPinBind(std::shared_ptrauthType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC){ + return NegotiatePinAuth(context, false); } else { return NegotiatePinAuth(context, false); } @@ -575,24 +585,248 @@ int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) return DM_OK; } -DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() +DmAuthStateType AuthSrcReverseUltrasonicStartState::GetStateType() { - return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; + return DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE; } -int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + LOGI("AuthSrcReverseUltrasonicStartState::Action start"); + context->timer->StartTImer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), + GET_ULTRASONIC_PIN_TIMEOUT,[context](std::stringname){ + LOGI("AuthSrcReverseUltrasonicStartState::Action timeout"); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK + }); + //gen pin + context=>pinCode=GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + LOGI("AuthSrcReverseUltrasonicStartState::Action gen pin code %{public}d", context->pinCode); + //set pincode + std::string ultraPinCode = std::to_string(context->pinCode); + Msdp::SpatiaAwarenessMgrClient::GetInstance().SerPinCode(ultraPincode); + //send 102 + context->reply = DM_OK; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_START, context); + LOGI("AuthSrcReverseUltrasonicStartState::Action send 102 msg done"); + return DM_OK } -DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() +DmAuthStateType AuthSrcReverseUltrasonicDoneState::GetStateType() { - return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; + return DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE; } -int32_t AuthSinkPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +int32_t AuthSrcReverseUltrasonicDoneState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + LOGI("AuthSrcReverseUltrasonicDoneState::Action start"); + // sink从msdp接受成功 + LOGI("AuthSrcReverseUltrasonicDoneState::Action Start."); + context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, + context->pinCode); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + return DM_OK; + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcReverseUltrasonicDoneState::AuthDevice ON_ERROR failed."); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + return STOP_BIND; +} + +DmAuthStateType AuthSrcForwardUltrasonicStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_START_STATE; +} + +int32_t AuthSrcForwardUltrasonicStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcForwardUltrasonicStartState::Action Start."); + // 发送101报文 + context->reply = DM_OK; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_START, context); + LOGI("AuthSrcForwardUltrasonicStartState::Action End."); + return DM_OK; +} + +DmAuthStateType AuthSrcForwardUltrasonicDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE; +} + +int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcForwardUltrasonicDoneState::Action Start."); + // 1.启动5s计时器 若到则切换至常规pin流程 + context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), + GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { + LOGI("AuthSrcForwardUltrasonicDoneState timeout."); + Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + }); + // 2.从MSDP接口拿到pin并取消监听 + sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); + Msdp::SpatialAwarenessMgrClient::GetInstance().RegisterPinCallback(callback); + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_ULTRASONIC_PIN_CHANGED); + if (retEvent == DmEventType::ON_ULTRASONIC_PIN_CHANGED) { + Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); + context->reply = DM_OK; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_DONE, context); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, + context->pinCode); + if (ret != DM_OK) { + LOGE("OnPinCodeChanged failed."); + return STOP_BIND; + } + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + LOGI("OnPinCodeChanged ON_TRANSMIT."); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + return DM_OK; + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("OnPinCodeChanged ON_ERROR failed."); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + } + return STOP_BIND; +} + +DmAuthStateType AuthSinkReverseUltrasonicStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_START_STATE; +} + +int32_t AuthSinkReverseUltrasonicStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkReverseUltrasonicStartState::Action Start."); + // 1.启动5s计时器 若到则切换至常规pin流程 + context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), + GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { + LOGI("AuthSinkReverseUltrasonicStartState timeout."); + Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + }); + // 2.从MSDP接口拿到pin并取消监听 + sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); + Msdp::SpatialAwarenessMgrClient::GetInstance().RegisterPinCallback(callback); + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_ULTRASONIC_PIN_CHANGED); + if (retEvent == DmEventType::ON_ULTRASONIC_PIN_CHANGED) { + Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); + context->reply = DM_OK; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_DONE, context); + LOGI("OnPinCodeChanged End."); + return DM_OK; + } + return STOP_BIND; +} + +DmAuthStateType AuthSinkReverseUltrasonicDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE; +} + +int32_t AuthSinkReverseUltrasonicDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkReverseUltrasonicDoneState::Action Start."); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); + context->pinNegotiateStarted = true; + LOGI("AuthSinkReverseUltrasonicDoneState::Action context->transmitData = %{public}s.", context->transmitData.c_str()); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送130报文 + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_TRANSMIT."); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); + // src侧在hichain中认证成功与否都发送120 sink侧与src侧的认证结果应当一致,故这里不需要再发130给src + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + return STOP_BIND; +} + +DmAuthStateType AuthSinkForwardUltrasonicStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_START_STATE; +} + +int32_t AuthSinkForwardUltrasonicStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkForwardUltrasonicStartState::Action Start."); + context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), + GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { + LOGI("AuthSinkForwardUltrasonicStartState timeout."); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + }); + // 生成pin + context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + // SetPinCode + std::string ultraPinCode = std::to_string(context->pinCode); + Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); + // 发送111报文 + context->reply = DM_OK; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, context); + LOGI("AuthSinkForwardUltrasonicStartState::Action End."); + return DM_OK; +} + +DmAuthStateType AuthSinkForwardUltrasonicDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE; +} + +int32_t AuthSinkForwardUltrasonicDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkForwardUltrasonicDoneState::Action Start."); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); + context->pinNegotiateStarted = true; + LOGI("AuthSinkForwardUltrasonicDoneState::Action context->transmitData = %{public}s.", context->transmitData.c_str()); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkForwardUltrasonicDoneState::Action call ProcessCredData err"); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送130报文 + LOGI("AuthSinkForwardUltrasonicDoneState::AuthDevice ON_TRANSMIT."); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkForwardUltrasonicDoneState::AuthDevice ON_ERROR failed."); + // src侧在hichain中认证成功与否都发送120 sink侧与src侧的认证结果应当一致,故这里不需要再发130给src + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + return STOP_BIND; } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d37e7c56a..9c953efb8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -276,7 +276,6 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_DONE,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicDone}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, @@ -302,7 +301,6 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone}, {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart}, {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_DONE,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicDone}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, @@ -1139,18 +1137,6 @@ int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate(const Jso return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageForwardUltrasonicDone(const JsonObject &json, - std::shared_ptr context) -{ - if (json[TAG_REPLY].IsNumberInteger()) { - context->reply = json[TAG_REPLY].Get(); - } - if (context->reply != DM_OK){ - context->authStateMachine->TransitionTo(std::make_shared()); - } - return DM_OK; -} - int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[TAG_AUTH_TYPE] = context->authType; @@ -1225,13 +1211,6 @@ int32_t DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate(std::sha return DM_OK; } -int32_t DmAuthMessageProcessor::CreateMessageForwardUltrasonicDone(std::shared_ptr context, - JsonObject &json) -{ - json[TAG_REPLY] = context->reply; - return DM_OK; -} - void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) { auto message = CreateMessage(msgType, context); -- Gitee From def488c1a2c6985a0256a8c67fc8a596e2082b54 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 10:22:59 +0800 Subject: [PATCH 13/38] modify Signed-off-by: BrainL --- .../auth_stages/auth_pin_auth.cpp | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 970d3a15d..5124e1076 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -207,7 +207,7 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c { LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); - if (context->authtype == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { + if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); } if (ret != DM_OK) { @@ -370,10 +370,14 @@ int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { - LOGI("AuthSrcPinNegotiateStartState ultrasonic forward"); + LOGI("AuthSrcPinNegotiateStartState ultrasonic forward."); context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && + context->ultrasonicInfo == DM_Ultrasonic_Reverse) { + LOGI("AuthSrcPinNegotiateStartState ultrasonic Reverse."); + context->authStateMachine->TransitionTo(std::make_shared()); } else { - LOGE("authType not support"); + LOGE("authType not support."); return ERR_DM_FAILED; } return DM_OK; @@ -462,11 +466,11 @@ int32_t AuthSrcPinNegotiateStartState::ProcessPinBind(std::shared_ptrauthTypeList.empty()) && DmAuthState::IsImportAuthCodeCompatibility(context->authTypeList[0])) { return NegotiatePinAuth(context, true); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC){ + return NegotiatePinAuth(context, true); } else { return NegotiatePinAuth(context, false); } - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC){ - return NegotiatePinAuth(context, false); } else { return NegotiatePinAuth(context, false); } @@ -593,23 +597,22 @@ DmAuthStateType AuthSrcReverseUltrasonicStartState::GetStateType() int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptr context) { LOGI("AuthSrcReverseUltrasonicStartState::Action start"); - context->timer->StartTImer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), + context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), GET_ULTRASONIC_PIN_TIMEOUT,[context](std::stringname){ LOGI("AuthSrcReverseUltrasonicStartState::Action timeout"); context->authStateMachine->TransitionTo(std::make_shared()); - return DM_OK + return DM_OK; }); //gen pin - context=>pinCode=GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - LOGI("AuthSrcReverseUltrasonicStartState::Action gen pin code %{public}d", context->pinCode); + context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); //set pincode std::string ultraPinCode = std::to_string(context->pinCode); - Msdp::SpatiaAwarenessMgrClient::GetInstance().SerPinCode(ultraPincode); + Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); //send 102 context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_START, context); LOGI("AuthSrcReverseUltrasonicStartState::Action send 102 msg done"); - return DM_OK + return DM_OK; } DmAuthStateType AuthSrcReverseUltrasonicDoneState::GetStateType() @@ -672,8 +675,7 @@ int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { LOGI("AuthSrcForwardUltrasonicDoneState timeout."); Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); - context->authStateMachine->TransitionTo(std::make_shared()); - return DM_OK; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_TIMEOUT); }); // 2.从MSDP接口拿到pin并取消监听 sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); @@ -681,10 +683,7 @@ int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_ULTRASONIC_PIN_CHANGED); if (retEvent == DmEventType::ON_ULTRASONIC_PIN_CHANGED) { Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); - context->reply = DM_OK; - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_DONE, context); - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(context->accesser.userId, context->requestId, context->pinCode); if (ret != DM_OK) { LOGE("OnPinCodeChanged failed."); @@ -701,6 +700,9 @@ int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } + } else if (retEvent == DmEventType::ON_ULTRASONIC_PIN_TIMEOUT){ + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } return STOP_BIND; } @@ -718,8 +720,7 @@ int32_t AuthSinkReverseUltrasonicStartState::Action(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); - return DM_OK; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_TIMEOUT); }); // 2.从MSDP接口拿到pin并取消监听 sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); @@ -731,6 +732,9 @@ int32_t AuthSinkReverseUltrasonicStartState::Action(std::shared_ptrauthMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_DONE, context); LOGI("OnPinCodeChanged End."); return DM_OK; + } else if (retEvent == DmEventType::ON_ULTRASONIC_PIN_TIMEOUT) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } return STOP_BIND; } @@ -746,7 +750,6 @@ int32_t AuthSinkReverseUltrasonicDoneState::Action(std::shared_ptrtimer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); context->pinNegotiateStarted = true; - LOGI("AuthSinkReverseUltrasonicDoneState::Action context->transmitData = %{public}s.", context->transmitData.c_str()); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); -- Gitee From a9d399c428cf4f0055a698363d15d9dc991a0091 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 10:40:02 +0800 Subject: [PATCH 14/38] modify Signed-off-by: BrainL --- .../src/authentication_v2/auth_manager.cpp | 2 +- .../auth_stages/auth_pin_auth.cpp | 4 +--- .../dm_auth_message_processor.cpp | 24 +++++++------------ .../dm_auth_state_machine.cpp | 2 +- .../src/device_manager_service_impl.cpp | 4 ++-- 5 files changed, 14 insertions(+), 22 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index cf8fa4017..521895e5a 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -466,7 +466,7 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); - if (tempInfo == DM_ULTRASONIC_FORWARD ){ + if (tempInfo == DM_ULTRASONIC_FORWARD) { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; } else if (tempInfo == DM_ULTRASONIC_REVERSE) { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 5124e1076..819e86b34 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -598,7 +598,7 @@ int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptrtimer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), - GET_ULTRASONIC_PIN_TIMEOUT,[context](std::stringname){ + GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::stringname) { LOGI("AuthSrcReverseUltrasonicStartState::Action timeout"); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -611,7 +611,6 @@ int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptrreply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_START, context); - LOGI("AuthSrcReverseUltrasonicStartState::Action send 102 msg done"); return DM_OK; } @@ -622,7 +621,6 @@ DmAuthStateType AuthSrcReverseUltrasonicDoneState::GetStateType() int32_t AuthSrcReverseUltrasonicDoneState::Action(std::shared_ptr context) { - LOGI("AuthSrcReverseUltrasonicDoneState::Action start"); // sink从msdp接受成功 LOGI("AuthSrcReverseUltrasonicDoneState::Action Start."); context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9c953efb8..a4fddf5cd 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -271,11 +271,11 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE,&DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START,&DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START, &DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE, &DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START, &DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, @@ -297,10 +297,10 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START,&DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE,&DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE,&DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START, &DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE, &DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START, &DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, @@ -1069,12 +1069,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js context->transmitData = json[TAG_DATA].Get(); } if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Reverse){ - LOGI("DmAuthMessageProcessor::ParseMessageReqPinAuthStart transmitDatao=%{public}s", - context->transmitData.c_str()); context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { - LOGI("DmAuthMessageProcessor::ParseMessageReqPinAuthStart transmitDatao=%{public}s", - context->transmitData.c_str()); context->authStateMachine->TransitionTo(std::make_shared()); } else { context->authStateMachine->TransitionTo(std::make_shared()); @@ -1117,8 +1113,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone(const JsonObje } if (context->reply == DM_OK){ context->authStateMachine->TransitionTo(std::make_shared()); - } else { - context->authStateMachine->TransitionTo(std::make_shared()); } return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index d40420143..3cf785298 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -58,7 +58,7 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, - {DmAuthStattType::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, { + {DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_START_STATE, { DmAuthStateType::AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 1cb4daad4..2085a22ef 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -834,7 +834,7 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr std::map bindParam; auto authMgr = GetAuthMgrByTokenId(tokenId); authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); - int32_t authType = -1; + int32_t authType = -1; authMgr->ParseAuthType(bindParam, authType); authMgrMap_.erase(tokenId); if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId) != DM_OK) { @@ -885,7 +885,7 @@ int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::mapsecond = CHANGE_PINTYPE; LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bind param %{public}s change to PIN_TYPE.", PARAM_KEY_AUTH_TYPE); -- Gitee From c146d311e133a432d28714a5bb8b2d6c40659ea1 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Mon, 14 Apr 2025 16:48:58 +0800 Subject: [PATCH 15/38] new credential Signed-off-by: q30043944 --- commondependency/BUILD.gn | 2 + .../include/deviceprofile_connector.h | 44 +- .../src/deviceprofile_connector.cpp | 376 ++++++++++-------- .../hichain/hichain_auth_connector.h | 6 +- .../include/device_manager_service_impl.h | 14 +- .../device_manager_service_impl_lite.h | 4 +- .../devicestate/dm_device_state_manager.h | 2 + .../src/authentication/dm_auth_manager.cpp | 31 +- .../hichain/hichain_auth_connector.cpp | 67 +--- .../src/device_manager_service_impl.cpp | 225 ++++++++--- .../src/device_manager_service_impl_lite.cpp | 6 +- .../devicestate/dm_device_state_manager.cpp | 35 +- .../include/idevice_manager_service_impl.h | 4 +- .../service/src/device_manager_service.cpp | 2 +- .../service/src/softbus/softbus_listener.cpp | 2 +- .../authenticatedeviceservice_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../dmauthmanager_fuzzer/BUILD.gn | 1 + .../hichainconnector_fuzzer/BUILD.gn | 1 + .../ondatareceived_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onerror_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onfinish_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onrequest_fuzzer/BUILD.gn | 1 + .../UTTest_dm_auth_manager_first.cpp | 8 +- .../UTTest_dm_auth_manager_second.cpp | 5 +- .../UTTest_dm_deviceprofile_connector.cpp | 32 +- ...Test_dm_deviceprofile_connector_second.cpp | 3 +- .../UTTest_hichain_auth_connector.cpp | 76 ++-- .../devicemanagerservice_fuzzer/BUILD.gn | 1 + .../deviceprofileconnector_fuzzer/BUILD.gn | 1 + .../device_profile_connector_fuzzer.cpp | 3 +- .../BUILD.gn | 1 + .../shiftlnngeardeviceservice_fuzzer/BUILD.gn | 1 + .../onsessionopened_fuzzer/BUILD.gn | 1 + test/unittest/BUILD.gn | 4 + .../UTTest_device_manager_service_impl.cpp | 25 +- ...Test_device_manager_service_impl_first.cpp | 2 +- .../mock/deviceprofile_connector_mock.cpp | 8 +- .../mock/deviceprofile_connector_mock.h | 9 +- .../mock/hichain_auth_connector_mock.cpp | 10 +- .../mock/hichain_auth_connector_mock.h | 12 +- 41 files changed, 661 insertions(+), 369 deletions(-) diff --git a/commondependency/BUILD.gn b/commondependency/BUILD.gn index 4f6e88b55..a0868efe7 100644 --- a/commondependency/BUILD.gn +++ b/commondependency/BUILD.gn @@ -82,6 +82,7 @@ ohos_shared_library("devicemanagerdependency") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_core", "os_account:libaccountkits", "samgr:samgr_proxy", @@ -151,6 +152,7 @@ ohos_shared_library("devicemanagerdependencytest") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_core", "os_account:libaccountkits", "samgr:samgr_proxy", diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 82470a301..079761bc3 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -22,6 +22,7 @@ #include "dm_single_instance.h" #include "i_dp_inited_callback.h" #include "local_service_info.h" +#include "parameter.h" #include "trusted_device_info.h" enum AllowAuthType { @@ -94,13 +95,24 @@ typedef struct DmAccessee { std::string trustDeviceName; } DmAccessee; +typedef struct DmAclIdParam { + std::string udid; + int32_t userId; + int64_t accessControlId; + int32_t skId; + std::string credId; +} DmAclIdParam; + typedef struct DmOfflineParam { uint32_t bindType; std::vector processVec; std::vector credIdVec; std::vector skIdVec; int32_t leftAclNumber; + int32_t peerUserId; bool isLnnAcl = false; + int64_t accessControlId; + std::vector dmAclIdParamVec; } DmOfflineParam; namespace OHOS { @@ -146,10 +158,11 @@ public: std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId); int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); EXPORT bool DeleteAclForAccountLogOut(const std::string &localUdid, - int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); - EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); + int32_t localUserId, const std::string &peerUdid, int32_t peerUserId, DmOfflineParam &offlineParam); + EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId, std::vector peerUdids, + std::multimap &peerUserIdMap, DmOfflineParam &offlineParam); EXPORT void DeleteAclForRemoteUserRemoved(std::string peerUdid, - int32_t peerUserId, std::vector &userIds); + int32_t peerUserId, std::vector &userIds, DmOfflineParam &offlineParam); EXPORT DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra); @@ -161,7 +174,7 @@ public: const std::string &deviceId); EXPORT bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); - EXPORT uint32_t DeleteTimeOutAcl(const std::string &deviceId); + EXPORT uint32_t DeleteTimeOutAcl(const std::string &deviceId, DmOfflineParam &offlineParam); EXPORT int32_t GetTrustNumber(const std::string &deviceId); bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); std::vector CompareBindType(std::vector profiles, @@ -187,6 +200,7 @@ public: int32_t tokenId, const std::string &localUdid, int32_t peerTokenId); EXPORT std::vector GetAllAccessControlProfile(); + EXPORT std::vector GetAllAclIncludeLnnAcl(); EXPORT void DeleteAccessControlById(int64_t accessControlId); EXPORT int32_t HandleUserSwitched(const std::string &localUdid, const std::vector &deviceVec, int32_t currentUserId, int32_t beforeUserId); @@ -197,8 +211,7 @@ public: const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); EXPORT void HandleUserSwitched( const std::vector &activeProfiles, - const std::vector &inActiveProfiles, - const std::vector &delActiveProfiles); + const std::vector &inActiveProfiles); EXPORT void HandleSyncForegroundUserIdEvent( const std::vector &remoteUserIds, const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid); @@ -257,7 +270,12 @@ public: int32_t GetAclListHashStr(const std::string localUdid, int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId, std::string &aclList); bool IsLnnAcl(const DistributedDeviceProfile::AccessControlProfile &profile); - + void CacheAcerAclId(const DistributedDeviceProfile::AccessControlProfile &profile, + DmOfflineParam &offlineParam); + void CacheAceeAclId(const DistributedDeviceProfile::AccessControlProfile &profile, + DmOfflineParam &offlineParam); + void DeleteCacheAcl(std::vector delAclIdVec, + std::vector &profiles); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); void GetParamBindTypeVec(DistributedDeviceProfile::AccessControlProfile profiles, std::string requestDeviceId, @@ -297,22 +315,26 @@ private: const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid, const std::string &extra); void DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); std::string GetAppServiceAuthVersionInfo(std::string localUdid, std::string remoteUdid, int32_t tokenId, int32_t userId, std::vector profiles); std::string GetDeviceAuthVersionInfo(std::string localUdid, std::string remoteUdid, std::vector profiles); void DeleteDeviceBindLevelV2(DmOfflineParam &offlineParam, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); void ParseExtra(const std::string &extra, uint64_t &peerTokenId, std::string &peerBundleName); + bool CacheLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, const std::string &localUdid, + DmAclIdParam &dmAclIdParam); + void CheckLastLnnAcl(const std::string &localDeviceId, int32_t userId, const std::string &remoteDeviceId, + DmOfflineParam &offlineParam, std::vector &profiles); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index ac81fa165..395ade51d 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -344,29 +344,33 @@ EXPORT DmOfflineParam DeviceProfileConnector::DeleteAccessControlListV2(uint32_t LOGE("DeleteAccessControlListV2: Invalied bindlevel."); break; } - std::vector leftProfiles = - GetAclProfileByDeviceIdAndUserId(localDeviceId, userId, remoteDeviceId); - if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { - if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localDeviceId) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); + CheckLastLnnAcl(localDeviceId, userId, remoteDeviceId, offlineParam, profiles); + return offlineParam; +} + +void DeviceProfileConnector::CheckLastLnnAcl(const std::string &localDeviceId, int32_t localUserId, + const std::string &remoteDeviceId, DmOfflineParam &offlineParam, + std::vector &profiles) +{ + LOGI("profiles size: %{public}zu", profiles.size()); + if (profiles.size() == 1 && IsLnnAcl(profiles[0])) { + if (profiles[0].GetAccesser().GetAccesserDeviceId() == localDeviceId) { + CacheAcerAclId(profiles[0], offlineParam); } - if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localDeviceId) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); + if (profiles[0].GetAccessee().GetAccesseeDeviceId() == localDeviceId) { + CacheAceeAclId(profiles[0], offlineParam); } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); offlineParam.isLnnAcl = true; } - return offlineParam; } void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) { int32_t bindNums = 0; int32_t deleteNums = 0; + std::vector delAclIdVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -379,15 +383,14 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); if ((acerTokenId == static_cast(tokenId)) && acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -395,24 +398,38 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, } if ((aceeTokenId == static_cast(tokenId)) && aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; } +void DeviceProfileConnector::DeleteCacheAcl(std::vector delAclIdVec, + std::vector &profiles) +{ + for (auto delAclId : delAclIdVec) { + for (auto item = profiles.begin(); item != profiles.end();) { + if (delAclId == item->GetAccessControlId()) { + item = profiles.erase(item); + } else { + item++; + } + } + } +} + void DeviceProfileConnector::ParseExtra(const std::string &extra, uint64_t &peerTokenId, std::string &peerBundleName) { JsonObject extraInfoJson(extra); @@ -429,7 +446,7 @@ void DeviceProfileConnector::ParseExtra(const std::string &extra, uint64_t &peer } void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid, const std::string &extra) { LOGI("DeviceProfileConnector::DeleteAppBindLevelV2 extra %{public}s", extra.c_str()); @@ -437,6 +454,7 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, int32_t deleteNums = 0; uint64_t peerTokenId = 0; std::string peerBundleName; + std::vector delAclIdVec; ParseExtra(extra, peerTokenId, peerBundleName); for (auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || @@ -450,15 +468,14 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); if ((acerTokenId == static_cast(tokenId)) && aceeDeviceId == remoteUdid && (aceeTokenId == static_cast(peerTokenId)) && acerDeviceId == localUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -466,30 +483,31 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, } if ((aceeTokenId == static_cast(tokenId)) && acerDeviceId == remoteUdid && (acerTokenId == static_cast(peerTokenId)) && aceeDeviceId == localUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; } void DeviceProfileConnector::DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, - const std::vector &profiles, const std::string &localUdid, + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) { int32_t bindNums = 0; int32_t deleteNums = 0; + std::vector delAclIdVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != SERVICE) { @@ -502,15 +520,14 @@ void DeviceProfileConnector::DeleteServiceBindLevelV2(DmOfflineParam &offlinePar std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); if ((acerTokenId == static_cast(tokenId)) && acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; ProcessInfo processInfo; - processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); - processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -518,29 +535,30 @@ void DeviceProfileConnector::DeleteServiceBindLevelV2(DmOfflineParam &offlinePar } if ((aceeTokenId == static_cast(tokenId)) && aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; ProcessInfo processInfo; - processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; } void DeviceProfileConnector::DeleteDeviceBindLevelV2(DmOfflineParam &offlineParam, - const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) + std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) { int32_t bindNums = 0; int32_t deleteNums = 0; + std::vector delAclIdVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || IsLnnAcl(item)) { continue; @@ -548,27 +566,26 @@ void DeviceProfileConnector::DeleteDeviceBindLevelV2(DmOfflineParam &offlinePara bindNums++; if (item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; } @@ -622,7 +639,7 @@ std::vector DeviceProfileConnector::GetAclProfileByDeviceI { std::vector aclProfileVec; - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && item.GetAccesser().GetAccesserUserId() == userId && @@ -1061,11 +1078,11 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, DmOfflineParam &offlineParam) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); std::vector deleteProfiles; bool notifyOffline = false; bool isDelete = false; @@ -1084,6 +1101,7 @@ EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( } deleteProfiles.push_back(item); notifyOffline = (item.GetStatus() == ACTIVE); + CacheAcerAclId(item, offlineParam); continue; } if (accesserUdid == peerUdid && accesserUserId == peerUserId && @@ -1093,56 +1111,68 @@ EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( } deleteProfiles.push_back(item); notifyOffline = (item.GetStatus() == ACTIVE); + CacheAceeAclId(item, offlineParam); continue; } } if (!isDelete) { return false; } - for (const auto &item : deleteProfiles) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } return notifyOffline; } -EXPORT void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, - int32_t userId) +EXPORT void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, int32_t userId, + std::vector peerUdids, std::multimap &peerUserIdMap, + DmOfflineParam &offlineParam) { LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), userId); - std::vector profiles = GetAccessControlProfileByUserId(userId); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (const auto &item : profiles) { + if (find(peerUdids.begin(), peerUdids.end(), item.GetTrustDeviceId()) == peerUdids.end()) { + continue; + } std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); - if ((accesserUdid == localUdid && accesserUserId == userId) || - (accesseeUdid == localUdid && accesseeUserId == userId)) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + if (accesserUdid == localUdid && accesserUserId == userId) { + if (!IsValueExist(peerUserIdMap, accesseeUdid, accesseeUserId)) { + peerUserIdMap.insert(std::pair(accesseeUdid, accesseeUserId)); + } + CacheAcerAclId(item, offlineParam); + continue; + } + if (accesseeUdid == localUdid && accesseeUserId == userId) { + if (!IsValueExist(peerUserIdMap, accesserUdid, accesserUserId)) { + peerUserIdMap.insert(std::pair(accesserUdid, accesserUserId)); + } + CacheAceeAclId(item, offlineParam); + continue; } } } EXPORT void DeviceProfileConnector::DeleteAclForRemoteUserRemoved( - std::string peerUdid, int32_t peerUserId, std::vector &userIds) + std::string peerUdid, int32_t peerUserId, std::vector &userIds, DmOfflineParam &offlineParam) { LOGI("peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(peerUdid).c_str(), peerUserId); - std::vector profiles = GetAccessControlProfileByUserId(peerUserId); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (const auto &item : profiles) { std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); if (accesserUdid == peerUdid && accesserUserId == peerUserId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); if (item.GetBindLevel() == USER) { userIds.push_back(accesseeUserId); } + CacheAceeAclId(item, offlineParam); } if (accesseeUdid == peerUdid && accesseeUserId == peerUserId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); if (item.GetBindLevel() == USER) { userIds.push_back(accesserUserId); } + CacheAcerAclId(item, offlineParam); } } } @@ -1222,6 +1252,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.peerUserId = item.GetAccessee().GetAccesseeUserId(); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -1237,6 +1268,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.peerUserId = item.GetAccesser().GetAccesserUserId(); LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -1273,6 +1305,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.peerUserId = item.GetAccessee().GetAccesseeUserId(); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -1289,6 +1322,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.peerUserId = item.GetAccesser().GetAccesserUserId(); LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -1313,8 +1347,6 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -1324,8 +1356,6 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -1431,24 +1461,69 @@ bool DeviceProfileConnector::CheckDevIdInAclForDevBind(const std::string &pkgNam return (CheckSinkDevIdInAclForDevBind(pkgName, deviceId) || CheckSrcDevIdInAclForDevBind(pkgName, deviceId)); } -EXPORT uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) +EXPORT uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId, DmOfflineParam &offlineParam) { - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t res = 0; + int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localDeviceId); + DmAclIdParam dmAclIdParam; for (auto &item : profiles) { if (item.GetTrustDeviceId() != deviceId || item.GetStatus() != ACTIVE) { continue; } + if (CacheLnnAcl(item, localUdid, dmAclIdParam)) { + continue; + } res++; + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); if (item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { res--; - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + if (accesserUserId == currentUserId && accesserUdid == localUdid && accesseeUdid == deviceId) { + CacheAcerAclId(item, offlineParam); + offlineParam.peerUserId = item.GetAccessee().GetAccesseeUserId(); + } + if (accesseeUserId == currentUserId && accesseeUdid == localUdid && accesserUdid == deviceId) { + CacheAceeAclId(item, offlineParam); + offlineParam.peerUserId = item.GetAccesser().GetAccesserUserId(); + } } } + if (res == 0) { + offlineParam.dmAclIdParamVec.push_back(dmAclIdParam); + } return res; } +bool DeviceProfileConnector::CacheLnnAcl(AccessControlProfile profile, const std::string &localUdid, + DmAclIdParam &dmAclIdParam) +{ + if (IsLnnAcl(profile)) { + if (profile.GetAccesser().GetAccesserDeviceId() == localUdid) { + dmAclIdParam.udid = profile.GetAccesser().GetAccesserDeviceId(); + dmAclIdParam.userId = profile.GetAccesser().GetAccesserUserId(); + dmAclIdParam.skId = profile.GetAccesser().GetAccesserSessionKeyId(); + dmAclIdParam.credId = profile.GetAccesser().GetAccesserCredentialIdStr(); + dmAclIdParam.accessControlId = profile.GetAccessControlId(); + } + if (profile.GetAccessee().GetAccesseeDeviceId() == localUdid) { + dmAclIdParam.udid = profile.GetAccessee().GetAccesseeDeviceId(); + dmAclIdParam.userId = profile.GetAccessee().GetAccesseeUserId(); + dmAclIdParam.skId = profile.GetAccessee().GetAccesseeSessionKeyId(); + dmAclIdParam.credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); + dmAclIdParam.accessControlId = profile.GetAccessControlId(); + } + return true; + } + return false; +} + EXPORT int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) { std::vector profiles = GetAccessControlProfile(); @@ -1778,7 +1853,7 @@ EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId, localUdid); int32_t bindType = DM_INVALIED_TYPE; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { @@ -1790,10 +1865,8 @@ EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId } if (item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); bindType = std::min(bindType, static_cast(item.GetBindType())); @@ -1801,10 +1874,8 @@ EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId } if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); offlineParam.bindType = USER; - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); bindType = std::min(bindType, static_cast(item.GetBindType())); @@ -1819,10 +1890,11 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId, localUdid); DmOfflineParam offlineParam; int32_t bindNums = 0; int32_t deleteNums = 0; + std::vector delAclIdVec; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -1834,15 +1906,14 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -1850,33 +1921,20 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; - std::vector leftProfiles = - GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); - if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { - if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); - } - if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); - } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); - offlineParam.isLnnAcl = true; - } + CheckLastLnnAcl(localUdid, remoteUserId, remoteUdid, offlineParam, profiles); return offlineParam; } @@ -1885,10 +1943,11 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId, localUdid); DmOfflineParam offlineParam; int32_t bindNums = 0; int32_t deleteNums = 0; + std::vector delAclIdVec; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -1904,47 +1963,33 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot if (acerUserId == remoteUserId && acerDeviceId == remoteUdid && aceeDeviceId == localUdid && (acerTokenId == tokenId) && (aceeTokenId == peerTokenId)) { LOGI("Src device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); continue; } if (aceeUserId == remoteUserId && aceeDeviceId == remoteUdid && acerDeviceId == localUdid && (aceeTokenId == tokenId) && (acerTokenId == peerTokenId)) { LOGI("Sink device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); continue; } } + DeleteCacheAcl(delAclIdVec, profiles); offlineParam.leftAclNumber = bindNums - deleteNums; - std::vector leftProfiles = - GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); - if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { - if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); - } - if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); - } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); - offlineParam.isLnnAcl = true; - } + CheckLastLnnAcl(localUdid, remoteUserId, remoteUdid, offlineParam, profiles); return offlineParam; } @@ -1953,8 +1998,9 @@ DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUs { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId, localUdid); DmOfflineParam offlineParam; + std::vector delAclIdVec; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != SERVICE) { @@ -1965,13 +2011,13 @@ DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUs (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); offlineParam.bindType = SERVICE; ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + CacheAceeAclId(item, offlineParam); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -1979,30 +2025,18 @@ DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUs (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + delAclIdVec.push_back(item.GetAccessControlId()); offlineParam.bindType = SERVICE; ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); - offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + CacheAcerAclId(item, offlineParam); continue; } } - std::vector leftProfiles = - GetAclProfileByDeviceIdAndUserId(localUdid, remoteUserId, remoteUdid); - if (leftProfiles.size() == 1 && IsLnnAcl(leftProfiles[0])) { - if (leftProfiles[0].GetAccesser().GetAccesserDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccesser().GetAccesserCredentialIdStr()); - } - if (leftProfiles[0].GetAccessee().GetAccesseeDeviceId() == localUdid) { - offlineParam.skIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeSessionKeyId()); - offlineParam.credIdVec.push_back(leftProfiles[0].GetAccessee().GetAccesseeCredentialIdStr()); - } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(leftProfiles[0].GetAccessControlId()); - offlineParam.isLnnAcl = true; - } + DeleteCacheAcl(delAclIdVec, profiles); + CheckLastLnnAcl(localUdid, remoteUserId, remoteUdid, offlineParam, profiles); return offlineParam; } @@ -2015,6 +2049,15 @@ EXPORT std::vector DeviceProfileConnector::GetAllAccessCon return profiles; } +EXPORT std::vector DeviceProfileConnector::GetAllAclIncludeLnnAcl() +{ + std::vector profiles; + if (DistributedDeviceProfileClient::GetInstance().GetAllAclIncludeLnnAcl(profiles) != DM_OK) { + LOGE("DP failed."); + } + return profiles; +} + EXPORT void DeviceProfileConnector::DeleteAccessControlById( int64_t accessControlId) { @@ -2029,10 +2072,9 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( LOGI("no remote device."); return DM_OK; } - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); std::vector activeProfiles; std::vector inActiveProfiles; - std::vector delActiveProfiles; for (auto &item : profiles) { if (std::find(deviceVec.begin(), deviceVec.end(), item.GetTrustDeviceId()) == deviceVec.end()) { continue; @@ -2045,9 +2087,6 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( item.SetStatus(INACTIVE); inActiveProfiles.push_back(item); } - if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { - delActiveProfiles.push_back(item); - } continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -2059,21 +2098,18 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( continue; } } - HandleUserSwitched(activeProfiles, inActiveProfiles, delActiveProfiles); + HandleUserSwitched(activeProfiles, inActiveProfiles); return DM_OK; } EXPORT void DeviceProfileConnector::HandleUserSwitched( const std::vector &activeProfiles, - const std::vector &inActiveProfiles, - const std::vector &delActiveProfiles) + const std::vector &inActiveProfiles) { for (auto &item : inActiveProfiles) { DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } - for (auto &item : delActiveProfiles) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } + for (auto &item : activeProfiles) { DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } @@ -2106,7 +2142,7 @@ EXPORT void DeviceProfileConnector::HandleSyncForegroundUserIdEvent( { LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && @@ -2215,7 +2251,7 @@ EXPORT void DeviceProfileConnector::UpdateACL(std::string &localUdid, { LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto item : profiles) { // deleta signal trust acl. DeleteSigTrustACL(item, remoteUdid, remoteFrontUserIds, remoteBackUserIds); @@ -2347,7 +2383,7 @@ EXPORT void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent( { LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { std::string accesserDeviceId = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); @@ -2360,9 +2396,6 @@ EXPORT void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent( item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } - if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } } else if ((accesseeDeviceId == localUdid && accesserDeviceId == remoteUdid) && (find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end() || find(localUserIds.begin(), localUserIds.end(), accesseeUserId) == localUserIds.end())) { @@ -2370,9 +2403,6 @@ EXPORT void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent( item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } - if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } } } } @@ -2597,7 +2627,7 @@ bool DeviceProfileConnector::CheckAclStatusNotMatch(const DistributedDeviceProfi bool DeviceProfileConnector::CheckAclStatusAndForegroundNotMatch(const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) { - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); LOGI("CheckAclStatusAndForegroundNotMatch profiles size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (CheckAclStatusNotMatch(item, localUdid, foregroundUserIds, backgroundUserIds)) { @@ -2616,10 +2646,9 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( LOGI("no remote device."); return DM_OK; } - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); std::vector activeProfiles; std::vector inActiveProfiles; - std::vector delActiveProfiles; for (auto &item : profiles) { if (std::find(deviceVec.begin(), deviceVec.end(), item.GetTrustDeviceId()) == deviceVec.end()) { continue; @@ -2634,9 +2663,6 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( item.SetStatus(INACTIVE); inActiveProfiles.push_back(item); } - if (item.GetBindType() != DM_IDENTICAL_ACCOUNT) { - delActiveProfiles.push_back(item); - } continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -2650,13 +2676,13 @@ EXPORT int32_t DeviceProfileConnector::HandleUserSwitched( continue; } } - HandleUserSwitched(activeProfiles, inActiveProfiles, delActiveProfiles); + HandleUserSwitched(activeProfiles, inActiveProfiles); return DM_OK; } int32_t DeviceProfileConnector::HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid) { - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == stopEventUdid && item.GetAccesser().GetAccesserUserId() == stopUserId && item.GetStatus() == ACTIVE) || @@ -2676,7 +2702,7 @@ int32_t DeviceProfileConnector::HandleUserStop(int32_t stopUserId, const std::st LOGI("no remote device."); return DM_OK; } - std::vector profiles = GetAllAccessControlProfile(); + std::vector profiles = GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { if (std::find(acceptEventUdids.begin(), acceptEventUdids.end(), item.GetTrustDeviceId()) == acceptEventUdids.end()) { @@ -2704,6 +2730,30 @@ bool DeviceProfileConnector::IsLnnAcl(const DistributedDeviceProfile::AccessCont return false; } +void DeviceProfileConnector::CacheAcerAclId(const DistributedDeviceProfile::AccessControlProfile &profile, + DmOfflineParam &offlineParam) +{ + DmAclIdParam dmAclIdParam; + dmAclIdParam.udid = profile.GetAccesser().GetAccesserDeviceId(); + dmAclIdParam.userId = profile.GetAccesser().GetAccesserUserId(); + dmAclIdParam.skId = profile.GetAccesser().GetAccesserSessionKeyId(); + dmAclIdParam.credId = profile.GetAccesser().GetAccesserCredentialIdStr(); + dmAclIdParam.accessControlId = profile.GetAccessControlId(); + offlineParam.dmAclIdParamVec.push_back(dmAclIdParam); +} + +void DeviceProfileConnector::CacheAceeAclId(const DistributedDeviceProfile::AccessControlProfile &profile, + DmOfflineParam &offlineParam) +{ + DmAclIdParam dmAclIdParam; + dmAclIdParam.udid = profile.GetAccessee().GetAccesseeDeviceId(); + dmAclIdParam.userId = profile.GetAccessee().GetAccesseeUserId(); + dmAclIdParam.skId = profile.GetAccessee().GetAccesseeSessionKeyId(); + dmAclIdParam.credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); + dmAclIdParam.accessControlId = profile.GetAccessControlId(); + offlineParam.dmAclIdParamVec.push_back(dmAclIdParam); +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 5684ef0c9..aee7bd57f 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -54,11 +54,11 @@ public: int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId); int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); - bool QueryCredential(std::string &localUdid, int32_t osAccountId); + bool QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId); int32_t QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, JsonObject &resultJson); int32_t QueryCredInfoByCredId(int32_t userId, std::string credId, JsonObject &resultJson); - int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); - int32_t DeleteCredential(const std::string &deviceId, int32_t userId); + int32_t ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, std::string publicKey); + int32_t DeleteCredential(const std::string &deviceId, int32_t userId, int32_t peerUserId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); int32_t RegisterHiChainAuthCallbackById(int64_t id, std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 8365fe874..3f44106d9 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -38,6 +38,7 @@ #include "ipc_skeleton.h" #include "mine_hichain_connector.h" #include "softbus_connector.h" +#include "deviceprofile_connector.h" namespace OHOS { namespace DistributedHardware { @@ -164,7 +165,7 @@ public: const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); int32_t RegisterAuthenticationType(int32_t authenticationType); void DeleteAlwaysAllowTimeOut(); - void CheckDeleteCredential(const std::string &remoteUdid); + void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel, const std::string &extra); @@ -190,7 +191,7 @@ private: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); - void HandleUserRemoved(int32_t preUserId); + void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); std::shared_ptr GetAuthMgr(); @@ -227,8 +228,13 @@ private: void CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId); int32_t DeleteProcAcl(uint32_t tokenId, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel, const std::string &extra, int32_t userId); - int32_t DeleteSkIdAndCredId(DmOfflineParam offlineParam, int32_t userId); - + int32_t DeleteSkIdAndCredId(DmOfflineParam offlineParam); + void DeleteAclByTokenId(const int32_t accessTokenId, + std::vector &profiles, + std::map &delProfileMap, + std::vector> &delACLInfoVec, std::vector &userIdVec); + bool CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, + DistributedDeviceProfile::AccessControlProfile lastprofile); private: std::shared_ptr authMgr_; // Old protocol only std::mutex authMgrMtx_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index c0896ecc2..5579a8c97 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -140,7 +140,7 @@ public: int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); - void HandleUserRemoved(int32_t preUserId); + void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, int32_t beforeUserId); @@ -161,7 +161,7 @@ public: int32_t localUserId, const std::string &localAccountId); int32_t RegisterAuthenticationType(int32_t authenticationType); void DeleteAlwaysAllowTimeOut(); - void CheckDeleteCredential(const std::string &remoteUdid); + void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, int32_t remoteTokenId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 8e6806ef4..fc231c78a 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -34,6 +34,7 @@ #include "hichain_connector.h" #include "hichain_auth_connector.h" #include "multiple_user_connector.h" +#include "deviceprofile_connector.h" namespace OHOS { namespace DistributedHardware { @@ -96,6 +97,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t DeleteSkIdAndCredId(DmOfflineParam offlineParam); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f56184951..0726af54b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -486,7 +486,8 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & if (offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); return DM_OK; } } @@ -496,7 +497,8 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & } if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); return DM_OK; } return ERR_DM_FAILED; @@ -2242,9 +2244,26 @@ void DmAuthManager::RequestCredentialDone() int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey) { - LOGI("DmAuthManager::ImportCredential"); + LOGI("DmAuthManager::ImportCredential, deviceId %{public}s", GetAnonyString(deviceId).c_str()); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey); + if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + // Source Import Credential + LOGI("Source Import Credential remoteUserId: %{public}d", authRequestContext_->remoteUserId); + CHECK_NULL_RETURN(authRequestContext_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + return hiChainAuthConnector_->ImportCredential(osAccountId, authRequestContext_->remoteUserId, deviceId, + publicKey); + } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { + // Sink Import Credential + LOGI("Source Import Credential remoteUserId: %{public}d", authResponseContext_->remoteUserId); + CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + return hiChainAuthConnector_->ImportCredential(osAccountId, authResponseContext_->remoteUserId, deviceId, + publicKey); + } else { + LOGE("DmAuthManager::ImportCredential failed, authRequestState_ or authResponseState_ is invalid."); + return ERR_DM_AUTH_FAILED; + } } void DmAuthManager::ResponseCredential() @@ -2628,7 +2647,7 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); authResponseContext_->haveCredential = hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, - MultipleUserConnector::GetFirstForegroundUserId()); + MultipleUserConnector::GetFirstForegroundUserId(), authResponseContext_->remoteUserId); if (!IsAuthTypeSupported(authResponseContext_->authType)) { LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; @@ -3081,7 +3100,7 @@ int32_t DmAuthManager::GetBinderInfo() ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, authResponseContext_->peerBundleName, 0, authResponseContext_->tokenId); #ifndef DEVICE_MANAGER_COMMON_FLAG - if (ret == DM_OK && authResponseContext_->bindLevel != APP) { + if (ret == DM_OK && static_cast(authResponseContext_->bindLevel) != APP) { LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); return ERR_DM_FAILED; } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 6ddbc6626..b214ecce6 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -351,15 +351,10 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t LOGE("Decode generate return data jsonStr error."); return ERR_DM_FAILED; } - if (!IsInt32(jsonObject, "result") || !IsString(jsonObject, "publicKey") || - jsonObject["result"].Get() != HC_SUCCESS) { + if (!IsString(jsonObject, "publicKey")) { LOGE("Hichain generate public key jsonObject invalied."); return ERR_DM_FAILED; } - if (jsonObject["result"].Get() != 0) { - LOGE("Hichain generate public key failed"); - return ERR_DM_FAILED; - } publicKey = jsonObject["publicKey"].Get(); return DM_OK; } @@ -428,11 +423,13 @@ int32_t HiChainAuthConnector::QueryCredInfoByCredId(int32_t userId, std::string return DM_OK; } -bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) { - LOGI("HiChainAuthConnector::QueryCredential start."); + LOGI("QueryCredential start, deviceId: %{public}s, peerOsAccountId: %{public}d", + GetAnonyString(localUdid).c_str(), peerOsAccountId); JsonObject jsonObj; jsonObj["osAccountId"] = osAccountId; + jsonObj["peerOsAccountId"] = peerOsAccountId; jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; @@ -450,11 +447,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc LOGE("Decode query return data jsonStr error."); return false; } - if (!IsInt32(jsonObject, "result") || jsonObject["result"].Get() == -1) { - LOGE("Hichain generate public key failed."); - return false; - } - if (!IsString(jsonObject, "publicKey") || jsonObject["result"].Get() == 1) { + if (!IsString(jsonObject, "publicKey")) { LOGI("Credential not exist."); return false; } @@ -483,11 +476,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc LOGE("Decode query return data jsonStr error."); return ERR_DM_FAILED; } - if (!IsInt32(jsonObject, "result") || jsonObject["result"].Get() == -1) { - LOGE("Hichain generate public key failed."); - return ERR_DM_FAILED; - } - if (!IsString(jsonObject, "publicKey") || jsonObject["result"].Get() == 1) { + if (!IsString(jsonObject, "publicKey")) { LOGI("Credential not exist."); return ERR_DM_FAILED; } @@ -495,11 +484,14 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc return DM_OK; } -int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) +int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, + std::string publicKey) { - LOGI("HiChainAuthConnector::ImportCredential"); + LOGI("ImportCredential start, deviceId: %{public}s, peerOsAccountId: %{public}d", + GetAnonyString(deviceId).c_str(), peerOsAccountId); JsonObject jsonObj; jsonObj["osAccountId"] = osAccountId; + jsonObj["peerOsAccountId"] = peerOsAccountId; jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; @@ -510,51 +502,28 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string FreeJsonString(returnData); return ERR_DM_FAILED; } - std::string returnDataStr = static_cast(returnData); FreeJsonString(returnData); - JsonObject jsonObject(returnDataStr); - if (jsonObject.IsDiscarded()) { - LOGE("Decode import return data jsonStr error."); - return ERR_DM_FAILED; - } - if (!IsInt32(jsonObject, "result")) { - LOGI("Hichain import public key jsonObject invalied."); - return ERR_DM_FAILED; - } - int32_t result = jsonObject["result"].Get(); - if (result != 0) { - LOGE("Hichain import public key result is %{public}d.", result); - return ERR_DM_FAILED; - } return DM_OK; } -int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int32_t userId) +int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int32_t userId, int32_t peerUserId) { - LOGI("DeleteCredential start."); + LOGI("DeleteCredential start, deviceId: %{public}s, peerUserId: %{public}d", + GetAnonyString(deviceId).c_str(), peerUserId); JsonObject jsonObj; jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; + jsonObj["peerOsAccountId"] = peerUserId; std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); FreeJsonString(returnData); - return false; - } - std::string returnDataStr = static_cast(returnData); - FreeJsonString(returnData); - JsonObject jsonObject(returnDataStr); - if (jsonObject.IsDiscarded()) { - LOGE("Decode import return data jsonStr error."); - return false; - } - if (!IsInt32(jsonObject, "result")) { - LOGI("Hichain delete credential result json key is invalid."); return ERR_DM_FAILED; } - return jsonObject["result"].Get(); + FreeJsonString(returnData); + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 02f43f706..fb6b9968a 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1584,8 +1584,9 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + DmOfflineParam offlineParam; bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); + peerUdid, peerUserId, offlineParam); if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); @@ -1595,33 +1596,59 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local CHECK_NULL_VOID(deviceStateMgr_); deviceStateMgr_->OnDeviceOffline(peerUdid); } + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(localUserId); + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(peerUdid, localUserId, peerUserId); + LOGE("DeleteSkIdAndCredId start"); + DeleteSkIdAndCredId(offlineParam); } -void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) +void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) { LOGI("PreUserId %{public}d.", preUserId); char localDeviceId[DEVICE_UUID_LENGTH]; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = reinterpret_cast(localDeviceId); - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId); + std::multimap peerUserIdMap; // key: peerUdid value: peerUserId + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId, peerUdids, peerUserIdMap, + offlineParam); CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteAllGroup(preUserId); + + if (peerUserIdMap.empty()) { + LOGE("peerUserIdMap is empty"); + return; + } + CHECK_NULL_VOID(hiChainAuthConnector_); + for (const auto &item : peerUserIdMap) { + hiChainAuthConnector_->DeleteCredential(item.first, preUserId, item.second); + } + LOGE("DeleteSkIdAndCredId start"); + DeleteSkIdAndCredId(offlineParam); } void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) { LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); std::vector localUserIds; - DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(remoteUdid, userId, localUserIds); + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(remoteUdid, userId, localUserIds, offlineParam); if (localUserIds.empty()) { return; } - CHECK_NULL_VOID(hiChainConnector_); + CHECK_NULL_VOID(hiChainAuthConnector_); std::vector> delInfoVec; for (int32_t localUserId : localUserIds) { delInfoVec.push_back(std::pair(localUserId, remoteUdid)); + hiChainAuthConnector_->DeleteCredential(remoteUdid, localUserId, userId); } + CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds); + LOGE("DeleteSkIdAndCredId start"); + DeleteSkIdAndCredId(offlineParam); + } void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector &deviceVec, @@ -1633,8 +1660,6 @@ void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, deviceVec, currentUserId, beforeUserId); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(beforeUserId); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -1723,8 +1748,9 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); for (const auto &item : devIdAndUserMap) { + DmOfflineParam offlineParam; bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, - remoteUdid, remoteUserId); + remoteUdid, remoteUserId, offlineParam); if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); @@ -1734,6 +1760,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co CHECK_NULL_VOID(deviceStateMgr_); deviceStateMgr_->OnDeviceOffline(remoteUdid); } + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(item.second); + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId); + //TODO: + LOGE("DeleteSkIdAndCredId start"); + DeleteSkIdAndCredId(offlineParam); } } @@ -1784,7 +1817,7 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const } int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); DeleteGroup(DM_PKG_NAME, remoteUdid); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -1803,7 +1836,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return; } if (offlineParam.leftAclNumber == 0) { @@ -1812,9 +1845,10 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const softbusConnector_->SetProcessInfoVec(offlineParam.processVec); if (!offlineParam.isLnnAcl) { CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); } else { - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); } return; } @@ -1837,7 +1871,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const CHECK_NULL_VOID(softbusConnector_); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return; } if (offlineParam.leftAclNumber == 0) { @@ -1846,9 +1880,10 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const softbusConnector_->SetProcessInfoVec(offlineParam.processVec); if (!offlineParam.isLnnAcl) { CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); } else { - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); } return; } @@ -1873,7 +1908,7 @@ void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const st softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); } - DeleteSkIdAndCredId(offlineParam, localUserId); + DeleteSkIdAndCredId(offlineParam); } void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, @@ -1973,27 +2008,39 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i if (profiles.size() == 0) { return DM_OK; } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localDeviceId); std::vector> delACLInfoVec; std::vector userIdVec; - for (auto &item : profiles) { - int64_t tokenId = item.GetAccesser().GetAccesserTokenId(); - if (accessTokenId != static_cast(tokenId) || item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - continue; + std::map delProfileMap; + DeleteAclByTokenId(accessTokenId, profiles, delProfileMap, delACLInfoVec, userIdVec); + for (auto item : delProfileMap) { + DmOfflineParam lnnAclParam; + bool isLastLnnAcl = false; + for (auto it : profiles) { + DistributedDeviceProfile::AccessControlProfile lnnAclProfile; + if (DeviceProfileConnector::GetInstance().IsLnnAcl(it) && CheckLnnAcl(item.second, it)) { + if (it.GetAccesser().GetAccesserDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAcerAclId(it, lnnAclParam); + } + if (it.GetAccessee().GetAccesseeDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAceeAclId(it, lnnAclParam); + } + } + if (!DeviceProfileConnector::GetInstance().IsLnnAcl(it) && CheckLnnAcl(item.second, it)) { + isLastLnnAcl = true; + } } - DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); - listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); - if (item.GetBindLevel() == USER) { - userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); - delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), - item.GetAccessee().GetAccesseeDeviceId())); + if (!isLastLnnAcl) { + DeleteSkIdAndCredId(lnnAclParam); } } + if (delACLInfoVec.size() == 0) { - LOGI("delACLInfoVec is empty"); return DM_OK; } if (userIdVec.size() == 0) { - LOGI("userIdVec is empty"); return DM_OK; } CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); @@ -2001,6 +2048,70 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i return DM_OK; } +void DeviceManagerServiceImpl::DeleteAclByTokenId(const int32_t accessTokenId, + std::vector &profiles, + std::map &delProfileMap, + std::vector> &delACLInfoVec, std::vector &userIdVec) +{ + for (auto &item : profiles) { + int64_t accesssertokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t accessseetokenId = item.GetAccessee().GetAccesseeTokenId(); + if (accessTokenId != static_cast(accesssertokenId) || + accessTokenId != static_cast(accessseetokenId)) { + continue; + } + if (accessTokenId == static_cast(accesssertokenId)) { + DmOfflineParam offlineParam; + delProfileMap[item.GetAccessControlId()] = item; + DeviceProfileConnector::GetInstance().CacheAcerAclId(item, offlineParam); + DeleteSkIdAndCredId(offlineParam); + listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); + if (item.GetBindLevel() == USER) { + userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), + item.GetAccessee().GetAccesseeDeviceId())); + } + } + if (accessTokenId == static_cast(accesssertokenId)) { + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().CacheAceeAclId(item, offlineParam); + delProfileMap[item.GetAccessControlId()] = item; + DeleteSkIdAndCredId(offlineParam); + listener_->OnAppUnintall(item.GetAccessee().GetAccesseeBundleName()); + if (item.GetBindLevel() == USER) { + userIdVec.push_back(item.GetAccessee().GetAccesseeUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccessee().GetAccesseeUserId(), + item.GetAccesser().GetAccesserDeviceId())); + } + } + } + for (auto item : delProfileMap) { + for (auto it = profiles.begin(); it != profiles.end();) { + if (item.first == it->GetAccessControlId()) { + it = profiles.erase(it); + } else { + it++; + } + } + } +} + +bool DeviceManagerServiceImpl::CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, + DistributedDeviceProfile::AccessControlProfile lastprofile) +{ + if ((delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && + delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccesser().GetAccesserUserId() && + delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && + delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccessee().GetAccesseeUserId()) || + (delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && + delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccessee().GetAccesseeUserId() && + delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && + delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccesser().GetAccesserUserId())) { + return true; + } + return false; +} + std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) { LOGI("localUserId %{public}d.", localUserId); @@ -2048,21 +2159,34 @@ void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() std::vector profiles = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); std::string remoteUdid = ""; + int32_t remoteUserId = -1; int64_t currentTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localDeviceId); for (auto &item : profiles) { if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { continue; } if ((currentTime - item.GetLastAuthTime()) > MAX_ALWAYS_ALLOW_SECONDS && item.GetLastAuthTime() > 0) { DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); + if (item.GetAccesser().GetAccesserUserId() == currentUserId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + remoteUserId = item.GetAccessee().GetAccesseeUserId(); + } + if (item.GetAccessee().GetAccesseeUserId() == currentUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + remoteUserId = item.GetAccesser().GetAccesserUserId(); + } remoteUdid = item.GetTrustDeviceId(); - CheckDeleteCredential(remoteUdid); + CheckDeleteCredential(remoteUdid, remoteUserId); } } } -void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid) +void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) { std::vector profiles = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); @@ -2074,7 +2198,8 @@ void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUd } if (!leftAcl) { LOGI("CheckDeleteCredential delete credential"); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); } } @@ -2103,6 +2228,8 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const st LOGE("Acl not contain the pkgname bind data."); return ERR_DM_FAILED; } + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); if (static_cast(bindLevel) == APP) { ProcessInfo processInfo; processInfo.pkgName = pkgName; @@ -2116,7 +2243,8 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const st if (offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); return DM_OK; } } @@ -2126,27 +2254,33 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const st } if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); return DM_OK; } return ERR_DM_FAILED; } -int32_t DeviceManagerServiceImpl::DeleteSkIdAndCredId(DmOfflineParam offlineParam, int32_t userId) +int32_t DeviceManagerServiceImpl::DeleteSkIdAndCredId(DmOfflineParam offlineParam) { LOGI("DeleteSkIdAndCredId start."); int32_t ret = DM_OK; - for (auto skId : offlineParam.skIdVec) { - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId); + if (offlineParam.dmAclIdParamVec.empty()) { + return ret; + } + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + for (auto item : offlineParam.dmAclIdParamVec) { + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(item.userId, item.skId); if (ret != DM_OK) { - LOGE("Delete Session Key err, userId: %{public}d, skId: %{public}d, ret: %{public}d", userId, skId, ret); + LOGE("DeleteSessionKey err, userId:%{public}d, skId:%{public}d, ret:%{public}d", item.userId, item.skId, + ret); } - } - for (auto credId : offlineParam.credIdVec) { - ret = hiChainAuthConnector_->DeleteCredential(userId, credId); + ret = hiChainAuthConnector_->DeleteCredential(item.userId, item.credId); if (ret != DM_OK) { - LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", userId, credId.c_str(), ret); + LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", item.userId, + item.credId.c_str(), ret); } + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.accessControlId); } return ret; } @@ -2161,28 +2295,29 @@ int32_t DeviceManagerServiceImpl::DeleteProcAcl(uint32_t tokenId, const std::str return ERR_DM_FAILED; } if (static_cast(bindLevel) == APP || static_cast(bindLevel) == SERVICE) { + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); if (offlineParam.leftAclNumber != 0) { LOGI("The tokenId unbind app-level type leftAclNumber not zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return DM_OK; } if (offlineParam.leftAclNumber == 0 && offlineParam.isLnnAcl) { LOGI("The tokenId unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return DM_OK; } } if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return DM_OK; } if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0 && offlineParam.isLnnAcl) { LOGI("Unbind deivce-level, retain null."); - DeleteSkIdAndCredId(offlineParam, userId); + DeleteSkIdAndCredId(offlineParam); return DM_OK; } return ERR_DM_FAILED; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 7cabe0aa3..98fb8feea 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -499,8 +499,9 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local return; } -void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) +void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) { + (void)peerUdids; (void)preUserId; return; } @@ -621,9 +622,10 @@ void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() return; } -void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid) +void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) { (void)remoteUdid; + (void)remoteUserId; return; } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 736c75c9d..70e4a411e 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -306,10 +306,15 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) hiChainConnector_->DeleteTimeOutGroup((idIter->second).c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) DeleteGroupByDP(idIter->second); - uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second); + DmOfflineParam offlineParam; + uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second, offlineParam); if (res == 0) { - hiChainAuthConnector_->DeleteCredential(idIter->second, - MultipleUserConnector::GetCurrentAccountUserID()); + if (offlineParam.skIdVec.empty()) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(idIter->second, + MultipleUserConnector::GetCurrentAccountUserID(), offlineParam.peerUserId); + } + DeleteSkIdAndCredId(offlineParam); } #endif stateTimerInfoMap_.erase(iter); @@ -318,6 +323,30 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) } } +int32_t DmDeviceStateManager::DeleteSkIdAndCredId(DmOfflineParam offlineParam) +{ + LOGI("DeleteSkIdAndCredId start."); + int32_t ret = DM_OK; + if (offlineParam.dmAclIdParamVec.empty()) { + return ret; + } + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + for (auto item : offlineParam.dmAclIdParamVec) { + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(item.userId, item.skId); + if (ret != DM_OK) { + LOGE("DeleteSessionKey err, userId:%{public}d, skId:%{public}d, ret:%{public}d", item.userId, item.skId, + ret); + } + ret = hiChainAuthConnector_->DeleteCredential(item.userId, item.credId); + if (ret != DM_OK) { + LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", item.userId, + item.credId.c_str(), ret); + } + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.accessControlId); + } + return ret; +} + void DmDeviceStateManager::StartEventThread() { LOGI("StartEventThread begin"); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 4fc1b9c06..3a45e993f 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -240,7 +240,7 @@ public: const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) = 0; - virtual void HandleUserRemoved(int32_t preUserId) = 0; + virtual void HandleUserRemoved(std::vector peerUdids, int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, int32_t beforeUserId) = 0; @@ -262,7 +262,7 @@ public: const std::string &localUdid, int32_t localUserId, const std::string &localAccountId) = 0; virtual int32_t RegisterAuthenticationType(int32_t authenticationType) = 0; virtual void DeleteAlwaysAllowTimeOut() = 0; - virtual void CheckDeleteCredential(const std::string &remoteUdid) = 0; + virtual void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) = 0; virtual int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId) = 0; virtual void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, int32_t remoteTokenId) = 0; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 3992ba4b1..fed2d2aba 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2154,7 +2154,7 @@ void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) if (!peerUdids.empty()) { // Send UserId Removed broadcast SendUserRemovedBroadCast(peerUdids, removedUserId); - dmServiceImpl_->HandleUserRemoved(removedUserId); + dmServiceImpl_->HandleUserRemoved(peerUdids, removedUserId); } } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 4a3729233..60c3529f9 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -1309,7 +1309,7 @@ int32_t SoftbusListener::GetAllTrustedDeviceList(const std::string &pkgName, con #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) (void)extra; std::vector allProfile = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); for (DistributedDeviceProfile::AccessControlProfile profile : allProfile) { if (profile.GetBindType() == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP) { continue; diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index 5c81e1a9f..0a3087fc2 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -79,6 +79,7 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index 1b8ea38d2..e0278c801 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -80,6 +80,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn index 34dc2e750..1d394b8ad 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("DmAuthManagerFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn index 1a3818c44..17b0edcfd 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn +++ b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("HichainConnectorFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn index b86115727..dd8015779 100644 --- a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn +++ b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn @@ -57,6 +57,7 @@ ohos_fuzztest("OnDataReceivedFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onerror_fuzzer/BUILD.gn b/test/commonfuzztest/onerror_fuzzer/BUILD.gn index 2b3aa462a..9d9d2801d 100644 --- a/test/commonfuzztest/onerror_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onerror_fuzzer/BUILD.gn @@ -56,6 +56,7 @@ ohos_fuzztest("OnErrorFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn index 6883f3964..3881335e7 100644 --- a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn @@ -56,6 +56,7 @@ ohos_fuzztest("OnFinishFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn index 34ea316f9..34a301d7a 100644 --- a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn @@ -57,6 +57,7 @@ ohos_fuzztest("OnRequestFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index d0ed88960..67a989cd4 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -783,7 +783,7 @@ HWTEST_F(DmAuthManagerTest, ImportCredential001, testing::ext::TestSize.Level1) { std::string deviceId = "deviceId"; std::string publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = authManager_->ImportCredential(deviceId, publicKey); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -794,13 +794,13 @@ HWTEST_F(DmAuthManagerTest, ResponseCredential001, testing::ext::TestSize.Level1 ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authResponseContext_->publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(DM_OK)); authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1834,7 +1834,7 @@ HWTEST_F(DmAuthManagerTest, RequestCredentialDone_003, testing::ext::TestSize.Le ASSERT_EQ(authManager_->isAuthDevice_, false); authManager_->authResponseContext_->publicKey = "publicKey"; - EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*hiChainAuthConnectorMock_, ImportCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); authManager_->RequestCredentialDone(); ASSERT_EQ(authManager_->isAuthDevice_, false); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index e1ebd3cfe..f1c44fb8a 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -1585,7 +1585,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level authManager_->authResponseContext_->isOnline = true; EXPECT_CALL(*softbusConnectorMock_, CheckIsOnline(_)).WillOnce(Return(true)); - EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _, _)).WillOnce(Return(true)); authManager_->GetAuthRequestContext(); JsonObject jsonPeerGroupIdObj; @@ -1652,7 +1652,8 @@ HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level1) authManager_->ProcessAuthRequest(sessionId); authManager_->authResponseContext_->haveCredential = true; - EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).Times(::testing::AtLeast(2)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, + QueryCredential(_, _, _)).Times(::testing::AtLeast(2)).WillOnce(Return(true)); authManager_->GetAuthRequestContext(); authManager_->authResponseContext_->isOnline = true; diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 88d823b1d..2e149b673 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -944,7 +944,11 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes DmAccessee dmAccessee; int32_t userId = 123456; std::string localDeviceId = "deviceId"; - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId); + std::vector peerUdids; + std::multimap peerUserIdMap; + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId, peerUdids, peerUserIdMap, + offlineParam); int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); EXPECT_EQ(ret, DM_OK); } @@ -1084,7 +1088,8 @@ HWTEST_F(DeviceProfileConnectorTest, CheckDevIdInAclForDevBind_001, testing::ext HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_001, testing::ext::TestSize.Level1) { std::string deviceId; - uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); + DmOfflineParam offlineParam; + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId, offlineParam); EXPECT_EQ(ret, 0); } @@ -1340,7 +1345,8 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_004, testing:: HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_002, testing::ext::TestSize.Level1) { std::string deviceId = "remoteDeviceId"; - uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); + DmOfflineParam offlineParam; + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId, offlineParam); EXPECT_EQ(ret, 0); } @@ -1464,36 +1470,41 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext int32_t localUserId = 444; std::string peerUdid = "deviceId"; int32_t peerUserId = 555; + DmOfflineParam offlineParam; bool ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); + peerUdid, peerUserId, offlineParam); EXPECT_FALSE(ret); localUdid = "deviceId"; localUserId = 123456; peerUdid = "deviceId"; peerUserId = 456; - ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId, + offlineParam); EXPECT_FALSE(ret); localUdid = "deviceId"; localUserId = 123456; peerUdid = "deviceId"; peerUserId = 123456; - ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId, + offlineParam); EXPECT_TRUE(ret); localUdid = "localDeviceId"; localUserId = 123456; peerUdid = "remoteDeviceId"; peerUserId = 123456; - ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId, + offlineParam); EXPECT_FALSE(ret); localUdid = "remoteDeviceId"; localUserId = 1234; peerUdid = "localDeviceId"; peerUserId = 1234; - ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId, + offlineParam); EXPECT_TRUE(ret); } @@ -2128,12 +2139,13 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForRemoteUserRemoved_001, testing: std::string peerUdid = "deviceId"; int32_t peerUserId = 123456; std::vector userIds; - DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(peerUdid, peerUserId, userIds); + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(peerUdid, peerUserId, userIds, offlineParam); EXPECT_FALSE(userIds.empty()); peerUdid = "remoteDeviceId"; peerUserId = 1234; - DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(peerUdid, peerUserId, userIds); + DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(peerUdid, peerUserId, userIds, offlineParam); EXPECT_FALSE(userIds.empty()); } diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 7f777ce50..081b33071 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -239,8 +239,9 @@ HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAclForAccountLogOut_001, testin int32_t localUserId = 1; std::string peerUdid = "peer_device_id"; int32_t peerUserId = 2; + DmOfflineParam offlineParam; EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAllAccessControlProfile(_)).WillOnce(Return(DM_OK)); - int32_t result = connector.DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + int32_t result = connector.DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId, offlineParam); EXPECT_EQ(result, false); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 9058c5861..54f958727 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -286,7 +286,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_001, testing::ext::TestSize.L { std::string localUdid = "2131351352"; int32_t osAccountId = 0; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_EQ(ret, false); } @@ -297,7 +298,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L jsonObject["publicKey"] = 0; std::string localUdid = SafetyDump(jsonObject); int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_EQ(ret, false); } @@ -310,7 +312,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_FALSE(ret); } @@ -323,8 +326,9 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); - EXPECT_FALSE(ret); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + EXPECT_TRUE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.Level1) @@ -335,9 +339,9 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; - int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); - EXPECT_FALSE(ret); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + EXPECT_TRUE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.Level1) @@ -349,7 +353,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_FALSE(ret); } @@ -362,8 +367,9 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); - EXPECT_FALSE(ret); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); + EXPECT_TRUE(ret); } HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.Level1) @@ -375,7 +381,8 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; - bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + int32_t peerOsAccountId = -1; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_TRUE(ret); } @@ -468,7 +475,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_001, testing::ext::TestSize. int32_t localUdid = 0; std::string deviceId; std::string publicKey; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); EXPECT_NE(ret, DM_OK); } @@ -477,7 +485,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestSize. int32_t localUdid = 0; std::string deviceId = "4513541351"; std::string publicKey = "42125143613"; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); EXPECT_NE(ret, DM_OK); } @@ -488,8 +497,9 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_003, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); - EXPECT_EQ(ret, ERR_DM_FAILED); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize.Level1) @@ -499,8 +509,9 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); - EXPECT_EQ(ret, ERR_DM_FAILED); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize.Level1) @@ -510,8 +521,9 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1})"; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); - EXPECT_EQ(ret, ERR_DM_FAILED); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize.Level1) @@ -521,7 +533,8 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize. std::string publicKey = "test"; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 0})"; - int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + int32_t peerUserId = 0; + int32_t ret = hiChain_->ImportCredential(localUdid, peerUserId, deviceId, publicKey); EXPECT_EQ(ret, DM_OK); } @@ -529,7 +542,8 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_001, testing::ext::TestSize. { std::string deviceId; int32_t userId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + int32_t peerUserId = 0; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); EXPECT_EQ(ret, DM_OK); } @@ -537,7 +551,8 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_002, testing::ext::TestSize. { std::string deviceId = "864513535"; int32_t userId = 0; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + int32_t peerUserId = 0; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); EXPECT_EQ(ret, DM_OK); } @@ -547,8 +562,9 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_003, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId); - EXPECT_EQ(ret, 0); + int32_t peerUserId = 0; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + EXPECT_EQ(ret, 0) } HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize.Level1) @@ -557,8 +573,9 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId); - EXPECT_EQ(ret, ERR_DM_FAILED); + int32_t peerUserId = 0; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize.Level1) @@ -567,8 +584,9 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize. int32_t userId = 0; g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 100})"; - int32_t ret = hiChain_->DeleteCredential(deviceId, userId); - EXPECT_EQ(ret, 100); + int32_t peerUserId = 0; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); + EXPECT_EQ(ret, DM_OK); } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index 160628a41..21041b11a 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -77,6 +77,7 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn b/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn index 8c61184f5..a7088be2b 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("DeviceProfileConnectorFuzzTest") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "init:libbegetutil", "ipc:ipc_single", ] diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index c7875807c..7629856a1 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -56,6 +56,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) dmAccessee.trustBundleName = trustBundleName; int32_t userId = fdp.ConsumeIntegral(); std::string accountId(reinterpret_cast(data), size); + DmOfflineParam offlineParam; DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); @@ -63,7 +64,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, localDeviceId); - DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId); + DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId, offlineParam); DeviceProfileConnector::GetInstance().GetTrustNumber(localDeviceId); } } diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index 78697ead4..7c353daa9 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -71,6 +71,7 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index fb7eeaba4..a43f96e63 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -71,6 +71,7 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn index 680c3e943..cb057edf6 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn @@ -64,6 +64,7 @@ ohos_fuzztest("OnSessionOpenedFuzzTest") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "init:libbegetutil", "safwk:system_ability_fwk", ] diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index eba271921..29347d8d8 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1140,6 +1140,8 @@ ohos_unittest("UTTest_dm_device_state_manager") { external_deps = [ "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "ffrt:libffrt", "googletest:gmock", @@ -1166,6 +1168,8 @@ ohos_unittest("UTTest_dm_device_state_manager_two") { external_deps = [ "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "ffrt:libffrt", "googletest:gmock", diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 37672cddf..1cf057d1b 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -470,7 +470,7 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L devIdAndUserMap.insert(std::make_pair("devId02", 102)); devIdAndUserMap.insert(std::make_pair("devId03", 103)); EXPECT_CALL(*deviceProfileConnectorMock_, GetDevIdAndUserIdByActHash(_, _, _, _)).WillOnce(Return(devIdAndUserMap)); - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _, _)) .Times(::testing::AtLeast(3)).WillOnce(Return(true)); deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); @@ -478,7 +478,7 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t localUserId = 123; std::string peerUdid = "peerUdid"; int32_t peerUserId = 456; - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _, _)).WillOnce(Return(true)); deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); @@ -1407,16 +1407,17 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::T HWTEST_F(DeviceManagerServiceImplTest, CheckDeleteCredential_001, testing::ext::TestSize.Level1) { std::string remoteUdid = "123456"; + int32_t remoteUserId = -1; std::vector profiles; AddAccessControlProfileFirst(profiles); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); std::vector profiles1; AddAccessControlProfileFirst(profiles1); remoteUdid = "666678"; EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles1)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); } HWTEST_F(DeviceManagerServiceImplTest, DeleteAlwaysAllowTimeOut_001, testing::ext::TestSize.Level1) @@ -1513,10 +1514,11 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); int32_t userId = 100; std::string accountId = "60008"; - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) + std::vector peerUdids; + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); - deviceManagerServiceImpl_->HandleUserRemoved(userId); + deviceManagerServiceImpl_->HandleUserRemoved(peerUdids, userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1854,7 +1856,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T int32_t localUserId = 123456; std::string peerUdid = "remoteUdid"; int32_t peerUserId = 1; - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _, _)).WillOnce(Return(true)); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } @@ -1923,7 +1925,7 @@ HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::T std::vector localUserIds; localUserIds.push_back(123); localUserIds.push_back(456); - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForRemoteUserRemoved(_, _, _)) + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForRemoteUserRemoved(_, _, _, _)) .WillOnce(DoAll(SetArgReferee<2>(localUserIds), Return())); deviceManagerServiceImpl_->HandleRemoteUserRemoved(userId, remoteUdid); } @@ -2005,7 +2007,7 @@ HWTEST_F(DeviceManagerServiceImplTest, RegisterAuthenticationType_001, testing:: int32_t userId = 0; std::string remoteUdid = "remoteUdid"; std::vector localUserIds; - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForRemoteUserRemoved(_, _, _)) + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForRemoteUserRemoved(_, _, _, _)) .WillOnce(DoAll(SetArgReferee<2>(localUserIds), Return())); deviceManagerServiceImpl_->HandleRemoteUserRemoved(userId, remoteUdid); } @@ -2059,14 +2061,15 @@ HWTEST_F(DeviceManagerServiceImplTest, DeleteCredential_010, testing::ext::TestS deviceManagerServiceImpl_->DeleteAlwaysAllowTimeOut(); std::string remoteUdid = "remoteUdid"; + int32_t remoteUserId = -1; profiles.clear(); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); accessProfile.SetTrustDeviceId(remoteUdid); profiles.push_back(accessProfile); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); - deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid); + deviceManagerServiceImpl_->CheckDeleteCredential(remoteUdid, remoteUserId); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index c01e5136a..af21d1fa7 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -65,7 +65,7 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, GetDeviceIdAndUserId_101, testing::e int32_t localUserId = 123456; std::string peerUdid = "remoteUdid"; int32_t peerUserId = 1; - EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _, _)).WillOnce(Return(true)); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index cecb212ce..f6bccb76d 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -51,10 +51,10 @@ std::map DeviceProfileConnector::GetUserIdAndBindLevel(const s } bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, DmOfflineParam &offlineParam) { return DmDeviceProfileConnector::dmDeviceProfileConnector->DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); + peerUdid, peerUserId, offlineParam); } DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, @@ -94,10 +94,10 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string } void DeviceProfileConnector::DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, - std::vector &userIds) + std::vector &userIds, DmOfflineParam &offlineParam) { return DmDeviceProfileConnector::dmDeviceProfileConnector->DeleteAclForRemoteUserRemoved(peerUdid, peerUserId, - userIds); + userIds, offlineParam); } DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index 5fa664674..9241698c7 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -36,7 +36,7 @@ public: virtual std::map GetUserIdAndBindLevel(const std::string &localUdid, const std::string &peerUdid) = 0; virtual bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) = 0; + const std::string &peerUdid, int32_t peerUserId, DmOfflineParam &offlineParam) = 0; virtual DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) = 0; virtual std::multimap GetDevIdAndUserIdByActHash(const std::string &localUdid, @@ -48,7 +48,7 @@ public: virtual DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra) = 0; virtual void DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, - std::vector &userIds) = 0; + std::vector &userIds, DmOfflineParam &offlineParam) = 0; virtual DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) = 0; virtual std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, @@ -77,7 +77,8 @@ public: const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); - MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t)); + MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t, + DmOfflineParam &)); MOCK_METHOD((DmOfflineParam), HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &)); MOCK_METHOD((std::multimap), GetDevIdAndUserIdByActHash, (const std::string &, @@ -87,7 +88,7 @@ public: MOCK_METHOD((std::vector), GetBindTypeByPkgName, (std::string, std::string, std::string)); MOCK_METHOD(DmOfflineParam, DeleteAccessControlList, (const std::string &, const std::string &, const std::string &, int32_t, const std::string &)); - MOCK_METHOD(void, DeleteAclForRemoteUserRemoved, (std::string, int32_t, std::vector &)); + MOCK_METHOD(void, DeleteAclForRemoteUserRemoved, (std::string, int32_t, std::vector &, DmOfflineParam &)); MOCK_METHOD((DmOfflineParam), HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &, int32_t)); MOCK_METHOD((std::unordered_map), GetAppTrustDeviceList, diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index dd7f98ffb..7c4240db3 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -19,9 +19,9 @@ namespace OHOS { namespace DistributedHardware { -bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) { - return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); + return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId, peerOsAccountId); } int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) @@ -29,9 +29,11 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthDevice(pinCode, osAccountId, udid, requestId); } -int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) +int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, + std::string publicKey) { - return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, deviceId, publicKey); + return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, peerOsAccountId, deviceId, + publicKey); } int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index d0de67f9e..a7c5f0e3e 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -26,10 +26,10 @@ class DmHiChainAuthConnector { public: virtual ~DmHiChainAuthConnector() = default; public: - virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId) = 0; - virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, - std::string udid, int64_t requestId) = 0; - virtual int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) = 0; + virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId, int32_t peerOsAccountId) = 0; + virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) = 0; + virtual int32_t ImportCredential(int32_t osAccountId, int32_t peerOsAccountId, std::string deviceId, + std::string publicKey) = 0; virtual int32_t ProcessCredData(int64_t authReqId, const std::string &data) = 0; virtual int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) = 0; @@ -46,9 +46,9 @@ public: class HiChainAuthConnectorMock : public DmHiChainAuthConnector { public: - MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); + MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t, int32_t)); MOCK_METHOD(int32_t, AuthDevice, (int32_t, int32_t, std::string, int64_t)); - MOCK_METHOD(int32_t, ImportCredential, (int32_t, std::string, std::string)); + MOCK_METHOD(int32_t, ImportCredential, (int32_t, int32_t, std::string, std::string)); MOCK_METHOD(int32_t, ProcessCredData, (int64_t, const std::string &)); MOCK_METHOD(int32_t, AddCredential, (int32_t, const std::string &, std::string &)); -- Gitee From 2b3f7221091dcd57b513258fb9fbf4ab917c4a69 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 11:19:26 +0800 Subject: [PATCH 16/38] modify Signed-off-by: BrainL --- .../include/authentication_v2/dm_auth_message_processor.h | 8 ++++---- .../dependency/MSDP/spatial_location_callback_impl.h | 2 +- .../implementation/src/authentication_v2/auth_manager.cpp | 6 +++--- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 1 - .../src/authentication_v2/dm_auth_message_processor.cpp | 6 +++--- .../dependency/MSDP/spatial_location_callback_impl.cpp | 4 ++-- 6 files changed, 13 insertions(+), 14 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4810d4a6a..83a4a2ecb 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -99,7 +99,11 @@ enum DmMessageType { MSG_TYPE_REQ_ACL_NEGOTIATE = 80, MSG_TYPE_RESP_ACL_NEGOTIATE = 90, MSG_TYPE_REQ_USER_CONFIRM = 100, + MSG_TYPE_FORWARD_ULTRASONIC_START = 101, + MSG_TYPE_REVERSE_ULTRASONIC_START = 102, MSG_TYPE_RESP_USER_CONFIRM = 110, + MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE = 111, + MSG_TYPE_REVERSE_ULTRASONIC_DONE = 112, MSG_TYPE_REQ_PIN_AUTH_START = 120, MSG_TYPE_RESP_PIN_AUTH_START = 130, MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE = 121, @@ -114,10 +118,6 @@ enum DmMessageType { MSG_TYPE_RESP_DATA_SYNC = 190, MSG_TYPE_AUTH_REQ_FINISH = 200, MSG_TYPE_AUTH_RESP_FINISH = 201, - MSG_TYPE_REVERSE_ULTRASONIC_START = 102, - MSG_TYPE_REVERSE_ULTRASONIC_DONE = 112, - MSG_TYPE_FORWARD_ULTRASONIC_START = 101, - MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE = 111, }; struct DmAccessControlTable { diff --git a/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h index e79704e5d..1c337473d 100644 --- a/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h +++ b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 521895e5a..f8c282569 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -466,10 +466,10 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); - if (tempInfo == DM_ULTRASONIC_FORWARD) { - context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; - } else if (tempInfo == DM_ULTRASONIC_REVERSE) { + if (tempInfo == DM_ULTRASONIC_REVERSE) { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } else { + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; } LOGI("ultrasonic side is %{public}d", context_->ultrasonicInfo); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 819e86b34..011927b2e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -807,7 +807,6 @@ int32_t AuthSinkForwardUltrasonicDoneState::Action(std::shared_ptrtimer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); context->pinNegotiateStarted = true; - LOGI("AuthSinkForwardUltrasonicDoneState::Action context->transmitData = %{public}s.", context->transmitData.c_str()); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthSinkForwardUltrasonicDoneState::Action call ProcessCredData err"); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index a4fddf5cd..fb116fbd0 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -947,10 +947,10 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje } if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); - if (tempInfo == DM_ULTRASONIC_FORWARD) { - context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; - } else if (tempInfo == DM_ULTRASONIC_REVERSE) { + if (tempInfo == DM_ULTRASONIC_REVERSE) { context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } else { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; } LOGI("DmAuthMessageProcessor::ParseNegotiateMessage ultrasonicInfo=%{public}d", context->ultrasonicInfo); } diff --git a/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp index 7ec3d5ae4..41b45a985 100644 --- a/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp +++ b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -41,7 +41,7 @@ return; } if (!IsValidPinCodeStr(pinCodeResponse.pincode)) { - LOGE("OnPinCodeChanged pincode is invalid, pinCode = %{public}s.", pinCodeResponse.pincode.c_str()); + LOGE("OnPinCodeChanged pincode is invalid"); return; } if (context_ == nullptr) { -- Gitee From ebe418f8fa4b78a12c6c44487db465d3bdbd32e2 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 14 Apr 2025 21:35:39 +0800 Subject: [PATCH 17/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=91=8A=E8=AD=A6=20Si?= =?UTF-8?q?gned-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/deviceprofile_connector.cpp | 7 +- .../dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 14 +++ .../src/authentication_v2/auth_manager.cpp | 2 +- .../auth_stages/auth_confirm.cpp | 93 +++++++++------- .../auth_stages/auth_credential.cpp | 12 +-- .../auth_stages/auth_negotiate.cpp | 100 +++++++++++------- .../dm_auth_message_processor.cpp | 3 +- .../src/authentication_v2/dm_auth_state.cpp | 2 - .../dependency/softbus/softbus_connector.cpp | 2 +- .../src/device_manager_service_impl.cpp | 7 +- .../UTTest_dm_deviceprofile_connector.cpp | 6 +- .../unittest/UTTest_auth_credential_state.cpp | 1 - 13 files changed, 151 insertions(+), 99 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index ac81fa165..9694e73b4 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -192,7 +192,7 @@ std::string DeviceProfileConnector::AccessToStr(DistributedDeviceProfile::Access jsonAcLObj[TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); jsonAcLObj[TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); jsonAcLObj[TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); - //TODO accessee + DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); jsonAcLObj[TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); jsonAcLObj[TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); @@ -238,8 +238,8 @@ std::vector DeviceProfileConnect return aclList; } -EXPORT std::string DeviceProfileConnector::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, - int32_t tokenId, int32_t userId) +EXPORT std::string DeviceProfileConnector::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, + std::string remoteUdid, int32_t tokenId, int32_t userId) { LOGI("localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); @@ -620,7 +620,6 @@ std::vector DeviceProfileConnector::GetAclProfileByDeviceI std::vector DeviceProfileConnector::GetAclProfileByDeviceIdAndUserId(const std::string &deviceId, int32_t userId, const std::string &remoteDeviceId) { - std::vector aclProfileVec; std::vector profiles = GetAllAccessControlProfile(); for (auto &item : profiles) { diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4565b12df..943851be1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -260,6 +260,7 @@ private: int32_t CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); // Construct the 161, 170, and 171 credential authentication messages int32_t CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateNegotiateOldMessage(std::shared_ptr context, JsonObject &jsonObject); // Construct the 180 and 190 sync messages int32_t CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject); // Create the 190 message diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 896bd4cb2..e5fb0c308 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -175,6 +175,8 @@ private: void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + void GetSrcAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); bool IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool ShareAclCompare(std::shared_ptr context, @@ -185,8 +187,13 @@ private: const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool CheckCredIdInAcl(std::shared_ptr context, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, + bool &checkResult); void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson); + void GetSrcCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, + JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); }; class AuthSinkStatePinAuthComm { @@ -399,6 +406,8 @@ private: void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + void GetSinkAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); bool IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool ShareAclCompare(std::shared_ptr context, @@ -409,8 +418,13 @@ private: const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool CheckCredIdInAcl(std::shared_ptr context, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, + bool &checkResult); void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson); + void GetSinkCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, + JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); }; class AuthSinkDataSyncState : public DmAuthState { diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7edf86dc6..505c4fbc9 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -384,7 +384,7 @@ void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) if (!IsHmlSessionType(context_->connSessionType)) { return; } - if(context_->connDelayCloseTime == 0){ + if (context_->connDelayCloseTime == 0) { context_->connDelayCloseTime = HML_SESSION_TIMEOUT; } if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 421269c60..84700a8cb 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -143,23 +143,14 @@ void AuthSrcConfirmState::GetSrcCredType(std::shared_ptr context, context->accesser.credentialInfos[credType] = item.Dump(); break; case DM_POINT_TO_POINT: - if (!aclInfo.Contains("pointTopointAcl") || - (context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != - item[FILED_CRED_ID].Get() && - context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != - item[FILED_CRED_ID].Get())) { - deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); - } else { - credTypeJson["pointTopointCredType"] = credType; - context->accesser.credentialInfos[credType] = item.Dump(); - } + GetSrcCredTypeForP2P(context, item, aclInfo, credTypeJson, credType, deleteCredInfo); break; case DM_LNN: if (!aclInfo.Contains("lnnAcl") || (context->accesser.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != - item[FILED_CRED_ID].Get() && + item[FILED_CRED_ID].Get() && context->accesser.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != - item[FILED_CRED_ID].Get())) { + item[FILED_CRED_ID].Get())) { deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); } else { credTypeJson["lnnCredType"] = credType; @@ -177,6 +168,22 @@ void AuthSrcConfirmState::GetSrcCredType(std::shared_ptr context, } } +void AuthSrcConfirmState::GetSrcCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, + JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo) +{ + CHECK_NULL_VOID(context); + if (!aclInfo.Contains("pointTopointAcl") || + (context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != + credObj[FILED_CRED_ID].Get() && + context->accesser.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != + credObj[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(credObj[FILED_CRED_ID].Get()); + } else { + credTypeJson["pointTopointCredType"] = credType; + context->accesser.credentialInfos[credType] = credObj.Dump(); + } +} + void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo) { @@ -209,16 +216,7 @@ void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, } break; case DM_POINT_TO_POINT: - if (Point2PointAclCompare(context, item.GetAccesser(), item.GetAccessee()) && - CheckCredIdInAcl(context, item, credInfo, DM_POINT_TO_POINT)) { - aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; - context->accesser.aclProfiles[DM_POINT_TO_POINT] = item; - } - if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && - CheckCredIdInAcl(context, item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { - aclInfo["lnnAcl"] = DM_LNN; - context->accesser.aclProfiles[DM_LNN] = item; - } + GetSrcAclInfoForP2P(context, item, credInfo, aclInfo); break; default: LOGE("invalid bindType %{public}d.", item.GetBindType()); @@ -231,6 +229,22 @@ void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, } } +void AuthSrcConfirmState::GetSrcAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + if (Point2PointAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_POINT_TO_POINT)) { + aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accesser.aclProfiles[DM_POINT_TO_POINT] = profile; + } + if (LnnAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_LNN) && profile.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accesser.aclProfiles[DM_LNN] = profile; + } +} + bool AuthSrcConfirmState::CheckCredIdInAcl(std::shared_ptr context, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) { @@ -264,20 +278,7 @@ bool AuthSrcConfirmState::CheckCredIdInAcl(std::shared_ptr contex } break; case DM_POINT_TO_POINT: - if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { - std::vector appList; - credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); - const size_t APP_LIST_SIZE = 2; - if (appList.size() >= APP_LIST_SIZE && - ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && - std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || - (std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1] && - std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0]))) { - checkResult = true; - } else { - DeleteAcl(context, profile); - } - } + CheckCredIdInAclForP2P(context, credId, profile, credInfo, bindType, checkResult); break; default: break; @@ -285,6 +286,26 @@ bool AuthSrcConfirmState::CheckCredIdInAcl(std::shared_ptr contex return checkResult; } +void AuthSrcConfirmState::CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, + bool &checkResult) +{ + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + const size_t APP_LIST_SIZE = 2; + if (appList.size() >= APP_LIST_SIZE && + ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || + (std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0]))) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + } +} + bool AuthSrcConfirmState::IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 9f1169a0c..596222221 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -39,7 +39,7 @@ constexpr const char* TAG_LOWER_USER_ID = "userId"; constexpr const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; // decrypt process -int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) +int32_t g_authCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { if (context->transmitData.empty()) { LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData failed."); @@ -95,7 +95,7 @@ DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) { // decrypt and transmit transmitData - int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + int32_t ret = g_authCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { return ret; } @@ -112,7 +112,7 @@ DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) { // decrypt and transmit transmitData - int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); + int32_t ret = g_authCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); if (ret != DM_OK) { return ret; } @@ -124,7 +124,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co } DmMessageType msgType; int32_t skId; - ret = context->authMessageProcessor->SaveSessionKeyToDP(context->accesser.userId ,skId); + ret = context->authMessageProcessor->SaveSessionKeyToDP(context->accesser.userId, skId); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); return ret; @@ -175,7 +175,7 @@ int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr { context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + int32_t ret = g_authCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { return ret; } @@ -190,7 +190,7 @@ DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) { - int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + int32_t ret = g_authCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { return ret; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index fa3ee432d..6ccf5560c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -239,23 +239,14 @@ void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptraccessee.credentialInfos[credType] = item.Dump(); break; case DM_POINT_TO_POINT: - if (!aclInfo.Contains("pointTopointAcl") || - (context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != - item[FILED_CRED_ID].Get() && - context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != - item[FILED_CRED_ID].Get())) { - deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); - } else { - credTypeJson["pointTopointCredType"] = credType; - context->accessee.credentialInfos[credType] = item.Dump(); - } + GetSinkCredTypeForP2P(context, item, aclInfo, credTypeJson, credType, deleteCredInfo); break; case DM_LNN: if (!aclInfo.Contains("lnnAcl") || (context->accessee.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != - item[FILED_CRED_ID].Get() && + item[FILED_CRED_ID].Get() && context->accessee.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != - item[FILED_CRED_ID].Get())) { + item[FILED_CRED_ID].Get())) { deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); } else { credTypeJson["lnnCredType"] = credType; @@ -273,6 +264,23 @@ void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptr context, + const JsonItemObject &credObj, JsonObject &aclInfo, JsonObject &credTypeJson, + int32_t credType, std::vector &deleteCredInfo) +{ + CHECK_NULL_VOID(context); + if (!aclInfo.Contains("pointTopointAcl") || + (context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != + credObj[FILED_CRED_ID].Get() && + context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != + credObj[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(credObj[FILED_CRED_ID].Get()); + } else { + credTypeJson["pointTopointCredType"] = credType; + context->accessee.credentialInfos[credType] = credObj.Dump(); + } +} + void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo) { @@ -286,7 +294,7 @@ void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptraccesser.deviceIdHash && trustDeviceIdHash != context->accessee.deviceIdHash) { LOGE("devId %{public}s hash %{public}s, er devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), - GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); + GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); continue; } bindLevel = item.GetBindLevel(); @@ -305,16 +313,7 @@ void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptraccessee.aclProfiles[DM_POINT_TO_POINT] = item; - } - if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && - CheckCredIdInAcl(context, item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { - aclInfo["lnnAcl"] = DM_LNN; - context->accessee.aclProfiles[DM_LNN] = item; - } + GetSinkAclInfoForP2P(context, item, credInfo, aclInfo); break; default: LOGE("invalid bindType %{public}d.", item.GetBindType()); @@ -327,6 +326,22 @@ void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + if (Point2PointAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_POINT_TO_POINT)) { + aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accessee.aclProfiles[DM_POINT_TO_POINT] = profile; + } + if (LnnAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_LNN) && profile.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accessee.aclProfiles[DM_LNN] = profile; + } +} + bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr context, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) { @@ -359,22 +374,7 @@ bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr() == bindType) { - std::vector appList; - credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); - const size_t APP_LIST_SIZE = 2; - if (appList.size() >= APP_LIST_SIZE && - ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && - std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || - (std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0] && - std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1]))) { - checkResult = true; - } else { - DeleteAcl(context, profile); - } - } else { - DeleteAcl(context, profile); - } + CheckCredIdInAclForP2P(context, credId, profile, credInfo, bindType, checkResult); break; default: break; @@ -382,6 +382,28 @@ bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr context, + std::string &credId, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, + uint32_t bindType, bool &checkResult) +{ + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + const size_t APP_LIST_SIZE = 2; + if (appList.size() >= APP_LIST_SIZE && + ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || + (std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0] && + std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1]))) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + } else { + DeleteAcl(context, profile); + } +} + bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index bc87c07c6..13a007404 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -512,7 +512,8 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr return DM_OK; } -int32_t CreateNegotiateOldMessage(std::shared_ptr context, JsonObject &jsonObject) +int32_t DmAuthMessageProcessor::CreateNegotiateOldMessage(std::shared_ptr context, + JsonObject &jsonObject) { jsonObject[TAG_CRYPTO_SUPPORT] = false; jsonObject[TAG_AUTH_TYPE] = context->authType; diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index dcc2c87f6..b5ad22c8b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -207,8 +207,6 @@ bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) return false; } - - void DmAuthState::SetAclExtraInfo(std::shared_ptr context) { DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 680c1c4fd..5e3342482 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -156,7 +156,7 @@ int32_t SoftbusConnector::SyncLocalAclListProcess(const std::string localUdid, i LOGE("ParaseAclChecksumList GetVersionNumber error"); return ERR_DM_FAILED; } - switch(versionNum) { + switch (versionNum) { case DM_VERSION_5_1_0: return SyncLocalAclList5_1_0(localUdid, localUserId, remoteUdid, remoteUserId, remoteAclListVec); default: diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 02f43f706..b111990fc 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -777,8 +777,8 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(i curSession->logicalSessionSet_.insert(logicalSessionId); std::string bundleName; int32_t displayId = 0; - if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { - bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + if (jsonObject[TAG_PEER_BUNDLE_NAME_V2].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME_V2].Get(); } if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); @@ -832,7 +832,7 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr std::map bindParam; auto authMgr = GetAuthMgrByTokenId(tokenId); authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); - int32_t authType = -1; + int32_t authType = -1; authMgr->ParseAuthType(bindParam, authType); authMgrMap_.erase(tokenId); if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId) != DM_OK) { @@ -1831,7 +1831,6 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - if (offlineParam.leftAclNumber != 0) { LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); CHECK_NULL_VOID(softbusConnector_); diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 88d823b1d..d41cb5b09 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1191,9 +1191,8 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::Tes int32_t remoteUserId = 0; std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; - int32_t bindType = DM_INVALIED_TYPE; DmOfflineParam offlineParam; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, offlineParam); EXPECT_EQ(bindType, DM_INVALIED_TYPE); } @@ -1418,9 +1417,8 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::Tes int32_t remoteUserId = 0; std::string remoteUdid; std::string localUdid = "localDeviceId"; - int32_t bindType = DM_INVALIED_TYPE; DmOfflineParam offlineParam; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, offlineParam); EXPECT_EQ(bindType, DM_INVALIED_TYPE); diff --git a/test/unittest/UTTest_auth_credential_state.cpp b/test/unittest/UTTest_auth_credential_state.cpp index bc555230e..b76d8011a 100644 --- a/test/unittest/UTTest_auth_credential_state.cpp +++ b/test/unittest/UTTest_auth_credential_state.cpp @@ -53,7 +53,6 @@ void AuthCredentialStateTest::SetUp() listener = std::make_shared(); hiChainAuthConnector = std::make_shared(); hiChainConnector = std::make_shared(); - } void AuthCredentialStateTest::TearDown() -- Gitee From cb375f5ae7943a4bec636f96277d253dec663c72 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 15 Apr 2025 11:40:22 +0800 Subject: [PATCH 18/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9crash=20Signed-off-by:?= =?UTF-8?q?=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../relationshipsyncmgr/relationship_sync_mgr.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 9b23cd5a2..823dd2a5b 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -583,13 +583,17 @@ std::string RelationShipChangeMsg::ToJson() const if (udidArrayObj == nullptr) { LOGE("cJSON_CreateArray failed"); cJSON_Delete(msg); - cJSON_Delete(udidArrayObj); return ""; } cJSON *udidStringObj = nullptr; for (uint32_t index = 0; index < peerUdids.size(); index++) { udidStringObj = cJSON_CreateString(peerUdids[index].c_str()); - if (udidStringObj == nullptr || !cJSON_AddItemToArray(udidArrayObj, udidStringObj)) { + if (udidStringObj == nullptr) { + cJSON_Delete(udidArrayObj); + cJSON_Delete(msg); + return ""; + } + if (!cJSON_AddItemToArray(udidArrayObj, udidStringObj)) { cJSON_Delete(udidStringObj); cJSON_Delete(udidArrayObj); cJSON_Delete(msg); @@ -602,15 +606,11 @@ std::string RelationShipChangeMsg::ToJson() const if (retStr == nullptr) { LOGE("to json is nullptr."); cJSON_Delete(msg); - cJSON_Delete(udidArrayObj); - cJSON_Delete(udidStringObj); return ""; } std::string ret = std::string(retStr); cJSON_Delete(msg); cJSON_free(retStr); - cJSON_Delete(udidArrayObj); - cJSON_Delete(udidStringObj); return ret; } -- Gitee From 8ea5adba94ad225e0ca3db1374a5ee84966a3c0c Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 14:38:32 +0800 Subject: [PATCH 19/38] modify Signed-off-by: BrainL --- .../auth_stages/auth_pin_auth.cpp | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 011927b2e..d68ec712e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -603,12 +603,9 @@ int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); return DM_OK; }); - //gen pin context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - //set pincode std::string ultraPinCode = std::to_string(context->pinCode); Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); - //send 102 context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_START, context); return DM_OK; @@ -621,7 +618,6 @@ DmAuthStateType AuthSrcReverseUltrasonicDoneState::GetStateType() int32_t AuthSrcReverseUltrasonicDoneState::Action(std::shared_ptr context) { - // sink从msdp接受成功 LOGI("AuthSrcReverseUltrasonicDoneState::Action Start."); context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -631,7 +627,6 @@ int32_t AuthSrcReverseUltrasonicDoneState::Action(std::shared_ptr LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); return ret; } - // 等待hiChain响应 transmit auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); @@ -653,7 +648,6 @@ DmAuthStateType AuthSrcForwardUltrasonicStartState::GetStateType() int32_t AuthSrcForwardUltrasonicStartState::Action(std::shared_ptr context) { LOGI("AuthSrcForwardUltrasonicStartState::Action Start."); - // 发送101报文 context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_START, context); LOGI("AuthSrcForwardUltrasonicStartState::Action End."); @@ -668,14 +662,12 @@ DmAuthStateType AuthSrcForwardUltrasonicDoneState::GetStateType() int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr context) { LOGI("AuthSrcForwardUltrasonicDoneState::Action Start."); - // 1.启动5s计时器 若到则切换至常规pin流程 context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { LOGI("AuthSrcForwardUltrasonicDoneState timeout."); Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); context->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_TIMEOUT); }); - // 2.从MSDP接口拿到pin并取消监听 sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); Msdp::SpatialAwarenessMgrClient::GetInstance().RegisterPinCallback(callback); auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_ULTRASONIC_PIN_CHANGED); @@ -713,14 +705,12 @@ DmAuthStateType AuthSinkReverseUltrasonicStartState::GetStateType() int32_t AuthSinkReverseUltrasonicStartState::Action(std::shared_ptr context) { LOGI("AuthSinkReverseUltrasonicStartState::Action Start."); - // 1.启动5s计时器 若到则切换至常规pin流程 context->timer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { LOGI("AuthSinkReverseUltrasonicStartState timeout."); Msdp::SpatialAwarenessMgrClient::GetInstance().UnregisterPinCallback(); context->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_TIMEOUT); }); - // 2.从MSDP接口拿到pin并取消监听 sptr callback = new(std::nothrow) SpatialLocationCallbackImpl(context); Msdp::SpatialAwarenessMgrClient::GetInstance().RegisterPinCallback(callback); auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_ULTRASONIC_PIN_CHANGED); @@ -753,17 +743,14 @@ int32_t AuthSinkReverseUltrasonicDoneState::Action(std::shared_ptrauthStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送130报文 LOGI("AuthSrcPinAuthStartState::AuthDevice ON_TRANSMIT."); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); return DM_OK; } if (retEvent == DmEventType::ON_ERROR) { LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); - // src侧在hichain中认证成功与否都发送120 sink侧与src侧的认证结果应当一致,故这里不需要再发130给src context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -784,12 +771,9 @@ int32_t AuthSinkForwardUltrasonicStartState::Action(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); return DM_OK; }); - // 生成pin context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - // SetPinCode std::string ultraPinCode = std::to_string(context->pinCode); Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); - // 发送111报文 context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, context); LOGI("AuthSinkForwardUltrasonicStartState::Action End."); @@ -812,17 +796,14 @@ int32_t AuthSinkForwardUltrasonicDoneState::Action(std::shared_ptrauthStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送130报文 LOGI("AuthSinkForwardUltrasonicDoneState::AuthDevice ON_TRANSMIT."); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); return DM_OK; } if (retEvent == DmEventType::ON_ERROR) { LOGI("AuthSinkForwardUltrasonicDoneState::AuthDevice ON_ERROR failed."); - // src侧在hichain中认证成功与否都发送120 sink侧与src侧的认证结果应当一致,故这里不需要再发130给src context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From ad067dced38e636aa8c1da0156493ada239912d8 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 16:21:38 +0800 Subject: [PATCH 20/38] modify Signed-off-by: BrainL --- .../include/authentication_v2/dm_auth_context.h | 13 +++++++------ .../src/authentication_v2/auth_manager.cpp | 9 +++++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 5c3f257e0..b0a4e7b32 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -92,6 +92,12 @@ enum { DM_SAME_GROUP_TYPE = 3, }; +enum DmUltrasonicInfo{ + DM_Ultrasonic_Forward = 0, // Phone->TV + DM_Ultrasonic_Reverse = 1, // Car->Phone + DM_Ultrasonic_Invalid = 2, +}; + // Used for one-touch pairing struct DmPeerTargetAddress { // directly establish a Bluetooth connection @@ -114,11 +120,6 @@ struct DmPeerTarget { DmPeerTargetAddress peerTargetAddress; }; -struct DmUltrasonicInfo{ - DM_Ultrasonic_Forward = 0; - DM_Ultrasonic_Reverse, -} - struct DmAccess { std::string deviceName; int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. @@ -215,7 +216,7 @@ struct DmAuthContext { DmAuthDirection direction; // Indicator of authentication direction ProcessInfo processInfo; DmPeerTarget peerTarget; - DmUltrasonicInfo ultrasonicInfo; + DmUltrasonicInfo ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; // Ultrasonic information DmAccess accesser; DmAccess accessee; std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f8c282569..f2e27cb9f 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -468,9 +468,11 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); if (tempInfo == DM_ULTRASONIC_REVERSE) { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; - } else { + } else if (tempInfo == DM_ULTRASONIC_FORWARD) { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; - } + } else { + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; + } LOGI("ultrasonic side is %{public}d", context_->ultrasonicInfo); } ParseHmlInfoInJsonObject(jsonObject); @@ -617,6 +619,9 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth return DM_OK; } InitAuthState(pkgName, authType, deviceId, extra); + if (context_->ultrasonicInfo == DmUltrasonicInfo::DM_Ultrasonic_Invalid) { + return ERR_DM_INPUT_PARA_INVALID; + } return DM_OK; } -- Gitee From f03f3d6fc090c78dd754d67ee686cc5e66a7427a Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 16:33:12 +0800 Subject: [PATCH 21/38] modify Signed-off-by: BrainL --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 +- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f2e27cb9f..9a4ae2536 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1015,7 +1015,7 @@ void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *ses char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) { - LOGI("AuthSrcManager::AuthDeviceRequest start"); + LOGI("AuthSinkManager::AuthDeviceRequest start"); (void)requestId; (void)reqParams; JsonObject jsonObj; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index fb116fbd0..3b86dd9bb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1069,7 +1069,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js context->transmitData = json[TAG_DATA].Get(); } if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Reverse){ - context->authStateMachine->TransitionTo(std::make_shared()); + context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { context->authStateMachine->TransitionTo(std::make_shared()); } else { -- Gitee From 2d27ac797f5ba2c7815c187ab78537bb30396df7 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 16:44:18 +0800 Subject: [PATCH 22/38] modify Signed-off-by: BrainL --- .../include/authentication_v2/dm_auth_context.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b0a4e7b32..b5ce6167c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -93,8 +93,10 @@ enum { }; enum DmUltrasonicInfo{ - DM_Ultrasonic_Forward = 0, // Phone->TV - DM_Ultrasonic_Reverse = 1, // Car->Phone + // Forward means the pincode is generated at sink side, then send by ultrasonic from sink to source side. + DM_Ultrasonic_Forward = 0, + // Reverse means the pincode is generated at source side, then send by ultrasonic from source to sink side. + DM_Ultrasonic_Reverse = 1, DM_Ultrasonic_Invalid = 2, }; -- Gitee From 58f158809930b09020e82323b6125f5ed25cf4b7 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 17:07:18 +0800 Subject: [PATCH 23/38] modify Signed-off-by: BrainL --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index d68ec712e..1f174e3ef 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -598,7 +598,7 @@ int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptrtimer->StartTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK), - GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::stringname) { + GET_ULTRASONIC_PIN_TIMEOUT, [context] (std::string name) { LOGI("AuthSrcReverseUltrasonicStartState::Action timeout"); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; -- Gitee From 1eea1ff646b4c9e69273f55684c04c3d12e239d5 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 17:18:28 +0800 Subject: [PATCH 24/38] modify Signed-off-by: BrainL --- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3b86dd9bb..95ce53278 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -94,12 +94,14 @@ const char* TAG_IS_AUTHED = "isAuthed"; const char* TAG_CREDENTIAL_INFO = "credentialInfo"; const char* TAG_CERT_INFO = "certInfo"; const char* TAG_LANGUAGE = "language"; -const char* DM_TAG_ULTRASONIC_SIDE = "ultrasonicSide"; +const char* TAG_ULTRASONIC_SIDE = "ultrasonicSide"; namespace { constexpr const int32_t DM_HASH_LEN = 32; const char* TAG_DEVICE_TYPE = "DEVICETYPE"; +constexpr int32_t DM_ULTRASONIC_FORWARD = 0; +constexpr int32_t DM_ULTRASONIC_REVERSE = 1; void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access) { @@ -567,7 +569,7 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.extraInfo; jsonObject[TAG_PEER_BUNDLE_NAME_V2] = context->accessee.bundleName; - jsonObject[TAG_ULTRASONIC_SIDE] = static_cast(context->ultrasonicSide); + jsonObject[TAG_ULTRASONIC_SIDE] = static_cast(context->ultrasonicInfo); jsonObject[TAG_PEER_DISPLAY_ID] = context->accessee.displayId; jsonObject[TAG_PEER_PKG_NAME] = context->accessee.pkgName; -- Gitee From 8b38fa859681ab18370d53bc44ed28eac9af5533 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 17:19:55 +0800 Subject: [PATCH 25/38] modify Signed-off-by: BrainL --- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index e1ebd3cfe..b06ac5fbe 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -1155,7 +1155,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaild_002, testing::ext::TestSize.Leve std::string pkgName = "ohos_test"; std::string deviceId = "512156"; int32_t ret = authManager_->CheckAuthParamVaild(pkgName, authType, deviceId, extra); - ASSERT_EQ(ret, ERR_DM_AUTH_FAILED); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_AUTH_TYPE); } HWTEST_F(DmAuthManagerTest, CheckAuthParamVaild_003, testing::ext::TestSize.Level1) -- Gitee From 89490e3f0db8a885b7f31af373a9f0b6b462d566 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 15 Apr 2025 15:26:25 +0800 Subject: [PATCH 26/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=91=8A=E8=AD=A6=20Si?= =?UTF-8?q?gned-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 3 +- .../authentication_v2/dm_auth_manager_base.h | 1 - .../dm_auth_message_processor.h | 6 ++-- .../src/authentication_v2/auth_manager.cpp | 6 ++-- .../auth_stages/auth_confirm.cpp | 4 +-- .../auth_stages/auth_credential.cpp | 2 +- .../auth_stages/auth_pin_auth.cpp | 2 +- .../dm_auth_message_processor.cpp | 30 +++++++++---------- .../hichain/hichain_auth_connector.cpp | 2 -- .../UTTest_hichain_auth_connector.cpp | 3 +- 10 files changed, 28 insertions(+), 31 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 5026b2642..2417e652f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -78,7 +78,6 @@ enum DmAuthScope { enum DmRole { DM_ROLE_UNKNOWN = 0, - DM_ROLE_DEVICE = 1, DM_ROLE_USER = 1, DM_ROLE_SA, DM_ROLE_FA, @@ -223,7 +222,7 @@ struct DmAuthContext { std::shared_ptr listener; std::shared_ptr authPtr; // Pointer to authentication interface std::shared_ptr timer; - std::string transmitData; // Data returned from onTrasmit function + std::string transmitData; // Data returned from onTransmit function std::string importPkgName = ""; std::string importAuthCode = ""; std::map> authenticationMap; diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 49915a2c2..7cbffca82 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -24,7 +24,6 @@ #include "softbus_session_callback.h" #include "softbus_connector_callback.h" #include "hichain_connector_callback.h" -#include "hichain_connector_callback.h" #include "auth_request_state.h" #include "auth_response_state.h" #include "dm_device_info.h" diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 943851be1..273d43749 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -28,8 +28,8 @@ namespace DistributedHardware { struct DmAuthContext; struct DmAccess; -extern const char* TAG_LNN_PUBLICK_KEY; -extern const char* TAG_TRANSMIT_PUBLICK_KEY; +extern const char* TAG_LNN_PUBLIC_KEY; +extern const char* TAG_TRANSMIT_PUBLIC_KEY; extern const char* TAG_LNN_CREDENTIAL_ID; extern const char* TAG_TRANSMIT_CREDENTIAL_ID; extern const char* TAG_CONFIRM_OPERATION_V2; @@ -46,7 +46,7 @@ extern const char* TAG_ALGORITHM_TYPE; extern const char* TAG_PROOF_TYPE; extern const char* TAG_KEY_VALUE; extern const char* TAG_AUTHORIZED_SCOPE; -extern const char* TAG_AUTHRIZED_APP_LIST; +extern const char* TAG_AUTHORIZED_APP_LIST; extern const char* TAG_CREDENTIAL_OWNER; extern const char* TAG_SYNC; extern const char* TAG_ACCESS; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 57263d234..b06303934 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -59,7 +59,7 @@ int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) return delaySeconds; } -std::string GetBundleLable(const std::string &bundleName) +std::string GetBundleLabel(const std::string &bundleName) { auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { @@ -313,7 +313,7 @@ bool AuthManager::IsAuthCodeReady(const std::string &pkgName) { if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and pkgName %{public}s.", - context_->importAuthCode.c_str(), context_->importPkgName.c_str()); + GetAnonyString(context_->importAuthCode).c_str(), context_->importPkgName.c_str()); return false; } if (pkgName != context_->importPkgName) { @@ -525,7 +525,7 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); context_->accesser.deviceId = std::string(localDeviceId); context_->pkgName = pkgName; - context_->pkgLabel = GetBundleLable(pkgName); + context_->pkgLabel = GetBundleLabel(pkgName); context_->authType = (DmAuthType)authType; context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 84700a8cb..20998d2f3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -102,7 +102,7 @@ void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context, J context->accesser.isAuthed = true; context->accesser.isPutLnnAcl = false; } - if (accesseeAclList.Contains("shareCredType") && accesserAclList.Contains("shareCredType")) { + if (accesseeAclList.Contains("shareAcl") && accesserAclList.Contains("shareAcl")) { LOGI("have share acl."); aclNegoResult["shareAcl"] = DM_SHARE; context->accesser.isAuthed = true; @@ -253,7 +253,7 @@ bool AuthSrcConfirmState::CheckCredIdInAcl(std::shared_ptr contex if (!credInfo.Contains(credId)) { credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); if (!credInfo.Contains(credId)) { - LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + LOGE("credInfoJson not contain credId %{public}s.", GetAnonyString(credId).c_str()); DeleteAcl(context, profile); return false; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 596222221..eb13fa2f3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -270,7 +270,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori if (authorizedScope == DM_AUTH_SCOPE_APP) { std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), std::to_string(authContext->accessee.tokenId)}; - jsonObj[TAG_AUTHRIZED_APP_LIST] = tokenIds; + jsonObj[TAG_AUTHORIZED_APP_LIST] = tokenIds; } jsonObj[TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index f53c7162e..96ef189e1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -189,7 +189,7 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context return DM_OK; } if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); + LOGI("AuthSinkPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); return DM_OK; } return STOP_BIND; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d94132621..3789c093b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -36,8 +36,8 @@ namespace OHOS { namespace DistributedHardware { -const char* TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; -const char* TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; +const char* TAG_LNN_PUBLIC_KEY = "lnnPublicKey"; +const char* TAG_TRANSMIT_PUBLIC_KEY = "transmitPublicKey"; const char* TAG_LNN_CREDENTIAL_ID = "lnnCredentialId"; const char* TAG_TRANSMIT_CREDENTIAL_ID = "transmitCredentialId"; const char* TAG_CONFIRM_OPERATION_V2 = "confirmOperation"; @@ -54,7 +54,7 @@ const char* TAG_ALGORITHM_TYPE = "algorithmType"; const char* TAG_PROOF_TYPE = "proofType"; const char* TAG_KEY_VALUE = "keyValue"; const char* TAG_AUTHORIZED_SCOPE = "authorizedScope"; -const char* TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; +const char* TAG_AUTHORIZED_APP_LIST = "authorizedAppList"; const char* TAG_CREDENTIAL_OWNER = "credOwner"; const char* TAG_SYNC = "syncMessage"; const char* TAG_ACCESS = "dmAccess"; @@ -419,21 +419,21 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js // First authentication, parse lnn public key if (context->accessee.isGenerateLnnCredential && context->accessee.bindLevel != static_cast(USER)) { - if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + if (!jsonData[TAG_LNN_PUBLIC_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); return ERR_DM_FAILED; } - context->accesser.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + context->accesser.lnnPublicKey = jsonData[TAG_LNN_PUBLIC_KEY].Get(); } - if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + if (!jsonData[TAG_TRANSMIT_PUBLIC_KEY].IsString() || !jsonData[TAG_DEVICE_ID].IsString() || !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accesser.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLIC_KEY].Get(); context->accesser.deviceId = jsonData[TAG_DEVICE_ID].Get(); context->accesser.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); context->accesser.tokenId = jsonData[TAG_TOKEN_ID].Get(); @@ -463,15 +463,15 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js // First authentication, parse lnn public key std::string tmpString = ""; if (context->accesser.isGenerateLnnCredential && context->accesser.bindLevel != static_cast(USER)) { - if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + if (!jsonData[TAG_LNN_PUBLIC_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey."); return ERR_DM_FAILED; } - context->accessee.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + context->accessee.lnnPublicKey = jsonData[TAG_LNN_PUBLIC_KEY].Get(); } // First authentication, parse transmit public key - if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + if (!jsonData[TAG_TRANSMIT_PUBLIC_KEY].IsString() || !jsonData[TAG_DEVICE_ID].IsString() || !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { @@ -479,7 +479,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js "message error."); return ERR_DM_FAILED; } - context->accessee.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLIC_KEY].Get(); context->accessee.deviceId = jsonData[TAG_DEVICE_ID].Get(); context->accessee.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); context->accessee.tokenId = jsonData[TAG_TOKEN_ID].Get(); @@ -592,9 +592,9 @@ int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptraccesser.isGenerateLnnCredential && context->accesser.bindLevel != static_cast(USER)) { - jsonData[TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; + jsonData[TAG_LNN_PUBLIC_KEY] = context->accesser.lnnPublicKey; } - jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.transmitPublicKey; + jsonData[TAG_TRANSMIT_PUBLIC_KEY] = context->accesser.transmitPublicKey; jsonData[TAG_DEVICE_ID] = context->accesser.deviceId; jsonData[TAG_PEER_USER_SPACE_ID] = context->accesser.userId; jsonData[TAG_TOKEN_ID] = context->accesser.tokenId; @@ -617,9 +617,9 @@ int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptraccessee.isGenerateLnnCredential && context->accessee.bindLevel != static_cast(USER)) { - jsonData[TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; + jsonData[TAG_LNN_PUBLIC_KEY] = context->accessee.lnnPublicKey; } - jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; + jsonData[TAG_TRANSMIT_PUBLIC_KEY] = context->accessee.transmitPublicKey; jsonData[TAG_DEVICE_ID] = context->accessee.deviceId; jsonData[TAG_PEER_USER_SPACE_ID] = context->accessee.userId; jsonData[TAG_TOKEN_ID] = context->accessee.tokenId; diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b214ecce6..c2760b35f 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -182,8 +182,6 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st const std::string &authParams, std::string &credId) { LOGI("HiChainAuthConnector::AgreeCredential start."); - LOGI("HiChainAuthConnector::AgreeCredential osAccountId=%{public}d, selfCredId=%{public}s, authParams=%{public}s\n", - osAccountId, selfCredId.c_str(), authParams.c_str()); char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 54f958727..643d1ef6c 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -339,6 +339,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; + int32_t osAccountId = 1245; int32_t peerOsAccountId = -1; bool ret = hiChain_->QueryCredential(localUdid, osAccountId, peerOsAccountId); EXPECT_TRUE(ret); @@ -564,7 +565,7 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_003, testing::ext::TestSize. g_processCredentialReturnDataStr = "{invalid_json}"; int32_t peerUserId = 0; int32_t ret = hiChain_->DeleteCredential(deviceId, userId, peerUserId); - EXPECT_EQ(ret, 0) + EXPECT_EQ(ret, 0); } HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize.Level1) -- Gitee From 6498cd3288b3f7f7b7bb15cc573493db456825a7 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Tue, 15 Apr 2025 17:40:46 +0800 Subject: [PATCH 27/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/src/dm_constants.cpp | 1 + .../include/authentication/dm_auth_manager.h | 14 +++---- .../include/authentication_v2/auth_manager.h | 4 +- .../authentication_v2/dm_auth_context.h | 2 +- .../authentication_v2/dm_auth_manager_base.h | 6 +-- .../hichain/hichain_auth_connector.h | 4 +- .../hichain/hichain_connector_callback.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 37 ++++++++++--------- .../src/authentication_v2/auth_manager.cpp | 21 ++++------- .../auth_stages/auth_confirm.cpp | 2 +- .../auth_stages/auth_pin_auth.cpp | 6 ++- .../dm_auth_manager_base.cpp | 8 ++-- .../hichain/hichain_auth_connector.cpp | 13 ++++--- .../dependency/hichain/hichain_connector.cpp | 10 ++--- .../src/device_manager_service_impl.cpp | 14 ++++--- .../mock/hichain_auth_connector_mock.cpp | 2 +- 16 files changed, 74 insertions(+), 72 deletions(-) diff --git a/common/src/dm_constants.cpp b/common/src/dm_constants.cpp index db8a8118b..f39ba50e2 100644 --- a/common/src/dm_constants.cpp +++ b/common/src/dm_constants.cpp @@ -63,6 +63,7 @@ const char AUTH_ALWAYS = '1'; const char AUTH_ONCE = '0'; const char* TAG_TARGET_DEVICE_NAME = "targetDeviceName"; const int32_t INVALID_PINCODE = -1; +const int32_t MIN_PINCODE_SIZE = 6; // HiChain const int32_t SERVICE_INIT_TRY_MAX_NUM = 200; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 2811a2e5a..9643b48f0 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -173,7 +173,7 @@ typedef struct DmAuthResponseContext { std::string authToken; int32_t pageId; int64_t requestId; - int32_t code = INVALID_PINCODE; + std::string code = ""; int32_t state; std::vector syncGroupList; std::string accountGroupIdHash; @@ -333,7 +333,7 @@ public: * @tc.desc: Process pin code of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t ProcessPincode(int32_t pinCode); + int32_t ProcessPincode(const std::string &pinCode); /** * @tc.name: DmAuthManager::GetConnectAddr @@ -382,7 +382,7 @@ public: * @tc.desc: Get Pin Code of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t GetPinCode(int32_t &code); + int32_t GetPinCode(std::string &code); /** * @tc.name: DmAuthManager::GenerateGroupName @@ -403,7 +403,7 @@ public: * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t GeneratePincode(); + std::string GeneratePincode(); /** * @tc.name: DmAuthManager::ShowConfigDialog @@ -516,7 +516,7 @@ private: void AbilityNegotiate(); void HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status); int32_t DeleteAuthCode(); - int32_t GetAuthCode(const std::string &pkgName, int32_t &pinCode); + int32_t GetAuthCode(const std::string &pkgName, std::string &pinCode); bool IsAuthTypeSupported(const int32_t &authType); bool IsAuthCodeReady(const std::string &pkgName); int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); @@ -572,8 +572,8 @@ private: void ProcessAuthRequest(const int32_t &sessionId); int32_t ConfirmProcess(const int32_t &action); int32_t ConfirmProcessExt(const int32_t &action); - int32_t AddMember(int32_t pinCode); - int32_t AuthDevice(int32_t pinCode); + int32_t AddMember(const std::string &pinCode); + int32_t AuthDevice(const std::string &pinCode); void PutAccessControlList(); void SinkAuthenticateFinish(); void SrcAuthenticateFinish(); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 4d1d45934..a6e560e01 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -60,7 +60,7 @@ public: * @tc.desc: User Operation of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t GeneratePincode(); + std::string GeneratePincode(); /** * @tc.name: AuthManager::ImportAuthCode @@ -125,7 +125,7 @@ protected: std::map bindParam_; PeerTargetId targetId_; - int32_t GetPinCode(int32_t &code); + int32_t GetPinCode(std::string &code); void GetRemoteDeviceId(std::string &deviceId); private: void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 5026b2642..b63c01b1c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -184,7 +184,7 @@ struct DmAuthContext { std::vector authTypeList; uint32_t currentAuthTypeIdx{0}; int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure - int32_t pinCode{INVALID_PINCODE}; + std::string pinCode{""}; bool serviceInfoFound{false}; // Link delay release time, does not automatically disconnect after // authorization (used for specific business needs), reserved field diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 49915a2c2..532835c7d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -154,7 +154,7 @@ public: virtual int32_t CreateGroup(); - virtual int32_t ProcessPincode(int32_t pinCode); + virtual int32_t ProcessPincode(const std::string &pinCode); virtual std::string GetConnectAddr(std::string deviceId); @@ -168,13 +168,13 @@ public: virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); - virtual int32_t GetPinCode(int32_t &code); + virtual int32_t GetPinCode(std::string &code); virtual std::string GenerateGroupName(); virtual void HandleAuthenticateTimeout(std::string name); - virtual int32_t GeneratePincode(); + virtual std::string GeneratePincode(); virtual void ShowConfigDialog(); diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 5684ef0c9..455b15e0e 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -51,7 +51,7 @@ public: public: HiChainAuthConnector(); ~HiChainAuthConnector(); - int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId); + int32_t AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, int64_t requestId); int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); bool QueryCredential(std::string &localUdid, int32_t osAccountId); @@ -72,7 +72,7 @@ public: // Credential authentication pinCode Pin code (required for point-to-point temporary credentials) int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode); - int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode); + int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pinCode); private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 56dd42bbc..5590744cc 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -23,7 +23,7 @@ public: virtual void OnGroupCreated(int64_t requestId, const std::string &groupId) = 0; virtual void OnMemberJoin(int64_t requestId, int32_t status) = 0; virtual std::string GetConnectAddr(std::string deviceId) = 0; - virtual int32_t GetPinCode(int32_t &code) = 0; + virtual int32_t GetPinCode(std::string &code) = 0; }; class IDmGroupResCallback { diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f56184951..5b312a8e0 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -766,7 +766,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId return; } CompatiblePutAcl(); - int32_t pinCode = -1; + std::string pinCode = ""; if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { GetAuthCode(authResponseContext_->hostPkgName, pinCode); } else if (authResponseContext_->authType != AUTH_TYPE_IMPORT_AUTH_CODE) { @@ -1249,7 +1249,7 @@ int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action) if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { if (CanUsePincodeFromDp()) { - authResponseContext_->code = std::atoi(serviceInfoProfile_.GetPinCode().c_str()); + authResponseContext_->code = serviceInfoProfile_.GetPinCode(); LOGI("import pincode from dp"); } else if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code); @@ -1347,7 +1347,7 @@ int32_t DmAuthManager::CreateGroup() return DM_OK; } -int32_t DmAuthManager::AddMember(int32_t pinCode) +int32_t DmAuthManager::AddMember(const std::string &pinCode) { if (authResponseContext_ == nullptr) { LOGE("failed to AddMember because authResponseContext_ is nullptr"); @@ -1560,9 +1560,10 @@ int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName) return DM_OK; } -int32_t DmAuthManager::GeneratePincode() +std::string DmAuthManager::GeneratePincode() { - return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + return std::to_string(pinCode); } bool DmAuthManager::IsPinCodeValid(const std::string strpin) @@ -1702,7 +1703,7 @@ int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr a return DM_OK; } -int32_t DmAuthManager::GetPinCode(int32_t &code) +int32_t DmAuthManager::GetPinCode(std::string &code) { if (authResponseContext_ == nullptr) { LOGE("failed to GetPinCode because authResponseContext_ is nullptr"); @@ -1783,7 +1784,7 @@ void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) LOGE("ReportAuthPullPinBox failed"); } pincodeDialogEverShown_ = true; - DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); + DmDialogManager::GetInstance().ShowPinDialog(authResponseContext_->code); } void DmAuthManager::ShowStartAuthDialog() @@ -1794,7 +1795,7 @@ void DmAuthManager::ShowStartAuthDialog() } if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { LOGI("Add member start"); - int32_t pinCode = -1; + std::string pinCode = ""; if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) { LOGE("failed to get auth code"); return; @@ -1817,7 +1818,7 @@ void DmAuthManager::ShowStartAuthDialog() return; } LOGI("DmAuthManager::ShowStartAuthDialog start"); - int32_t pincode = 0; + std::string pincode = ""; if (authResponseContext_->authType == AUTH_TYPE_NFC && GetAuthCode(authResponseContext_->hostPkgName, pincode) == DM_OK) { LOGI("already has pin code"); @@ -1829,7 +1830,7 @@ void DmAuthManager::ShowStartAuthDialog() DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName); } -int32_t DmAuthManager::ProcessPincode(int32_t pinCode) +int32_t DmAuthManager::ProcessPincode(const std::string &pinCode) { if (authResponseContext_ == nullptr) { LOGE("failed to ProcessPincode because authResponseContext_ is nullptr"); @@ -1851,7 +1852,7 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) return ERR_DM_FAILED; } -int32_t DmAuthManager::AuthDevice(int32_t pinCode) +int32_t DmAuthManager::AuthDevice(const std::string &pinCode) { LOGI("DmAuthManager::AuthDevice start."); if (isAuthDevice_) { @@ -1910,7 +1911,7 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR); break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(std::atoi(params.c_str())); + ProcessPincode(params); info.stageRes = static_cast(StageRes::STAGE_SUCC); break; default: @@ -2138,7 +2139,7 @@ int32_t DmAuthManager::DeleteAuthCode() return DM_OK; } -int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode) +int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, std::string &pinCode) { if (importAuthCode_.empty() || importPkgName_.empty()) { LOGE("GetAuthCode failed, auth code not exist."); @@ -2148,13 +2149,13 @@ int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode) LOGE("GetAuthCode failed, pkgName not supported."); return ERR_DM_FAILED; } - pinCode = std::atoi(importAuthCode_.c_str()); + pinCode = importAuthCode_; return DM_OK; } bool DmAuthManager::IsImportedAuthCodeValid() { - int32_t pinCode = 0; + std::string pinCode = ""; if (GetAuthCode(authRequestContext_->hostPkgName, pinCode) == DM_OK) { return true; } @@ -2535,12 +2536,12 @@ char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, con (void)requestId; (void)reqParams; JsonObject jsonObj; - int32_t pinCode = INVALID_PINCODE; - if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + std::string pinCode = ""; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_PIN_CODE] = pinCode; } std::string deviceId = ""; GetRemoteDeviceId(deviceId); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7816d9fba..cfe421d68 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -167,10 +167,11 @@ std::shared_ptr AuthManager::GetAuthContext() return this->context_; } -int32_t AuthManager::GeneratePincode() +std::string AuthManager::GeneratePincode() { LOGI("AuthManager::GeneratePincode start"); - context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + context_->pinCode = std::to_string(pinCode); return context_->pinCode; } @@ -210,12 +211,6 @@ int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::strin } context_->importAuthCode = authCode; context_->importPkgName = pkgName; - - if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { - context_->pinCode = std::stoi(authCode.c_str()); - } else { - AuthSinkStatePinAuthComm::GeneratePincode(context_); - } LOGI("AuthManager::ImportAuthCode ok"); return DM_OK; } @@ -871,7 +866,7 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m LOGE("OnUserOperation jsonStr error"); return ERR_DM_INPUT_PARA_INVALID; } - context_->pinCode = std::stoi(params); + context_->pinCode = params; } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; @@ -1006,12 +1001,12 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c DmAuthStateType curState = context_->authStateMachine->GetCurState(); if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { - int32_t pinCode = INVALID_PINCODE; - if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + std::string pinCode = ""; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_PIN_CODE] = pinCode; } } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { if (context_->isOnline) { // Non-first time certification @@ -1031,7 +1026,7 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c return buffer; } -int32_t AuthManager::GetPinCode(int32_t &code) +int32_t AuthManager::GetPinCode(std::string &code) { if (context_ == nullptr) { LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 421269c60..4be5a11be 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -587,7 +587,7 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { std::string pinCode = srvInfo.GetPinCode(); // read pincode if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { - context->pinCode = std::stoi(pinCode.c_str()); + context->pinCode = pinCode; } srvInfo.SetPinCode("******"); DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(srvInfo); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index f53c7162e..6b3dc29a3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -47,7 +47,7 @@ int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptrpinCode)); + DmDialogManager::GetInstance().ShowPinDialog(context->pinCode); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [context] (std::string name) { @@ -117,7 +117,8 @@ bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr co void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) { - context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + context->pinCode = std::to_string(pinCode); } DmAuthStateType AuthSrcPinAuthStartState::GetStateType() @@ -129,6 +130,7 @@ int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::Action start"); // auth pincode + if () auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(context->accesser.userId, context->requestId, context->pinCode); if (ret != DM_OK) { diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 24d710867..d3929063b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -196,7 +196,7 @@ int32_t AuthManagerBase::CreateGroup() return ERR_DM_FAILED; } -int32_t AuthManagerBase::ProcessPincode(int32_t pinCode) +int32_t AuthManagerBase::ProcessPincode(const std::string &pinCode) { LOGE("ProcessPincode is not implemented in the current version"); return ERR_DM_FAILED; @@ -237,7 +237,7 @@ int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr return ERR_DM_FAILED; } -int32_t AuthManagerBase::GetPinCode(int32_t &code) +int32_t AuthManagerBase::GetPinCode(std::string &code) { LOGE("GetPinCode is not implemented in the current version"); return ERR_DM_FAILED; @@ -254,10 +254,10 @@ void AuthManagerBase::HandleAuthenticateTimeout(std::string name) LOGE("HandleAuthenticateTimeout is not implemented in the current version"); } -int32_t AuthManagerBase::GeneratePincode() +std::string AuthManagerBase::GeneratePincode() { LOGE("GeneratePincode is not implemented in the current version"); - return ERR_DM_FAILED; + return ""; } void AuthManagerBase::ShowConfigDialog() diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 6ddbc6626..0b5d12c74 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -87,12 +87,13 @@ std::shared_ptr HiChainAuthConnector::GetDeviceAuthCallba return dmDeviceAuthCallback_; } -int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) +int32_t HiChainAuthConnector::AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, + int64_t requestId) { LOGI("HiChainAuthConnector::AuthDevice start."); JsonObject authParamJson; authParamJson["osAccountId"] = osAccountId; - authParamJson["pinCode"] = std::to_string(pinCode); + authParamJson["pinCode"] = pinCode; authParamJson["acquireType"] = AcquireType::P2P_BIND; std::string authParam = SafetyDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), @@ -240,17 +241,17 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe return DM_OK; } -int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pinCode) { LOGI("HiChainAuthConnector::AuthCredential start."); - if (pinCode == INVALID_PINCODE) { - LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pinCode is empty."); + if (pinCode.size() < MIN_PINCODE_SIZE) { + LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pinCode size is %{public}zu.", pinCode.size()); return ERR_DM_FAILED; } JsonObject jsonAuthParam; - jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonAuthParam[FIELD_PIN_CODE] = pinCode; jsonAuthParam[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); std::string authParams = jsonAuthParam.Dump(); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index a5365a560..4ea6913cc 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -345,12 +345,12 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string connectInfomation = GetConnectPara(deviceId, jsonObject[TAG_DEVICE_ID].Get()); - int32_t pinCode = jsonObject[PIN_CODE_KEY].Get(); + std::string pinCode = jsonObject[PIN_CODE_KEY].Get(); std::string groupId = jsonObject[TAG_GROUP_ID].Get(); JsonObject jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); + jsonObj[FIELD_PIN_CODE] = pinCode; jsonObj[FIELD_IS_ADMIN] = false; jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].Get(); @@ -487,12 +487,12 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch return nullptr; } JsonObject jsonObj; - int32_t pinCode = INVALID_PINCODE; - if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + std::string pinCode = ""; + if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_PIN_CODE] = pinCode; } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 02f43f706..379f38390 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1470,7 +1470,6 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { - int32_t ret = DM_OK; if (pkgName.empty()) { LOGE("BindTarget failed, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1478,8 +1477,7 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P std::string deviceId = ""; PeerTargetId targetIdTmp = const_cast(targetId); - ret = ParseConnectAddr(targetId, deviceId, bindParam); - if (ret == DM_OK) { + if (ParseConnectAddr(targetId, deviceId, bindParam) == DM_OK) { targetIdTmp.deviceId = deviceId; } else { if (targetId.deviceId.empty()) { @@ -1504,8 +1502,8 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P // Create on the src end. uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); - ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); - if (ret != DM_OK) { + if ((ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId)) != DM_OK) { + LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret); return ret; } curSession->logicalSessionSet_.insert(logicalSessionId); @@ -1519,7 +1517,11 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P return ERR_DM_POINT_NULL; } authMgr->SetBindTargetParams(targetId); - return authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId); + if ((ret = authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId)) != DM_OK) { + LOGE("authMgr BindTarget failed, ret %{public}d.", ret); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + return ret; } int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index dd7f98ffb..85734ac50 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -24,7 +24,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); } -int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) +int32_t HiChainAuthConnector::AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, int64_t requestId) { return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthDevice(pinCode, osAccountId, udid, requestId); } -- Gitee From 4016d123533995128fd75a58692207297082fa00 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 15 Apr 2025 16:17:12 +0800 Subject: [PATCH 28/38] code check Signed-off-by: q30043944 --- .../src/deviceprofile_connector.cpp | 16 ++++----- .../include/device_manager_service_impl.h | 3 ++ .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 33 ++++++++++--------- .../devicestate/dm_device_state_manager.cpp | 15 ++++++--- 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 2488e448b..df8dd740c 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -477,8 +477,7 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, offlineParam.processVec.push_back(processInfo); CacheAcerAclId(item, offlineParam); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", - item.GetBindType(), GetAnonyString(localUdid).c_str(), - GetAnonyString(remoteUdid).c_str()); + item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } if ((aceeTokenId == static_cast(tokenId)) && acerDeviceId == remoteUdid && @@ -492,8 +491,7 @@ void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, offlineParam.processVec.push_back(processInfo); CacheAceeAclId(item, offlineParam); LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", - item.GetBindType(), GetAnonyString(localUdid).c_str(), - GetAnonyString(remoteUdid).c_str()); + item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } } @@ -1953,14 +1951,12 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot continue; } bindNums++; - int32_t acerUserId = item.GetAccesser().GetAccesserUserId(); - int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId(); std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); int32_t acerTokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); int32_t aceeTokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); - if (acerUserId == remoteUserId && acerDeviceId == remoteUdid && aceeDeviceId == localUdid && - (acerTokenId == tokenId) && (aceeTokenId == peerTokenId)) { + if (item.GetAccesser().GetAccesserUserId() == remoteUserId && acerDeviceId == remoteUdid && + aceeDeviceId == localUdid && (acerTokenId == tokenId) && (aceeTokenId == peerTokenId)) { LOGI("Src device unbind."); delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; @@ -1972,8 +1968,8 @@ EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remot CacheAceeAclId(item, offlineParam); continue; } - if (aceeUserId == remoteUserId && aceeDeviceId == remoteUdid && acerDeviceId == localUdid && - (aceeTokenId == tokenId) && (acerTokenId == peerTokenId)) { + if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && aceeDeviceId == remoteUdid && + acerDeviceId == localUdid && (aceeTokenId == tokenId) && (acerTokenId == peerTokenId)) { LOGI("Sink device unbind."); delAclIdVec.push_back(item.GetAccessControlId()); deleteNums++; diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 3f44106d9..2477a7578 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -235,6 +235,9 @@ private: std::vector> &delACLInfoVec, std::vector &userIdVec); bool CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, DistributedDeviceProfile::AccessControlProfile lastprofile); + void CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, + DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, + bool &isLastLnnAcl, const std::string &localUdid); private: std::shared_ptr authMgr_; // Old protocol only std::mutex authMgrMtx_; diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index fc231c78a..be9fe7c29 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -109,7 +109,7 @@ private: int32_t DeleteGroupByDP(const std::string &deviceId); #endif void ProcessDeviceStateChange(const DmDeviceState devState, const DmDeviceInfo &devInfo); - + void DeleteCredential(DmOfflineParam offlineParam, const std::string &deviceId); private: std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f321343df..4b7dc33fc 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1648,7 +1648,6 @@ void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds); LOGE("DeleteSkIdAndCredId start"); DeleteSkIdAndCredId(offlineParam); - } void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector &deviceVec, @@ -1764,7 +1763,6 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co hiChainConnector_->DeleteAllGroup(item.second); CHECK_NULL_VOID(hiChainAuthConnector_); hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId); - //TODO: LOGE("DeleteSkIdAndCredId start"); DeleteSkIdAndCredId(offlineParam); } @@ -1830,7 +1828,6 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (offlineParam.leftAclNumber != 0) { LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); CHECK_NULL_VOID(softbusConnector_); @@ -2018,18 +2015,7 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i DmOfflineParam lnnAclParam; bool isLastLnnAcl = false; for (auto it : profiles) { - DistributedDeviceProfile::AccessControlProfile lnnAclProfile; - if (DeviceProfileConnector::GetInstance().IsLnnAcl(it) && CheckLnnAcl(item.second, it)) { - if (it.GetAccesser().GetAccesserDeviceId() == localUdid) { - DeviceProfileConnector::GetInstance().CacheAcerAclId(it, lnnAclParam); - } - if (it.GetAccessee().GetAccesseeDeviceId() == localUdid) { - DeviceProfileConnector::GetInstance().CacheAceeAclId(it, lnnAclParam); - } - } - if (!DeviceProfileConnector::GetInstance().IsLnnAcl(it) && CheckLnnAcl(item.second, it)) { - isLastLnnAcl = true; - } + CheckIsLastLnnAcl(it, item.second, lnnAclParam, isLastLnnAcl, localUdid); } if (!isLastLnnAcl) { DeleteSkIdAndCredId(lnnAclParam); @@ -2047,6 +2033,23 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i return DM_OK; } +void DeviceManagerServiceImpl::CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, + DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, bool &isLastLnnAcl, + const std::string &localUdid) +{ + if (DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { + if (profile.GetAccesser().GetAccesserDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAcerAclId(profile, lnnAclParam); + } + if (profile.GetAccessee().GetAccesseeDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAceeAclId(profile, lnnAclParam); + } + } + if (!DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { + isLastLnnAcl = true; + } +} + void DeviceManagerServiceImpl::DeleteAclByTokenId(const int32_t accessTokenId, std::vector &profiles, std::map &delProfileMap, diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 70e4a411e..1c2ce48d6 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -309,11 +309,7 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) DmOfflineParam offlineParam; uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second, offlineParam); if (res == 0) { - if (offlineParam.skIdVec.empty()) { - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(idIter->second, - MultipleUserConnector::GetCurrentAccountUserID(), offlineParam.peerUserId); - } + DeleteCredential(offlineParam, idIter->second); DeleteSkIdAndCredId(offlineParam); } #endif @@ -323,6 +319,15 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) } } +void DmDeviceStateManager::DeleteCredential(DmOfflineParam offlineParam, const std::string &deviceId) +{ + if (offlineParam.skIdVec.empty()) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); + } +} + int32_t DmDeviceStateManager::DeleteSkIdAndCredId(DmOfflineParam offlineParam) { LOGI("DeleteSkIdAndCredId start."); -- Gitee From 5016219b75bf5f6d499d769be94c1e2d7abd34e2 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 18:01:10 +0800 Subject: [PATCH 29/38] modify Signed-off-by: BrainL --- .../authentication_v2/dm_auth_context.h | 2 +- .../auth_stages/auth_negotiate.cpp | 4 ++++ .../dm_auth_message_processor.cpp | 22 +++++++++++++------ 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b5ce6167c..813a8d061 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -92,7 +92,7 @@ enum { DM_SAME_GROUP_TYPE = 3, }; -enum DmUltrasonicInfo{ +enum DmUltrasonicInfo { // Forward means the pincode is generated at sink side, then send by ultrasonic from sink to source side. DM_Ultrasonic_Forward = 0, // Reverse means the pincode is generated at source side, then send by ultrasonic from source to sink side. diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index fa3ee432d..808b40302 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -181,6 +181,10 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) { LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + if (context->ultrasonicInfo == DM_Ultrasonic_Invalid) { + LOGE("AuthSinkNegotiateStateMachine::Action ultrasonicInfo invalid."); + return ERR_DM_INPUT_PARA_INVALID; + } // 1. Create an authorization timer if (context->timer != nullptr) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 95ce53278..d6e51033f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -273,11 +273,16 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START, &DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart}, - {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE, &DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START, &DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START, + &DmAuthMessageProcessor::CreateMessageReverseUltrasonicStart}, + {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE, + &DmAuthMessageProcessor::CreateMessageReverseUltrasonicDone}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START, + &DmAuthMessageProcessor::CreateMessageForwardUltrasonicStart}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageForwardUltrasonicNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, @@ -302,7 +307,8 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_START, &DmAuthMessageProcessor::ParseMessageReverseUltrasonicStart}, {DmMessageType::MSG_TYPE_REVERSE_ULTRASONIC_DONE, &DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone}, {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_START, &DmAuthMessageProcessor::ParseMessageForwardUltrasonicStart}, - {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, + {DmMessageType::MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageForwardUltrasonicNegotiate}, {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, @@ -951,8 +957,10 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); if (tempInfo == DM_ULTRASONIC_REVERSE) { context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; - } else { + } else if (tempInfo == DM_ULTRASONIC_FORWARD){ context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + } else { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; } LOGI("DmAuthMessageProcessor::ParseNegotiateMessage ultrasonicInfo=%{public}d", context->ultrasonicInfo); } -- Gitee From d2a0b00d811de01fe861ab452ffeac0ed5bd0752 Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 18:04:06 +0800 Subject: [PATCH 30/38] modify Signed-off-by: BrainL --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 4 ++-- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 808b40302..42a83a8db 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -181,7 +181,7 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) { LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); - if (context->ultrasonicInfo == DM_Ultrasonic_Invalid) { + if (context->ultrasonicInfo == DmUltrasonicInfo::DM_Ultrasonic_Invalid) { LOGE("AuthSinkNegotiateStateMachine::Action ultrasonicInfo invalid."); return ERR_DM_INPUT_PARA_INVALID; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 1f174e3ef..2eefb77fc 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -466,7 +466,7 @@ int32_t AuthSrcPinNegotiateStartState::ProcessPinBind(std::shared_ptrauthTypeList.empty()) && DmAuthState::IsImportAuthCodeCompatibility(context->authTypeList[0])) { return NegotiatePinAuth(context, true); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC){ + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { return NegotiatePinAuth(context, true); } else { return NegotiatePinAuth(context, false); @@ -690,7 +690,7 @@ int32_t AuthSrcForwardUltrasonicDoneState::Action(std::shared_ptr context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } - } else if (retEvent == DmEventType::ON_ULTRASONIC_PIN_TIMEOUT){ + } else if (retEvent == DmEventType::ON_ULTRASONIC_PIN_TIMEOUT) { context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d6e51033f..7ad088422 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -957,7 +957,7 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); if (tempInfo == DM_ULTRASONIC_REVERSE) { context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; - } else if (tempInfo == DM_ULTRASONIC_FORWARD){ + } else if (tempInfo == DM_ULTRASONIC_FORWARD) { context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; } else { context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; @@ -1078,7 +1078,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js if (json[TAG_DATA].IsString()) { context->transmitData = json[TAG_DATA].Get(); } - if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Reverse){ + if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Reverse) { context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { context->authStateMachine->TransitionTo(std::make_shared()); @@ -1121,7 +1121,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReverseUltrasonicDone(const JsonObje if (json[TAG_REPLY].IsNumberInteger()) { context->reply = json[TAG_REPLY].Get(); } - if (context->reply == DM_OK){ + if (context->reply == DM_OK) { context->authStateMachine->TransitionTo(std::make_shared()); } return DM_OK; -- Gitee From a9da5a08ae1a797049e125318655938ce1d7150b Mon Sep 17 00:00:00 2001 From: BrainL Date: Tue, 15 Apr 2025 20:04:59 +0800 Subject: [PATCH 31/38] modify format Signed-off-by: BrainL --- .../include/authentication_v2/auth_manager.h | 1 + .../dm_auth_message_processor.h | 18 ++-- .../include/authentication_v2/dm_auth_state.h | 6 +- .../MSDP/spatial_location_callback_impl.h | 50 ++++----- .../src/authentication_v2/auth_manager.cpp | 13 ++- .../auth_stages/auth_pin_auth.cpp | 17 ++- .../dm_auth_message_processor.cpp | 33 +++--- .../MSDP/spatial_location_callback_impl.cpp | 102 +++++++++--------- .../src/device_manager_service_impl.cpp | 5 +- 9 files changed, 130 insertions(+), 115 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 4d1d45934..77d6109ea 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -142,6 +142,7 @@ private: const std::string &deviceId, const std::string &extra); int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); + void ParseUltrasonicSide(const JsonObject &jsonObject, std::shared_ptr context_); }; class AuthSrcManager : public AuthManager { diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 83a4a2ecb..b48dc3305 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -240,14 +240,15 @@ private: int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); // Parse the 201 message int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); - // Parse the 102 message - int32_t ParseMessageReverseUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); - // Parse the 112 message - int32_t ParseMessageReverseUltrasonicDone(const JsonObject &jsonObject, std::shared_ptr context); - // Parse the 101 message - int32_t ParseMessageForwardUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); - // Parse the 111 message - int32_t ParseMessageForwardUltrasonicNegotiate(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 102 message + int32_t ParseMessageReverseUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 112 message + int32_t ParseMessageReverseUltrasonicDone(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 101 message + int32_t ParseMessageForwardUltrasonicStart(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 111 message + int32_t ParseMessageForwardUltrasonicNegotiate(const JsonObject &jsonObject, + std::shared_ptr context); // Create the 80 message int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); @@ -308,6 +309,7 @@ private: int32_t CheckLogicalSessionId(const JsonObject &jsonObject, std::shared_ptr context); bool CheckAccessValidityAndAssign(std::shared_ptr &context, DmAccess &access, DmAccess &accessTmp); + void ParseUltrasonicSide(const JsonObject &jsonObject, std::shared_ptr context); std::shared_ptr cryptoMgr_ = nullptr; std::unordered_map createMessageFuncMap_; std::unordered_map paraseMessageFuncMap_; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 23f68131b..4dc7130bd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -44,9 +44,9 @@ enum class DmAuthStateType { AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message // or rollback or 90 jump AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN - AUTH_SRC_REVERSE_ULTRASONIC_START_STATE = 6, + AUTH_SRC_REVERSE_ULTRASONIC_START_STATE = 6, AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE = 7, - AUTH_SRC_FORWARD_ULTRASONIC_START_STATE = 8, + AUTH_SRC_FORWARD_ULTRASONIC_START_STATE = 8, AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE = 9, AUTH_SRC_PIN_AUTH_START_STATE = 10, // Start authentication and send 120 message. AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 11, // Receive 130 authentication PIN result message, send 121 message @@ -64,7 +64,7 @@ enum class DmAuthStateType { AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN - AUTH_SINK_REVERSE_ULTRASONIC_START_STATE = 55, + AUTH_SINK_REVERSE_ULTRASONIC_START_STATE = 55, AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE = 56, AUTH_SINK_FORWARD_ULTRASONIC_START_STATE = 57, AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE = 58, diff --git a/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h index 1c337473d..9cfd8c8ae 100644 --- a/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h +++ b/services/implementation/include/dependency/MSDP/spatial_location_callback_impl.h @@ -11,29 +11,29 @@ * WITHOUT 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 OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H - #define OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H - - #include "spatial_location_callback_stub.h" - #include "dm_auth_state.h" - #include "dm_auth_context.h" - #include "spatial_awareness_mgr_client.h" - - namespace OHOS { - namespace DistributedHardware { - class SpatialLocationCallbackImpl : public Msdp::SpatialLocationCallbackStub { - public: - SpatialLocationCallbackImpl(std::shared_ptr context); - ~SpatialLocationCallbackImpl(); - void OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) override; - - private: - bool IsValidPinCodeStr(const std::string &pinCodeStr); - std::shared_ptr context_ = nullptr; - }; - } // namespace DistributedHardware - } // namespace OHOS - - #endif // OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H \ No newline at end of file +#ifndef OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H +#define OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H + +#include "spatial_location_callback_stub.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "spatial_awareness_mgr_client.h" + +namespace OHOS { +namespace DistributedHardware { +class SpatialLocationCallbackImpl : public Msdp::SpatialLocationCallbackStub { +public: + SpatialLocationCallbackImpl(std::shared_ptr context); + ~SpatialLocationCallbackImpl(); + void OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) override; + +private: + bool IsValidPinCodeStr(const std::string &pinCodeStr); + std::shared_ptr context_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_SPATIAL_LOCATION_CALLBACK_IMPL_DM_H \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 9a4ae2536..4ed660123 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -464,6 +464,16 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); } + + ParseUltrasonicSide(jsonObject, context_); + + ParseHmlInfoInJsonObject(jsonObject); + return; +} + +void AuthManager::ParseUltrasonicSide( + const JsonObject &jsonObject, std::shared_ptr context_) +{ if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); if (tempInfo == DM_ULTRASONIC_REVERSE) { @@ -473,10 +483,7 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; } - LOGI("ultrasonic side is %{public}d", context_->ultrasonicInfo); } - ParseHmlInfoInJsonObject(jsonObject); - return; } int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 2eefb77fc..4e2638446 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -209,7 +209,7 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (context->authType == AUTH_TYPE_PIN_ULTRASONIC && context->ultrasonicInfo == DM_Ultrasonic_Forward) { context->timer->DeleteTimer(std::string(GET_ULTRASONIC_PIN_TIMEOUT_TASK)); - } + } if (ret != DM_OK) { LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err."); return ret; @@ -362,20 +362,17 @@ int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); } else { - LOGE("auth code not ready"); context->reason = ERR_DM_INPUT_PARA_INVALID; return ERR_DM_FAILED; } } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { context->authStateMachine->TransitionTo(std::make_shared()); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && - context->ultrasonicInfo == DM_Ultrasonic_Forward) { - LOGI("AuthSrcPinNegotiateStartState ultrasonic forward."); - context->authStateMachine->TransitionTo(std::make_shared()); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && - context->ultrasonicInfo == DM_Ultrasonic_Reverse) { - LOGI("AuthSrcPinNegotiateStartState ultrasonic Reverse."); - context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && + context->ultrasonicInfo == DM_Ultrasonic_Forward) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC && + context->ultrasonicInfo == DM_Ultrasonic_Reverse) { + context->authStateMachine->TransitionTo(std::make_shared()); } else { LOGE("authType not support."); return ERR_DM_FAILED; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 7ad088422..0f248f664 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -917,8 +917,8 @@ int32_t DmAuthMessageProcessor::CheckLogicalSessionId(const JsonObject &jsonObje return DM_OK; } -int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, - std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseNegotiateMessage( + const JsonObject &jsonObject, std::shared_ptr context) { if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { context->logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); @@ -953,17 +953,7 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_BUNDLE_NAME_V2].IsString()) { context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME_V2].Get(); } - if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { - int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); - if (tempInfo == DM_ULTRASONIC_REVERSE) { - context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; - } else if (tempInfo == DM_ULTRASONIC_FORWARD) { - context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; - } else { - context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; - } - LOGI("DmAuthMessageProcessor::ParseNegotiateMessage ultrasonicInfo=%{public}d", context->ultrasonicInfo); - } + if (jsonObject[TAG_EXTRA_INFO].IsString()) { context->accesser.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); } @@ -975,10 +965,27 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje context->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); } + ParseUltrasonicSide(jsonObject, context); + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } +void DmAuthMessageProcessor::ParseUltrasonicSide( + const JsonObject &jsonObject, std::shared_ptr context) +{ + if (jsonObject[TAG_ULTRASONIC_SIDE].IsNumberInteger()) { + int32_t tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); + if (tempInfo == DM_ULTRASONIC_REVERSE) { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } else if (tempInfo == DM_ULTRASONIC_FORWARD) { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + } else { + context->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; + } + } +} + int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { diff --git a/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp index 41b45a985..61419cabd 100644 --- a/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp +++ b/services/implementation/src/dependency/MSDP/spatial_location_callback_impl.cpp @@ -11,56 +11,56 @@ * WITHOUT 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 "spatial_location_callback_impl.h" - #include "dm_auth_state.h" - #include "multiple_user_connector.h" - #include "dm_auth_state_machine.h" - - namespace OHOS { - namespace DistributedHardware { - constexpr int32_t pinCodeLength = 6; - - SpatialLocationCallbackImpl::SpatialLocationCallbackImpl(std::shared_ptr context) - { - LOGI("SpatialLocationCallbackImpl Init."); - context_ = context; - } - - SpatialLocationCallbackImpl::~SpatialLocationCallbackImpl() - { - LOGI("SpatialLocationCallbackImpl End."); - } - - void SpatialLocationCallbackImpl::OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) - { - LOGI("SpatialLocationCallbackImpl::OnPinCodeChanged Start."); - if (pinCodeResponse.pincode.length() != pinCodeLength) { - LOGE("OnPinCodeChanged pincode length error."); - return; - } - if (!IsValidPinCodeStr(pinCodeResponse.pincode)) { - LOGE("OnPinCodeChanged pincode is invalid"); - return; - } - if (context_ == nullptr) { - LOGE("OnPinCodeChanged context_ empty."); - return; - } - int32_t pinCode = std::stoi(pinCodeResponse.pincode); - context_->pinCode = pinCode; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_CHANGED); - } - - bool SpatialLocationCallbackImpl::IsValidPinCodeStr(const std::string &pinCodeStr) +#include "spatial_location_callback_impl.h" +#include "dm_auth_state.h" +#include "multiple_user_connector.h" +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { +constexpr int32_t pinCodeLength = 6; + +SpatialLocationCallbackImpl::SpatialLocationCallbackImpl(std::shared_ptr context) +{ + LOGI("SpatialLocationCallbackImpl Init."); + context_ = context; +} + +SpatialLocationCallbackImpl::~SpatialLocationCallbackImpl() +{ + LOGI("SpatialLocationCallbackImpl End."); +} + +void SpatialLocationCallbackImpl::OnPinCodeChanged(const Msdp::PinCodeResponse &pinCodeResponse) { - for (auto &digit : pinCodeStr) { - if (digit < '0' || digit > '9') { - return false; - } - } - return true; - } - } // namespace DistributedHardware - } // namespace OHOS \ No newline at end of file + LOGI("SpatialLocationCallbackImpl::OnPinCodeChanged Start."); + if (pinCodeResponse.pincode.length() != pinCodeLength) { + LOGE("OnPinCodeChanged pincode length error."); + return; + } + if (!IsValidPinCodeStr(pinCodeResponse.pincode)) { + LOGE("OnPinCodeChanged pincode is invalid"); + return; + } + if (context_ == nullptr) { + LOGE("OnPinCodeChanged context_ empty."); + return; + } + int32_t pinCode = std::stoi(pinCodeResponse.pincode); + context_->pinCode = pinCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ULTRASONIC_PIN_CHANGED); +} + +bool SpatialLocationCallbackImpl::IsValidPinCodeStr(const std::string &pinCodeStr) +{ + for (auto &digit : pinCodeStr) { + if (digit < '0' || digit > '9') { + return false; + } + } + return true; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 2085a22ef..3198991de 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -884,11 +884,12 @@ int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::mapsecond = CHANGE_PINTYPE; - LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bind param %{public}s change to PIN_TYPE.", PARAM_KEY_AUTH_TYPE); + LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s PINTYPE.", PARAM_KEY_AUTH_TYPE); return DM_OK; } -- Gitee From 4fbc9fc91df23456bd5b1c4f145474e24a3ee1ff Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Tue, 15 Apr 2025 20:14:32 +0800 Subject: [PATCH 32/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/include/dm_constants.h | 3 +-- .../src/authentication/dm_auth_manager.cpp | 2 +- .../src/authentication_v2/auth_manager.cpp | 2 +- .../auth_stages/auth_pin_auth.cpp | 3 +-- .../src/device_manager_service_impl.cpp | 3 ++- .../dm_auth_manager_fuzzer.cpp | 2 +- .../UTTest_dm_auth_manager_first.cpp | 16 ++++++++-------- .../UTTest_dm_auth_manager_second.cpp | 18 +++++++++--------- .../UTTest_hichain_auth_connector.cpp | 4 ++-- .../UTTest_hichain_connector.cpp | 5 ++--- .../mock/hichain_auth_connector_mock.cpp | 5 +++-- .../mock/hichain_auth_connector_mock.h | 4 ++-- 12 files changed, 33 insertions(+), 34 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 52dcb380b..f7b09656e 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -71,8 +71,7 @@ EXPORT extern const int32_t CHECK_AUTH_ALWAYS_POS; EXPORT extern const char AUTH_ALWAYS; EXPORT extern const char AUTH_ONCE; EXPORT extern const char* TAG_TARGET_DEVICE_NAME; -EXPORT extern const int32_t INVALID_PINCODE; - +EXPORT extern const int32_t MIN_PINCODE_SIZE; // HiChain EXPORT extern const int32_t SERVICE_INIT_TRY_MAX_NUM; constexpr int32_t DEVICE_UUID_LENGTH = 65; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 5b312a8e0..11184f52e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1562,7 +1562,7 @@ int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName) std::string DmAuthManager::GeneratePincode() { - int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); return std::to_string(pinCode); } diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index cfe421d68..517bb39a7 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -170,7 +170,7 @@ std::shared_ptr AuthManager::GetAuthContext() std::string AuthManager::GeneratePincode() { LOGI("AuthManager::GeneratePincode start"); - int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); context_->pinCode = std::to_string(pinCode); return context_->pinCode; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 6b3dc29a3..dc0ebbd76 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -117,7 +117,7 @@ bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr co void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) { - int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE) + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); context->pinCode = std::to_string(pinCode); } @@ -130,7 +130,6 @@ int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::Action start"); // auth pincode - if () auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(context->accesser.userId, context->requestId, context->pinCode); if (ret != DM_OK) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 379f38390..b455551bd 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1502,7 +1502,8 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P // Create on the src end. uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); - if ((ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId)) != DM_OK) { + int32_t ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); + if (ret != DM_OK) { LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret); return ret; } diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp index fc9ff5b79..053f739b4 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp @@ -39,7 +39,7 @@ int32_t g_sessionSide = 0; int32_t g_result = 1; int32_t g_authType = 1; int32_t g_status = 1; -int32_t g_pinCode = 1; +std::string g_pinCode = "111111"; int32_t g_action = 1; int32_t g_userId = 1; int32_t g_pageId = 1; diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index d0ed88960..9feff10d6 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -41,7 +41,7 @@ namespace OHOS { namespace DistributedHardware { namespace { - constexpr int32_t PINCODE = 100001; + constexpr std::string PINCODE = "100001"; constexpr int32_t MIN_PIN_CODE_VALUE = 10; constexpr int32_t MAX_PIN_CODE_VALUE = 9999999; constexpr int32_t INVALID_AUTHBOX_TYPE = 100; @@ -283,7 +283,7 @@ HWTEST_F(DmAuthManagerTest, AddMember_001, testing::ext::TestSize.Level1) authManager_->authResponseContext_->code = 123; authManager_->authResponseContext_->requestId = 234; authManager_->authResponseContext_->deviceId = "234"; - int32_t pinCode = 444444; + std::string pinCode = "444444"; authManager_->hiChainConnector_->RegisterHiChainCallback(authManager_); authManager_->SetAuthResponseState(authResponseState); int32_t ret = authManager_->AddMember(pinCode); @@ -292,7 +292,7 @@ HWTEST_F(DmAuthManagerTest, AddMember_001, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, AddMember_002, testing::ext::TestSize.Level1) { - int32_t pinCode = 33333; + std::string pinCode = "33333"; authManager_->authResponseContext_ = nullptr; int32_t ret = authManager_->AddMember(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -1841,7 +1841,7 @@ HWTEST_F(DmAuthManagerTest, RequestCredentialDone_003, testing::ext::TestSize.Le HWTEST_F(DmAuthManagerTest, AuthDevice_003, testing::ext::TestSize.Level1) { - int32_t pinCode = 123456; + std::string pinCode = "123456"; authManager_->isAuthDevice_ = false; authManager_->authResponseContext_->authType = 5; EXPECT_CALL(*hiChainAuthConnectorMock_, AuthDevice(_, _, _, _)).WillOnce(Return(DM_OK)); @@ -2045,7 +2045,7 @@ HWTEST_F(DmAuthManagerTest, CheckNeedShowAuthInfoDialog_001, testing::ext::TestS int32_t errorCode = ERR_DM_HICHAIN_PROOFMISMATCH; authManager_->pincodeDialogEverShown_ = false; authManager_->authResponseContext_->authType = AUTH_TYPE_NFC; - authManager_->serviceInfoProfile_.SetPinCode(std::to_string(PINCODE)); + authManager_->serviceInfoProfile_.SetPinCode(PINCODE); authManager_->serviceInfoProfile_.SetPinExchangeType( static_cast(DMLocalServiceInfoPinExchangeType::FROMDP)); bool ret = authManager_->CheckNeedShowAuthInfoDialog(errorCode); @@ -2063,7 +2063,7 @@ HWTEST_F(DmAuthManagerTest, CheckNeedShowAuthInfoDialog_001, testing::ext::TestS localServiceInfo.SetAuthType(static_cast(DMLocalServiceInfoAuthType::TRUST_ONETIME)); localServiceInfo.SetAuthBoxType(static_cast(DMLocalServiceInfoAuthBoxType::STATE3)); localServiceInfo.SetPinExchangeType(static_cast(DMLocalServiceInfoPinExchangeType::FROMDP)); - localServiceInfo.SetPinCode(std::to_string(PINCODE)); + localServiceInfo.SetPinCode(PINCODE); EXPECT_CALL(*deviceProfileConnectorMock_, GetLocalServiceInfoByBundleNameAndPinExchangeType(_, _, _)) .WillOnce(DoAll(SetArgReferee<2>(localServiceInfo), Return(DM_OK))); authManager_->GetLocalServiceInfoInDp(); @@ -2091,7 +2091,7 @@ HWTEST_F(DmAuthManagerTest, IsPinCodeValid_001, testing::ext::TestSize.Level1) static_cast(DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM)); authManager_->authResponseContext_->authType = AUTH_TYPE_NFC; - authManager_->serviceInfoProfile_.SetPinCode(std::to_string(PINCODE)); + authManager_->serviceInfoProfile_.SetPinCode(PINCODE); authManager_->serviceInfoProfile_.SetPinExchangeType( static_cast(DMLocalServiceInfoPinExchangeType::FROMDP)); authManager_->ShowConfigDialog(); @@ -2153,7 +2153,7 @@ HWTEST_F(DmAuthManagerTest, IsLocalServiceInfoValid_001, testing::ext::TestSize. profile.SetPinCode(""); ASSERT_TRUE(authManager_->IsLocalServiceInfoValid(profile)); - profile.SetPinCode(std::to_string(PINCODE)); + profile.SetPinCode(PINCODE); ASSERT_TRUE(authManager_->IsLocalServiceInfoValid(profile)); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index e1ebd3cfe..826f1ab3f 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -822,7 +822,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ProcessPincode_001, testing::ext::TestSize.Level1) { - int32_t pinCode = 123456; + std::string pinCode = "123456"; authManager_->authResponseContext_ = nullptr; int32_t ret = authManager_->ProcessPincode(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -830,7 +830,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_001, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, ProcessPincode_002, testing::ext::TestSize.Level1) { - int32_t pinCode = 123456; + std::string pinCode = "123456"; authManager_->authResponseContext_->dmVersion = "dmVersion"; authManager_->authResponseContext_->bindLevel = 1; authManager_->isAuthDevice_ = true; @@ -840,7 +840,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_002, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level1) { - int32_t pinCode = -1; + std::string pinCode = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authUiStateMgr_ = nullptr; authManager_->importAuthCode_ = "123456"; @@ -870,7 +870,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level1) { - int32_t pinCode = 123456; + std::string pinCode = "123456"; authManager_->isAuthDevice_ = true; int32_t ret = authManager_->AuthDevice(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -878,7 +878,7 @@ HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, AuthDevice_002, testing::ext::TestSize.Level1) { - int32_t pinCode = 123456; + std::string pinCode = "123456"; authManager_->isAuthDevice_ = false; authManager_->authResponseContext_->authType = 5; EXPECT_CALL(*hiChainAuthConnectorMock_, AuthDevice(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); @@ -1086,7 +1086,7 @@ HWTEST_F(DmAuthManagerTest, DeleteAuthCode_001, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, GetAuthCode_001, testing::ext::TestSize.Level1) { std::string pkgName; - int32_t pinCode = 1; + std::string pinCode = "1"; authManager_->importAuthCode_ = ""; authManager_->importPkgName_ = "importPkgName_"; int32_t ret = authManager_->GetAuthCode(pkgName, pinCode); @@ -1096,7 +1096,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthCode_001, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, GetAuthCode_002, testing::ext::TestSize.Level1) { std::string pkgName; - int32_t pinCode = 1; + std::string pinCode = "1"; authManager_->importAuthCode_ = "importAuthCode_"; authManager_->importPkgName_ = ""; int32_t ret = authManager_->GetAuthCode(pkgName, pinCode); @@ -1106,7 +1106,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthCode_002, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, GetAuthCode_003, testing::ext::TestSize.Level1) { std::string pkgName = "pkgName"; - int32_t pinCode = 1; + std::string pinCode = "1"; authManager_->importAuthCode_ = "importAuthCode_"; authManager_->importPkgName_ = "importPkgName_"; int32_t ret = authManager_->GetAuthCode(pkgName, pinCode); @@ -1116,7 +1116,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthCode_003, testing::ext::TestSize.Level1) HWTEST_F(DmAuthManagerTest, GetAuthCode_004, testing::ext::TestSize.Level1) { std::string pkgName = "ohos_test"; - int32_t pinCode = 1; + std::string pinCode = "1"; authManager_->importAuthCode_ = "123456"; authManager_->importPkgName_ = "ohos_test"; int32_t ret = authManager_->GetAuthCode(pkgName, pinCode); diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 9058c5861..11a04bb71 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -75,7 +75,7 @@ public: return nullptr; } private: - int32_t pinCode = 0; + pinCode = 0; }; HWTEST_F(HiChainAuthConnectorTest, RegisterHiChainAuthCallback_001, testing::ext::TestSize.Level1) @@ -87,7 +87,7 @@ HWTEST_F(HiChainAuthConnectorTest, RegisterHiChainAuthCallback_001, testing::ext HWTEST_F(HiChainAuthConnectorTest, AuthDevice_001, testing::ext::TestSize.Level1) { - int32_t pinCode = 0; + std::string pinCode = "0"; int32_t osAccountId = 0; std::string udid; int64_t requestId = 0; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 908216828..81ea90399 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -61,10 +61,9 @@ public: { return ""; } - int32_t GetPinCode(int32_t &code) + int32_t GetPinCode(std::string &code) { - int32_t pinCode = 123456; - code = pinCode; + code = "123456"; return DM_OK; } }; diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index 85734ac50..b7e050952 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -24,7 +24,8 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); } -int32_t HiChainAuthConnector::AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, int64_t requestId) +int32_t HiChainAuthConnector::AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, + int64_t requestId) { return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthDevice(pinCode, osAccountId, udid, requestId); } @@ -66,7 +67,7 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredential(osAccountId, authReqId, credId, pinCode); } -int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pinCode) { return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredentialPinCode(osAccountId, authReqId, pinCode); } diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index d0de67f9e..f97914b1d 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -27,7 +27,7 @@ public: virtual ~DmHiChainAuthConnector() = default; public: virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId) = 0; - virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, + virtual int32_t AuthDevice(const std::string &pinCode, int32_t osAccountId, std::string udid, int64_t requestId) = 0; virtual int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) = 0; @@ -39,7 +39,7 @@ public: virtual int32_t DeleteCredential(int32_t osAccountId, const std::string &creId) = 0; virtual int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode) = 0; - virtual int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) = 0; + virtual int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pinCode) = 0; public: static inline std::shared_ptr dmHiChainAuthConnector = nullptr; }; -- Gitee From 79ad16c0aba1c451b585c356299213a19d28286f Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 15 Apr 2025 21:08:31 +0800 Subject: [PATCH 33/38] include LnnAcl Signed-off-by: q30043944 --- commondependency/src/deviceprofile_connector.cpp | 10 +++++----- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- .../authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- .../implementation/src/device_manager_service_impl.cpp | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index df8dd740c..a237de69e 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -86,7 +86,7 @@ int32_t DeviceProfileConnector::GetAclListHashStr(const std::string localUdid, i { std::string extraInfo = ""; std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); for (auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccesser().GetAccesserUserId() == localUserId && @@ -124,7 +124,7 @@ int32_t DeviceProfileConnector::GetAclListHashStr(const std::string localUdid, i // Query ACL. std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); std::vector aclStrVec; // Traverse the ACL table to find historical ACL records at both ends. for (auto &item : profiles) { @@ -214,7 +214,7 @@ std::vector DeviceProfileConnect const std::string localUdid, int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId) { std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); std::vector aclList; for (auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -320,8 +320,8 @@ EXPORT DmOfflineParam DeviceProfileConnector::DeleteAccessControlListV2(uint32_t return offlineParam; } int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::vector profiles = - GetAclProfileByDeviceIdAndUserId(localDeviceId, userId, remoteDeviceId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localDeviceId, userId, + remoteDeviceId); if (profiles.empty()) { LOGE("Acl is empty."); return offlineParam; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 20998d2f3..b29ffdae6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -189,7 +189,7 @@ void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, { CHECK_NULL_VOID(context); std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); uint32_t bindLevel = DM_INVALIED_TYPE; for (const auto &item : profiles) { std::string trustDeviceId = item.GetTrustDeviceId(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index b28da1657..1e4c381c6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -290,7 +290,7 @@ void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); int32_t bindLevel = DM_INVALIED_TYPE; for (const auto &item : profiles) { std::string trustDeviceId = item.GetTrustDeviceId(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 20dc6520f..b3b232254 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -2020,7 +2020,7 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i { CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str()); if (profiles.size() == 0) { return DM_OK; -- Gitee From 5cbaf208b3327248b94969444e83e118a7a7da3b Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 16 Apr 2025 00:16:39 +0800 Subject: [PATCH 34/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/src/dm_constants.cpp | 1 - .../src/deviceprofile_connector.cpp | 2 -- .../auth_stages/auth_confirm.cpp | 9 ------- .../auth_stages/auth_pin_auth.cpp | 5 ++++ .../hichain_connector_fuzzer.cpp | 2 +- .../onerror_fuzzer/on_error_fuzzer.cpp | 2 +- .../onfinish_fuzzer/on_finish_fuzzer.cpp | 2 +- .../onrequest_fuzzer/on_request_fuzzer.cpp | 2 +- .../UTTest_dm_auth_manager_first.cpp | 24 +++++++++---------- .../UTTest_hichain_auth_connector.cpp | 2 +- .../commonunittest/UTTest_hichain_connector.h | 2 +- test/unittest/UTTest_auth_response_state.cpp | 2 +- .../mock/hichain_auth_connector_mock.h | 4 ++-- 13 files changed, 26 insertions(+), 33 deletions(-) diff --git a/common/src/dm_constants.cpp b/common/src/dm_constants.cpp index f39ba50e2..791beb0da 100644 --- a/common/src/dm_constants.cpp +++ b/common/src/dm_constants.cpp @@ -62,7 +62,6 @@ const int32_t CHECK_AUTH_ALWAYS_POS = 0; const char AUTH_ALWAYS = '1'; const char AUTH_ONCE = '0'; const char* TAG_TARGET_DEVICE_NAME = "targetDeviceName"; -const int32_t INVALID_PINCODE = -1; const int32_t MIN_PINCODE_SIZE = 6; // HiChain diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index ac81fa165..a7249b5cd 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -190,7 +190,6 @@ std::string DeviceProfileConnector::AccessToStr(DistributedDeviceProfile::Access jsonAcLObj[TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); jsonAcLObj[TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserCredentialIdStr(); jsonAcLObj[TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); - jsonAcLObj[TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); jsonAcLObj[TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); //TODO accessee DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); @@ -204,7 +203,6 @@ std::string DeviceProfileConnector::AccessToStr(DistributedDeviceProfile::Access jsonAcLObj[TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); jsonAcLObj[TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeCredentialIdStr(); jsonAcLObj[TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); - jsonAcLObj[TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); jsonAcLObj[TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); return jsonAcLObj.Dump(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 4be5a11be..8a7db542d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -55,8 +55,6 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con accesseeCredTypeList.Parse(context->accessee.credTypeList); JsonObject accesserCredTypeList; accesserCredTypeList.Parse(context->accesser.credTypeList); - LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", - accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { LOGE("CredTypeList invalid."); return; @@ -90,8 +88,6 @@ void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context, J accesseeAclList.Parse(context->accessee.aclTypeList); JsonObject accesserAclList; accesserAclList.Parse(context->accesser.aclTypeList); - LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", - accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { LOGE("aclList invalid."); return; @@ -492,8 +488,6 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co accesseeCredTypeList.Parse(context->accessee.credTypeList); JsonObject accesserCredTypeList; accesserCredTypeList.Parse(context->accesser.credTypeList); - LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", - accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { LOGE("CredTypeList invalid."); return; @@ -528,8 +522,6 @@ void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context, accesseeAclList.Parse(context->accessee.aclTypeList); JsonObject accesserAclList; accesserAclList.Parse(context->accesser.aclTypeList); - LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", - accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { LOGE("aclList invalid."); return; @@ -725,7 +717,6 @@ std::string AuthSinkConfirmState::GetCredIdByCredType(std::shared_ptraccessee.credentialInfos[credType]; - LOGI("yangwei credInfoStr %{public}s.", credInfoStr.c_str()); JsonObject credInfoJson; credInfoJson.Parse(credInfoStr); if (credInfoJson.IsDiscarded() || !credInfoJson.Contains(FILED_CRED_ID) || diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index dc0ebbd76..648c2e1a1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -387,6 +387,11 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con if (context->needBind) { return ProcessPinBind(context); } + if (!context->needBind && !context->needAgreeCredential && !context->needAuth) { + context->reason = ERR_DM_BIND_TRUST_TARGET; + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; return ERR_DM_FAILED; } diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index be997d5e2..e65a30cf2 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -53,7 +53,7 @@ public: (void)deviceId; return ""; } - int32_t GetPinCode(int32_t &code) override + int32_t GetPinCode(std::string &code) override { (void)code; return DM_OK; diff --git a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp index fdf2075d3..781698e0d 100644 --- a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp +++ b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp @@ -47,7 +47,7 @@ public: (void)deviceId; return ""; } - int32_t GetPinCode(int32_t &code) override + int32_t GetPinCode(std::string &code) override { (void)code; return DM_OK; diff --git a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp index 7c75b19b4..19b2b0ae5 100644 --- a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp +++ b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp @@ -47,7 +47,7 @@ public: (void)deviceId; return ""; } - int32_t GetPinCode(int32_t &code) override + int32_t GetPinCode(std::string &code) override { (void)code; return DM_OK; diff --git a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp index e4c91f69d..baaeb16e3 100644 --- a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp +++ b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp @@ -46,7 +46,7 @@ public: (void)deviceId; return ""; } - int32_t GetPinCode(int32_t &code) override + int32_t GetPinCode(std::string &code) override { (void)code; return DM_OK; diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 9feff10d6..f65fc598c 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -41,7 +41,7 @@ namespace OHOS { namespace DistributedHardware { namespace { - constexpr std::string PINCODE = "100001"; + const std::string PINCODE = "100001"; constexpr int32_t MIN_PIN_CODE_VALUE = 10; constexpr int32_t MAX_PIN_CODE_VALUE = 9999999; constexpr int32_t INVALID_AUTHBOX_TYPE = 100; @@ -124,8 +124,8 @@ void DmAuthManagerTest::TearDownTestCase() } namespace { -const int32_t MIN_PIN_CODE = 100000; -const int32_t MAX_PIN_CODE = 999999; +const std::string MIN_PIN_CODE = "100000"; +const std::string MAX_PIN_CODE = "999999"; HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_001, testing::ext::TestSize.Level1) { @@ -345,10 +345,10 @@ HWTEST_F(DmAuthManagerTest, SetAuthResponseState_002, testing::ext::TestSize.Lev HWTEST_F(DmAuthManagerTest, GetPinCode_001, testing::ext::TestSize.Level1) { - authManager_->authResponseContext_->code = 123456; - int32_t code = 0; + authManager_->authResponseContext_->code = "123456"; + std::string code = "0"; authManager_->GetPinCode(code); - ASSERT_EQ(code, 123456); + ASSERT_EQ(code, "123456"); } HWTEST_F(DmAuthManagerTest, GetPinCode_002, testing::ext::TestSize.Level1) @@ -357,9 +357,9 @@ HWTEST_F(DmAuthManagerTest, GetPinCode_002, testing::ext::TestSize.Level1) authManager_->ShowConfigDialog(); authManager_->ShowAuthInfoDialog(); authManager_->ShowStartAuthDialog(); - int32_t code = 0; + std::string code = "0"; int32_t ret = authManager_->GetPinCode(code); - ASSERT_NE(code, ERR_DM_TIME_OUT); + ASSERT_NE(ret, ERR_DM_TIME_OUT); } HWTEST_F(DmAuthManagerTest, SetPageId_001, testing::ext::TestSize.Level1) @@ -461,7 +461,7 @@ HWTEST_F(DmAuthManagerTest, GeneratePincode_001, testing::ext::TestSize.Level1) authManager_->timer_ = nullptr; authManager_->OnSessionOpened(openedSessionId, sessionSide, result); authManager_->OnSessionClosed(closedSessionId); - int32_t ret = authManager_->GeneratePincode(); + std::string ret = authManager_->GeneratePincode(); ASSERT_LE(ret, MAX_PIN_CODE); ASSERT_GE(ret, MIN_PIN_CODE); } @@ -477,7 +477,7 @@ HWTEST_F(DmAuthManagerTest, GeneratePincode_002, testing::ext::TestSize.Level1) authManager_->timer_ = std::make_shared(); authManager_->OnSessionOpened(openedSessionId, sessionSide, result); authManager_->OnSessionClosed(closedSessionId); - int32_t ret = authManager_->GeneratePincode(); + std::string ret = authManager_->GeneratePincode(); ASSERT_LE(ret, MAX_PIN_CODE); ASSERT_GE(ret, MIN_PIN_CODE); } @@ -493,7 +493,7 @@ HWTEST_F(DmAuthManagerTest, GeneratePincode_003, testing::ext::TestSize.Level1) authManager_->timer_ = nullptr; authManager_->OnSessionOpened(openedSessionId, sessionSide, result); authManager_->OnSessionClosed(closedSessionId); - int32_t ret = authManager_->GeneratePincode(); + std::string ret = authManager_->GeneratePincode(); ASSERT_LE(ret, MAX_PIN_CODE); ASSERT_GE(ret, MIN_PIN_CODE); } @@ -509,7 +509,7 @@ HWTEST_F(DmAuthManagerTest, GeneratePincode_004, testing::ext::TestSize.Level1) authManager_->timer_ = std::make_shared(); authManager_->OnSessionOpened(openedSessionId, sessionSide, result); authManager_->OnSessionClosed(closedSessionId); - int32_t ret = authManager_->GeneratePincode(); + std::string ret = authManager_->GeneratePincode(); ASSERT_LE(ret, MAX_PIN_CODE); ASSERT_GE(ret, MIN_PIN_CODE); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 11a04bb71..82dc3e2d4 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -75,7 +75,7 @@ public: return nullptr; } private: - pinCode = 0; + int32_t pinCode = 0; }; HWTEST_F(HiChainAuthConnectorTest, RegisterHiChainAuthCallback_001, testing::ext::TestSize.Level1) diff --git a/test/commonunittest/UTTest_hichain_connector.h b/test/commonunittest/UTTest_hichain_connector.h index 8de11bc2b..e41fe69b9 100644 --- a/test/commonunittest/UTTest_hichain_connector.h +++ b/test/commonunittest/UTTest_hichain_connector.h @@ -50,7 +50,7 @@ public: MOCK_METHOD(void, OnGroupCreated, (int64_t requestId, const std::string &groupId), (override)); MOCK_METHOD(void, OnMemberJoin, (int64_t requestId, int32_t status), (override)); MOCK_METHOD(std::string, GetConnectAddr, (std::string deviceId), (override)); - MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); + MOCK_METHOD(int32_t, GetPinCode, (std::string &code), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp index 1a7ec5796..25b68d7bc 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -402,7 +402,7 @@ HWTEST_F(AuthResponseStateTest, Enter_009, testing::ext::TestSize.Level1) authManager->authResponseContext_ = std::make_shared(); std::shared_ptr authResponseState = std::make_shared(); authManager->authPtr_ = authManager->authenticationMap_[1]; - authManager->authResponseContext_->code = 123456; + authManager->authResponseContext_->code = "123456"; authResponseState->SetAuthManager(authManager); int32_t ret = authResponseState->Enter(); ASSERT_EQ(ret, DM_OK); diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index f97914b1d..e2e4d3840 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -47,7 +47,7 @@ public: class HiChainAuthConnectorMock : public DmHiChainAuthConnector { public: MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); - MOCK_METHOD(int32_t, AuthDevice, (int32_t, int32_t, std::string, int64_t)); + MOCK_METHOD(int32_t, AuthDevice, (const std::string &, int32_t, std::string, int64_t)); MOCK_METHOD(int32_t, ImportCredential, (int32_t, std::string, std::string)); MOCK_METHOD(int32_t, ProcessCredData, (int64_t, const std::string &)); @@ -56,7 +56,7 @@ public: MOCK_METHOD(int32_t, AgreeCredential, (int32_t, const std::string, const std::string &, std::string &)); MOCK_METHOD(int32_t, DeleteCredential, (int32_t, const std::string &)); MOCK_METHOD(int32_t, AuthCredential, (int32_t, int64_t, const std::string &, const std::string &)); - MOCK_METHOD(int32_t, AuthCredentialPinCode, (int32_t, int64_t, int32_t)); + MOCK_METHOD(int32_t, AuthCredentialPinCode, (int32_t, int64_t, const std::string &)); }; } } -- Gitee From ecb6f69a53976c33d496415d2abc4fb4254877b6 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 16 Apr 2025 00:22:57 +0800 Subject: [PATCH 35/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- commondependency/src/deviceprofile_connector.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index a7249b5cd..4857836ec 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -60,7 +60,6 @@ namespace { const char* TAG_ACCESSER_BIND_LEVEL = "accesserBindLevel"; const char* TAG_ACCESSER_CREDENTIAL_ID = "accesserCredetialId"; const char* TAG_ACCESSER_STATUS = "accesserStatus"; - const char* TAG_ACCESSER_SK_ID = "accesserSessionKeyId"; const char* TAG_ACCESSER_SK_TIMESTAMP = "accesserSKTimeStamp"; // Accessee table content is used for ACL synchronization. @@ -74,7 +73,6 @@ namespace { const char* TAG_ACCESSEE_BIND_LEVEL = "accesseeBindLevel"; const char* TAG_ACCESSEE_CREDENTIAL_ID = "accesseeCredetialId"; const char* TAG_ACCESSEE_STATUS = "accesseeStatus"; - const char* TAG_ACCESSEE_SK_ID = "accesseeSessionKeyId"; const char* TAG_ACCESSEE_SK_TIMESTAMP = "accesseeSKTimeStamp"; }; -- Gitee From b0208e0ebe41ffb33a0c8d4dab1dbca09b96ef05 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 16 Apr 2025 11:28:22 +0800 Subject: [PATCH 36/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index b5a9e56d1..1ff4e8770 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -609,8 +609,8 @@ int32_t AuthSrcReverseUltrasonicStartState::Action(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); return DM_OK; }); - context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - std::string ultraPinCode = std::to_string(context->pinCode); + context->pinCode = std::to_string(GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE)); + std::string ultraPinCode = context->pinCode; Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REVERSE_ULTRASONIC_START, context); @@ -777,8 +777,8 @@ int32_t AuthSinkForwardUltrasonicStartState::Action(std::shared_ptrauthStateMachine->TransitionTo(std::make_shared()); return DM_OK; }); - context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - std::string ultraPinCode = std::to_string(context->pinCode); + context->pinCode = std::to_string(GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE)); + std::string ultraPinCode = context->pinCode; Msdp::SpatialAwarenessMgrClient::GetInstance().SetPinCode(ultraPinCode); context->reply = DM_OK; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_FORWARD_ULTRASONIC_NEGOTIATE, context); -- Gitee From 10ace24d6ed10f7cd149e84cb246bf3b7469f06d Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 16 Apr 2025 11:32:04 +0800 Subject: [PATCH 37/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=8F=E5=90=8C?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/implementation/src/authentication_v2/auth_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 4ce27baa1..4ff7cca99 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -213,6 +213,7 @@ int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::strin } context_->importAuthCode = authCode; context_->importPkgName = pkgName; + context_->pinCode = authCode; LOGI("AuthManager::ImportAuthCode ok"); return DM_OK; } -- Gitee From 346a84e03c465d5759f80e5ed5b53e959751481d Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Wed, 16 Apr 2025 15:25:14 +0800 Subject: [PATCH 38/38] modify L1 compile error Signed-off-by: hwzhangchuang --- .../devicestate/dm_device_state_manager.h | 6 ++++- .../dependency/softbus/softbus_connector.cpp | 26 +++++++++++++++++++ .../devicestate/dm_device_state_manager.cpp | 2 ++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index be9fe7c29..3fd420bcb 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -34,7 +34,9 @@ #include "hichain_connector.h" #include "hichain_auth_connector.h" #include "multiple_user_connector.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "deviceprofile_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -97,7 +99,9 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) int32_t DeleteSkIdAndCredId(DmOfflineParam offlineParam); +#endif private: void StartEventThread(); void StopEventThread(); @@ -107,9 +111,9 @@ private: DmAuthForm GetAuthForm(const std::string &networkId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) int32_t DeleteGroupByDP(const std::string &deviceId); + void DeleteCredential(DmOfflineParam offlineParam, const std::string &deviceId); #endif void ProcessDeviceStateChange(const DmDeviceState devState, const DmDeviceInfo &devInfo); - void DeleteCredential(DmOfflineParam offlineParam, const std::string &deviceId); private: std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 5e3342482..d1393eb31 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -28,7 +28,9 @@ #include "json_object.h" #include "parameter.h" #include "system_ability_definition.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "deviceprofile_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -76,6 +78,7 @@ void SoftbusConnector::SyncAclList(int32_t userId, std::string credId, { LOGI("SyncAclList userId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", userId, credId.c_str(), sessionKeyId, aclId); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) // 根据skid删除sk,删除skid int32_t ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, sessionKeyId); if (ret != DM_OK) { @@ -90,11 +93,13 @@ void SoftbusConnector::SyncAclList(int32_t userId, std::string credId, LOGE("SyncAclList DeleteCredential failed."); } } +#endif } int32_t SoftbusConnector::SyncLocalAclList5_1_0(const std::string localUdid, int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId, std::vector remoteAclList) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::vector localAclList = DeviceProfileConnector::GetInstance().GetAclList(localUdid, localUserId, remoteUdid, remoteUserId); for (auto &localAcl : localAclList) { @@ -118,6 +123,14 @@ int32_t SoftbusConnector::SyncLocalAclList5_1_0(const std::string localUdid, int } } return DM_OK; +#else + (void)localUdid; + (void)localUserId; + (void)remoteUdid; + (void)remoteUserId; + (void)remoteAclList; + return DM_OK; +#endif } int32_t SoftbusConnector::ParaseAclChecksumList(const std::string &jsonString, std::string &dmVersion, @@ -169,8 +182,17 @@ int32_t SoftbusConnector::SyncLocalAclListProcess(const std::string localUdid, i int32_t SoftbusConnector::GetAclListHash(const std::string localUdid, int32_t localUserId, const std::string remoteUdid, int32_t remoteUserId, std::string &aclList) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) return DeviceProfileConnector::GetInstance().GetAclListHashStr(localUdid, localUserId, remoteUdid, remoteUserId, aclList); +#else + (void)localUdid; + (void)localUserId; + (void)remoteUdid; + (void)remoteUserId; + (void)aclList; + return DM_OK; +#endif } int32_t SoftbusConnector::RegisterConnectorCallback(std::shared_ptr callback) @@ -456,6 +478,10 @@ void SoftbusConnector::OnSoftbusJoinLNNResult(ConnectionAddr *addr, const char * int32_t sessionId = addr->info.session.sessionId; CHECK_NULL_VOID(connectorCallback_); connectorCallback_->OnSoftbusJoinLNNResult(sessionId, networkId, result); +#else + (void)addr; + (void)networkId; + (void)result; #endif } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 1c2ce48d6..70e7674cb 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -319,6 +319,7 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) } } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void DmDeviceStateManager::DeleteCredential(DmOfflineParam offlineParam, const std::string &deviceId) { if (offlineParam.skIdVec.empty()) { @@ -351,6 +352,7 @@ int32_t DmDeviceStateManager::DeleteSkIdAndCredId(DmOfflineParam offlineParam) } return ret; } +#endif void DmDeviceStateManager::StartEventThread() { -- Gitee