diff --git a/bundle.json b/bundle.json index 769e15000358c1d34a54b3937164440df6de3611..2f4868a16fe58d0ed0e833ac748b62dd12e6d9c8 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 aa2c98547fb2fc7efd33c4120b5d67d2f7888092..5ba9498fdb3f5df9c81b5296e9ad5c82fd56592c 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 2d2b96fe2d4b863912ac2f8389b1d58c5bc6d74b..2a7c075ae5c22dbbb997aae7bf27917c627a9075 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 15d940b42c4cc07f5fac48d71e1305c60ad7c9b6..e2ac8903f2301380a39cb2cd9be1eaf4b5e55ab1 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/common/src/ipc/standard/ipc_model_codec.cpp b/common/src/ipc/standard/ipc_model_codec.cpp index 1091961c6f7cc45e7f05d277fd987f758d29a8be..daf2d650d8955f64ad496f12e8e05e131e4fc792 100644 --- a/common/src/ipc/standard/ipc_model_codec.cpp +++ b/common/src/ipc/standard/ipc_model_codec.cpp @@ -462,7 +462,7 @@ bool IpcModelCodec::DecodeStringVector(MessageParcel &parcel, std::vector MAX_DEVICE_PROFILE_SIZE) { - LOGE("num is Invalid value, num = %{public}zu", num); + LOGE("num is Invalid value, num = %{public}" PRIu32, num); return false; } for (uint32_t k = 0; k < num; k++) { diff --git a/commondependency/BUILD.gn b/commondependency/BUILD.gn index b5e8f1773b29df4016522e094d8060aff444a2a5..4071e35426c02c4de52962573e3b69025fa677d0 100644 --- a/commondependency/BUILD.gn +++ b/commondependency/BUILD.gn @@ -73,6 +73,7 @@ ohos_shared_library("devicemanagerdependency") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${json_path}:devicemanagerjson", "${utils_path}:devicemanagerutils", ] @@ -82,7 +83,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", @@ -143,6 +143,7 @@ ohos_shared_library("devicemanagerdependencytest") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${json_path}:devicemanagerjson", "${utils_path}:devicemanagerutils", ] @@ -152,7 +153,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 f0f697595f7739e221c02caec1df47afb1cb17e0..82470a30147a9667248aad09cd5020936bbdd561 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 a96752c432cdf3f134ad77613589d7f0387b3686..8d24824d98cba452b34d4cb95bf692de1248f9a3 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 bb48d6c15f711683375e9077a87f44e742f8a272..ac81fa16528be4c556953677cebe4a4fcfa730ca 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 1bcaa8d8eadc0e09cfa829854703eef59836642e..0b6949ea64c7813334d1f49ef65eef7eb02fe479 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 4478d94cf343dd79e9a8d562221065a41c2d5b83..0302487105f9fb987c8b2ceec1f598870d9d9015 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 e2855531e7087640550aa37e217a0a5c505c47e9..b93d073e433fb89e043b45a94d39dd81b9cbc3ab 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 de3ddcad6af1003901b039b468bf9bca71fc0f18..baf2529729b43519e44694149ae2a0b455e04e3c 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 dde7dbf83b63396621afb0f7c40bab4508754fee..a42b9d6a5044b1b4de156034e2422ca58c4ae035 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,18 @@ 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 3dee55dac8aee166321d11c24f53dfa8ccd857ee..2811a2e5ab79f15815b2cf3c889e3b888e7df5a1 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 0000000000000000000000000000000000000000..4d1d45934a6d75ce45fd5f082704ed767bf43713 --- /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 0000000000000000000000000000000000000000..e744a416398e0283380a04a885451e4f118cd84a --- /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 0000000000000000000000000000000000000000..49915a2c2afa978572753de2d699ed15922deb1a --- /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 0000000000000000000000000000000000000000..4565b12df2d454e37457661e506b4a8479a57397 --- /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 0000000000000000000000000000000000000000..896bd4cb2a4e976b050ca42c0bcc6393170d90ec --- /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 0000000000000000000000000000000000000000..00a4c80e26144c9bfc9bcbf5530e6a3c21cfab0e --- /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 0000000000000000000000000000000000000000..f8a21a9f0d8ef4429038811df2e66a20d9577bf2 --- /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 86a759081dcc686b32730176d758fda0a71369a9..e31e27c15f6c27e7e5150f1a515e1e8359eec570 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 94d418501b6005edf879fe3ba4d8a3455fef9d14..5684ef0c93ff0d34d59b461f96dbab96ad14d3bf 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.h b/services/implementation/include/dependency/hichain/hichain_connector.h index c6e518cadae2ef1a2656b05fee9859a996505f4e..c6210ddd80eb5b4c0521d58cb25c2ebcc4301224 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -155,7 +155,7 @@ public: * @tc.type: FUNC */ bool GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); - + bool GetGroupInfoExt(const int32_t userId, const std::string &queryParams, std::vector &groupList); bool GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 1e8e73f430f2a86209dad621e8fa96be5731e84d..56dd42bbc22b4281911f704856c9668330441348 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 718d7ddeb11f5c60b49d0887923b8beada28d987..f7c2acc85c8f2ca63c0dfc2422a855427e6a11cd 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 289a9cd60e3ad756eff66cfc0b3039ea401a09ab..b3dfc2840c51d70cb62f9858279d96ad30b329d8 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 423e5be0f97b24201ee09d1fd99478b97be22ffb..8365fe874083666eb0ed63ad80c1cf229d22693a 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 6cd5df070fa5e1050378aa840148670db89480a6..c0896ecc2e9c504bece72482ffed8a034f989ef0 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 74b0ca886422eac1e0e3784c5d3a107ae3d9fcad..5a39f1aac81376dd6f4742aacc3b705a4d7bc2ac 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/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 11b35a76255b36d9020965614aa379a5bb77df07..d5becb9cea662f54fa7b705e57b57b9e31194b6c 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -78,22 +78,23 @@ void DmDialogManager::ShowConfirmDialog(const std::string param) std::string appOperationStr = ""; std::string customDescriptionStr = ""; std::string hostPkgLabel = ""; + uint64_t tokenId = 0; int32_t deviceType = -1; JsonObject jsonObject(param); if (!jsonObject.IsDiscarded()) { - if (IsString(jsonObject, TAG_REQUESTER)) { + if (jsonObject[TAG_REQUESTER].IsString()) { deviceName = jsonObject[TAG_REQUESTER].Get(); } - if (IsString(jsonObject, TAG_APP_OPERATION)) { + if (jsonObject[TAG_APP_OPERATION].IsString()) { appOperationStr = jsonObject[TAG_APP_OPERATION].Get(); } - if (IsString(jsonObject, TAG_CUSTOM_DESCRIPTION)) { + if (jsonObject[TAG_CUSTOM_DESCRIPTION].IsString()) { customDescriptionStr = jsonObject[TAG_CUSTOM_DESCRIPTION].Get(); } - if (IsInt32(jsonObject, TAG_LOCAL_DEVICE_TYPE)) { + if (jsonObject[TAG_LOCAL_DEVICE_TYPE].IsNumberInteger()) { deviceType = jsonObject[TAG_LOCAL_DEVICE_TYPE].Get(); } - if (IsString(jsonObject, TAG_HOST_PKGLABEL)) { + if (jsonObject[TAG_HOST_PKGLABEL].IsString()) { hostPkgLabel = jsonObject[TAG_HOST_PKGLABEL].Get(); } } @@ -201,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = SafetyDump(param); + std::string paramStr = param.Dump(); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 273db6dfb1bc88f6a79a0fd66d53d12f24e1510e..44294f3b08223e4921dea2b1be7a14e10366326f 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 17d8b08f38d8d6b11f2e69bbf4f81c6c09a94700..6bf532d83db4ad9f6bc3f8e35e606ff4fe42c988 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); @@ -2294,26 +2241,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() @@ -2568,7 +2498,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; @@ -2596,6 +2528,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."); @@ -2612,7 +2565,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) { @@ -2674,7 +2627,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; @@ -3028,21 +2981,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 = ""; @@ -3088,13 +3026,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; } @@ -3142,7 +3080,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; } @@ -3164,7 +3102,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; @@ -3283,11 +3221,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; } @@ -3399,5 +3332,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 0000000000000000000000000000000000000000..7edf86dc68534f1e91221fb5ce0a60557d7d9bab --- /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 0000000000000000000000000000000000000000..0b913a0b43516944cfc8f3c963ed8ffb7b141a0e --- /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 0000000000000000000000000000000000000000..4d201c7194290549c76855f6970453c584e901d1 --- /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 0000000000000000000000000000000000000000..9f1169a0c5107859a28689c1a062fd6b25dc7b16 --- /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 0000000000000000000000000000000000000000..fa3ee432d24c157a00227b50726d7c3127a007cc --- /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 0000000000000000000000000000000000000000..f53c7162eace95c46f88d4fd75084e91f0d1a866 --- /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 0000000000000000000000000000000000000000..13bfb140a2765b31b971099312f1516ea72d96f9 --- /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 0000000000000000000000000000000000000000..24d710867cede19e044e5b0de68e981295f257ed --- /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 0000000000000000000000000000000000000000..bc87c07c6188c958b0811f060e507e6cd252d9c1 --- /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 0000000000000000000000000000000000000000..dcc2c87f6ff1ab3df3e2bf7a18f89486af22a3b9 --- /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 0000000000000000000000000000000000000000..6cef7a6dc1e81deefd95b263a3f7f0c99e99f494 --- /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 0000000000000000000000000000000000000000..8111934cf870a853f11853b501d63f980c4b0f8d --- /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 91d35dee06ff9b250dc4346ff3b965c7ae3be67c..4af9f65f9b0a4bddb00f8573e641e8e8a878366a 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 cf9af2ad4094068ac64b25fbe218f9392f80418c..51343a786af3af7d1023896944d6b8d6a816ecfb 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 0af9630944e8c84427f4f38b25a4923a7bf198fd..680c1c4fdc020a9101dd8bfdedb6b1ea6019b507 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 125ffce5a8fd7babde8ad1b45e138d223af4218d..393105765bb5680a1f31c06382723cd20a6bcfd3 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 12ad2f7fd1c914bfadfc2d17b64aa1b3aacac9c7..8eb9aaf0099a9edea2a9e2f1c3716caefabec92d 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 516b29bdae29d001874dd3f6398db0dced44974e..7cabe0aa36f58986cf4599bbc0c64d7d9fabc8c0 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 d88646d7c854b2ba978559e1f926d070eb21eae8..736c75c9dc073558fb88dad4dfb26a720cce4bdb 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 3357cd49ba40556de557af72b20dae93f61ba8cc..2ecf862e493d3c32d4616875bd7015a6f1861fe9 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 8b40da361de4cc8b9c948e410a4e99f8a483bb4d..b924f1fe61cd801c960764aa970d9b9ee66deba2 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 7d2e349069b9cd300cc5c2419109c5377b114cc3..4fc1b9c06e81009e0070057f69368e807bb8e2fa 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 227a5caf5e63641117ca336caaf59f08bb424d04..641f333c606d6de36791119b1d7d4d8596cd3059 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -69,6 +69,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; @@ -77,6 +78,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 9e0941b66640e1cbd0cc8fd4deb41044f10dfa5e..33332d929a9afbf7ac4073754f73364e2ee70058 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -75,6 +75,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 4aedfa71ed0e7a35e5e362cb4beb0b4a822810cb..6c838a651fa11cd580e13255fe14fa4eeb6de96b 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2065,6 +2065,9 @@ void DeviceManagerService::UpdateAclAndDeleteGroup(const std::string &localUdid, } discoveryMgr_->GetCommonDependencyObj()->HandleUserSwitched(localUdid, deviceVec, foregroundUserIds, backgroundUserIds); + //delete group + CHECK_NULL_VOID(hichainListener_); + hichainListener_->DeleteAllGroup(localUdid, backgroundUserIds); } #endif @@ -2156,8 +2159,8 @@ void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) if (!peerUdids.empty()) { // Send UserId Removed broadcast SendUserRemovedBroadCast(peerUdids, removedUserId); - dmServiceImpl_->HandleUserRemoved(peerUdids, removedUserId); } + dmServiceImpl_->HandleUserRemoved(removedUserId); } void DeviceManagerService::SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId) @@ -2416,7 +2419,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; } @@ -2433,7 +2436,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; } @@ -2529,6 +2532,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); @@ -2730,6 +2737,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/dm_comm_tool.cpp b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp index 7047624ffed3b3b56a9dd3fec040fa6ff77b20fe..01a64b6723649cd6fa12b21627f7e295a564f09f 100644 --- a/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp +++ b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp @@ -225,7 +225,7 @@ void DMCommTool::ProcessReceiveUserIdsEvent(const std::shared_ptr } RspLocalFrontOrBackUserIds(commMsg->remoteNetworkId, foregroundUserIdsU32, backgroundUserIdsU32, commMsg->socketId); - + if (userIdsMsg.foregroundUserIds.empty()) { LOGE("Parse but get none remote foreground userids"); } else { diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 962391c13c068ba88046af53acd81126816f3722..ce38f2adedde02782d617791b0bde409f070d51d 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 2379642244e648ffc0cdc88408e0e83ef52b71fd..e91ba803bc8284ede06f096eeae6be7dd6c8a5f9 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 4430b898c558325dd8cf715f3cac09ba6f42408f..c88c67ba243daa0e32af9e3f00ab22ec24c2da27 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 191a46aa1070728afed3e3a71f6ca32bc47ee592..4534e8cce5ac01f9400658b1743917b189dd9f6f 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 c8a6e778480b7e0b3faa5bcc309efb8d02c0bcbe..de76f2d4aa6b65dad69c5f5b068bfeb2b0baea36 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 aed9accd40744a9eab9f5d717ea9fbc9a7bb6f64..4c990cac6e13939278ad1ff56bb62e8619c92f5c 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 2e0da79a6ed094286e2bf2978cfb691378b20813..fc9ff5b798328c4486989738b3a0c29ed9fd6e75 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 0000000000000000000000000000000000000000..d81bcb502e38be6378174149c5bfffb99301ba6f --- /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 0000000000000000000000000000000000000000..d9719cafab50ed61d354cfa865b56390a0df320f --- /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 0000000000000000000000000000000000000000..0858f3b678166b252a4acf2a0d3daefcadf80304 --- /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 0000000000000000000000000000000000000000..35643d1c413a5faa1d10d0d6c7812892ccdc835f --- /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 0000000000000000000000000000000000000000..bac4974e9068af3c045fbb5c3a588aa79e47faaf --- /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 37ac3b0882be4706e0859edaeba78ae37bbe5961..7e9a4120ebd6d71fd471a47b704ec937bb637453 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 6d3c8e043aa684129c9c185f3025076c40748855..d7dfefd1819fa9922f7e9f7bc26c471342d41077 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 0000000000000000000000000000000000000000..6ecb86c334bd32a4db1446815127efec6fea8222 --- /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 0000000000000000000000000000000000000000..d9719cafab50ed61d354cfa865b56390a0df320f --- /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 0000000000000000000000000000000000000000..6b1cec0cce5b11b9e4a006347f610375c8e85417 --- /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 0000000000000000000000000000000000000000..e59b91fdae845288037debbdd6947feafed4a93e --- /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 0000000000000000000000000000000000000000..bac4974e9068af3c045fbb5c3a588aa79e47faaf --- /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 05eafbd5a6eb3556551db3c9a3d2c5fd212ae6ab..dca3887cf3fb8893e7114574c1cfd84c582d7586 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 d21f5d1fbeb52deada20e3df82e44e53abd046ea..3c4e2a88bc913b87ebd78e4328828328596624b9 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 248c1dd4e9385ae8203284a2809a1053318173eb..b268f554c8d592db60c4e2e5aee5bfd43bbe0218 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 3eeb05cbd0f00568c72c81a3764dbb42647f86c5..d0ed889605c3074bf8d6b33fc6056c05ae158d9a 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, 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 89df6d0d36d62d33b08e651734e18923f9037c30..e1ebd3cfec07d5333fb01741cca0a19289c10cc9 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 2e644498ea9fe8583db27059cfa233ea24065fa8..559b079e28f67f0c61163efcc6fe874afdd784aa 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 9a82df9538f3a0d4e9a1ef223ebacbcaad812817..88d823b1db3ed28bb1f0e7b41c4f49e74fae8395 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 523d6d2599ad98286b5942f3aad2027a3cf33648..7f777ce5046d5e37614c838c40f3a04474d5cd25 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 805b97404b3c7aec4b62b5c2e5aac3149d2fcb71..9058c5861cbdbad432fd41d96b0e233d3d319461 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 3c708b59809563ae030627fca58ac720f75859bf..fdff7c0cb49a42b48fb584e6502521bc6d887a1d 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 deefda7e9467094a87d1ec283284c32ece7e90fc..c2d76c6f966e195a83718921174f4152357f8c8f 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 35a631553f94aaa22be718fc6dff48e5ff08f5f8..aa336a977a4339e36548dc937bf4e7dfc697bb1f 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 fb5dd1d3246fa657f05de547400f17bb86c5beaa..c7875807c9ff81f52e3cf37edc222dbb06ecaaea 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 c869bb10a56aa94fd00b0d7faa6a8cb0dcff4e8b..b1104c112c4fac2ca56eb170c69669dc5884fa9e 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -70,7 +70,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 f848667b267937d2caa015fa80023230ffa0a010..6c5daba150e337a67d17be6f3de7a05f06d299cc 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -70,7 +70,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 2d0979540abe7b696cf88c84ccf7174a15facdf1..2fe1110fdb279e1bf0a31e18fd22d9a0bb1147d5 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 1a3c66d97fed6a8e73fb66ff71aa3a2b3c01f0ac..df0fa3fac645ee9236c96b1dfada812ec024648f 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 571edcf51b4a7a7740f0c41634c24e4ef3488e37..56e4a9ea9374c8b8f5e99d958e0dd15e79f6a90a 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 b2660a05f12c6ccef0f050078e712b01c434cbd9..e484bda715f4df37afa9d49a802c1501e1f8cc4b 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 9fabf87c8cd54d6c98fbf07a457a2b0f97fdd82a..e54de95666c49d18e7ae10773ead88d0592305f2 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 53f50fa3f1c3bbf1bca1dc5af71e054ae495a5a9..0f22b5c0c5c04a14090544b408d4535fcb83e3a6 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 8151476ebb5ebe9244a8b21a724538ec82a80b5b..c40cd2536fe9033000563307f66a8355981a1c68 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 d58d41e9c6fcce10aab8fd0ffba1b1698eaff7a9..23eed5f2e12196b6dbe189b5bc6c3e905d09902c 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 a079a5c9e2322e124616c2320badb8891170d377..9df6f8cdc50bfc013fe330e613e6b8d09cabff27 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 2010752ded433c8a6e8b6fc3e12d0bb0418b121e..ac36259b25772374c7750a386e2227fbfd895958 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 fe688c42f599ad3d63da0832dddb28801925fd5c..3d76c29caee89fac337cd42db5a3d29f9939e7eb 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 c510b8492bfe0bfe6c9218e83054b2e854962bc6..deb4a4b086fa939048390a8825c1959951f5095c 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 e5618bb35a4801c8146e5374e8c107e00e20e702..3559e9d18fdece35730974946351d143f03839e0 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 01d95d171b5dc2f04bf7a41c7da249d89acd2de3..914eb193254492c8503d6e0301f8f6759358721b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -91,6 +91,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", ] } @@ -1186,7 +1189,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", @@ -1919,6 +1921,7 @@ ohos_unittest("UTTest_advertise_manager") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", "dsoftbus:softbus_client", "ffrt:libffrt", "googletest:gmock", @@ -1948,6 +1951,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 0000000000000000000000000000000000000000..519690d9b3ca7f54c2471559bc1af20b4bf82e48 --- /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 0000000000000000000000000000000000000000..ba289305185fa2ed001f236eab9e89ad81ddf913 --- /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 0000000000000000000000000000000000000000..5d276478c3d811fd4fcdfba48ad0654ec3e1fc21 --- /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 0000000000000000000000000000000000000000..d385723bc59b782bb31274cc1478539d03ddfac2 --- /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 0000000000000000000000000000000000000000..acd9376eec9ad40859aba25c2fb896f64eb055e5 --- /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 0000000000000000000000000000000000000000..6d4fee840880a991737b92609f58b57935d0ea04 --- /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 e711089afc466a6b264883a7cbc63b8b558435b4..90514cea85619fe6037587d014ac02a41ccf297e 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 05550beebbc9f11784454e1bfe062ab46d1a39c2..21c5bdfbce7801f999a964e2c6f520e7e6be98d9 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 952cbe49d7f192208988bcdf0a5e703a1077759f..b09860eee93b5c2c5a78a220a8457b6e912f9bbe 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 ea0aa57f4241a00f207a7fbc49242b5e2287ae8a..885ddbee15e3607ae5fadbabc661aeb67c0ef5a0 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 08e5dd4e5eb2624908288ca937c5161086ae8fe0..310b00c3baa81c61ee2914103320bae6edf654c2 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(); @@ -1822,7 +1825,7 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::Te std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, DM_OK); 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 b8b947ac7f70ca2d01631a19a65efa5d2e1b75a1..37672cddff392ccf1ae127a9cd1126f731576c15 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 8eea619caf5deaabdc1a3b35f014d0bafee69a52..6a1ec8a9bceb6f965bfaba308ff923e5548eed15 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 d98ba12118637581c699177cd526b6cabad3ce55..37cf2b5efa3b623c2ca0519874de656a3bb3f928 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); @@ -1280,11 +1287,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); } @@ -1335,6 +1342,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); } @@ -1447,8 +1455,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); @@ -1490,7 +1499,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; @@ -1548,7 +1557,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, @@ -1696,7 +1705,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)); @@ -1726,7 +1735,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)); @@ -1780,7 +1789,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 ab8fb40a0d00fa2a54c6b4cf2a8b31e807aea759..cecb212cee9b316f23477aa10cd190df1650081a 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 e021413695703e281e4e125eda9d552d348c9acd..5fa664674b9a259d6624699e0a7e6f2e767a3164 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 0000000000000000000000000000000000000000..8d5ce21ed764b3e69a604df8c3c86b7463913d78 --- /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 0000000000000000000000000000000000000000..89a79689e7313da4c8e463c64f1a05d646d897ed --- /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 0000000000000000000000000000000000000000..49da4bfb235e6a0dba79b6cc6ec11b45434061ba --- /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 0000000000000000000000000000000000000000..9489d08fdd24af99cdc60d9c3991b1441d3c0392 --- /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 3a7a416c264debec28fa0198c26d447f51879e7e..dd7f98ffb49a101dcc4003e7dd1a1595d56bf6f1 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 bdcd74fd6d36999fb24245421952c6fb006b6d8e..d0de67f9e5a85d818f4d13bccb973eda61351936 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 50f194432304fa33754b12a2771175cf8fe1dc64..7a237c25edb45ec2dbbba379095e91138e834047 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 bbaedbb8916c88da8bf36a75a955e3ae34c1505a..3575e978b3f91e10603ffb3791701606394435be 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 b6ce63c77222bc92fa73cd824a7d891013c775d4..84d251e9dd725f9531967f208dec641cb5920082 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 69879f418c0ae1db8531d30c3050b4437d2418dc..ef8f53df878e193847db412447acfa7082f9a8cb 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 171311d9e12928d00987ab556840780d6f347a16..77c65ea4964177d5af32c3dc4456aa9eeaf2d6cf 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 fa25cade0a505546bbd06a048f06b0a5412e04d6..a8caf14924294101e2c41f41025eba5456c137ee 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 1c657174e59e2ded6d5ea21c61fae41db0927732..c85d7045d13a77be7fea3621d4830ec6912454da 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 732174ef40b77da80c5bd2633e77ab078772c198..9f386d18388b8c01da00ab872a8e5fad15852dd3 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 6d2ec638da249a11c3338365d3a08a9d1330d28c..015adfa62ad622095f3523cea6e35a1cd9ddad2f 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};