From f02fa44a46e664a42faaf71b4c37b93c42f9291f Mon Sep 17 00:00:00 2001 From: libing23 Date: Mon, 21 Feb 2022 21:07:47 +0800 Subject: [PATCH] add token_sync mock unittest Signed-off-by: libing23 --- BUILD.gn | 1 + .../include/i_accesstoken_manager.h | 9 +- interfaces/innerkits/accesstoken/BUILD.gn | 1 + .../include/accesstoken_death_recipient.h | 35 + .../accesstoken/include/accesstoken_kit.h | 1 + .../src/accesstoken_death_recipient.cpp | 35 + .../accesstoken/src/accesstoken_kit.cpp | 7 + .../src/accesstoken_manager_client.cpp | 68 +- .../src/accesstoken_manager_client.h | 5 + .../src/accesstoken_manager_proxy.cpp | 31 + .../src/accesstoken_manager_proxy.h | 1 + .../unittest/src/accesstoken_kit_test.cpp | 70 +- .../service/accesstoken_manager_service.h | 1 + .../service/accesstoken_manager_stub.h | 1 + .../include/token/accesstoken_info_manager.h | 1 + .../cpp/include/token/hap_token_info_inner.h | 1 + .../service/accesstoken_manager_service.cpp | 9 + .../src/service/accesstoken_manager_stub.cpp | 16 + .../src/token/accesstoken_info_manager.cpp | 42 +- .../accesstoken_remote_token_manager.cpp | 1 + .../cpp/src/token/hap_token_info_inner.cpp | 5 + .../cpp/src/token/native_token_info_inner.cpp | 4 +- .../src/remote/remote_command_executor.cpp | 4 + .../src/remote/soft_bus_manager.cpp | 1 - .../test/mock/include/mock_parameter.h | 33 + .../test/mock/include/session.h | 354 ++++++++++ .../test/mock/src/constant_mock.cpp | 40 ++ .../test/mock/src/mock_parameter.c | 26 + .../test/mock/src/soft_bus_center_mock.cpp | 98 +++ .../test/mock/src/soft_bus_session_mock.cpp | 223 +++++++ .../test/unittest/token_sync_service/BUILD.gn | 100 +++ .../token_sync_service_test.cpp | 606 ++++++++++++++++++ .../token_sync_service_test.h | 36 ++ 33 files changed, 1828 insertions(+), 38 deletions(-) create mode 100644 interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h create mode 100644 interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp create mode 100644 services/tokensyncmanager/test/mock/include/mock_parameter.h create mode 100644 services/tokensyncmanager/test/mock/include/session.h create mode 100644 services/tokensyncmanager/test/mock/src/constant_mock.cpp create mode 100644 services/tokensyncmanager/test/mock/src/mock_parameter.c create mode 100644 services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp create mode 100644 services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp create mode 100644 services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn create mode 100644 services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp create mode 100644 services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h diff --git a/BUILD.gn b/BUILD.gn index d57c193e9..01805d6c9 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -46,6 +46,7 @@ group("accesstoken_build_module_test") { "//base/security/access_token/interfaces/innerkits/token_setproc/test:unittest", "//base/security/access_token/interfaces/innerkits/tokensync/test:unittest", "//base/security/access_token/services/accesstokenmanager/test:unittest", + "//base/security/access_token/services/tokensyncmanager/test/unittest/token_sync_service:unittest", ] } } diff --git a/frameworks/accesstoken/include/i_accesstoken_manager.h b/frameworks/accesstoken/include/i_accesstoken_manager.h index 12b1d3165..0cb3e8219 100644 --- a/frameworks/accesstoken/include/i_accesstoken_manager.h +++ b/frameworks/accesstoken/include/i_accesstoken_manager.h @@ -59,15 +59,15 @@ public: AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParcel& policyParcel) = 0; virtual int GetHapTokenInfoFromRemote(AccessTokenID tokenID, - HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; virtual int GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) = 0; virtual int SetRemoteHapTokenInfo(const std::string& deviceID, - HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; virtual int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoParcel) = 0; - virtual int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) = 0; virtual int DeleteRemoteDeviceTokens(const std::string& deviceID) = 0; - virtual int DumpToken(std::string& dumpInfo) = 0; enum class InterfaceCode { @@ -95,6 +95,7 @@ public: SET_REMOTE_NATIVE_TOKEN_INFO = 0xff2a, DELETE_REMOTE_TOKEN_INFO = 0xff2b, DELETE_REMOTE_DEVICE_TOKEN = 0xff2c, + GET_NATIVE_REMOTE_TOKEN = 0xff2f, DUMP = 0xff30, }; diff --git a/interfaces/innerkits/accesstoken/BUILD.gn b/interfaces/innerkits/accesstoken/BUILD.gn index 2c353eec6..95c8b1f17 100644 --- a/interfaces/innerkits/accesstoken/BUILD.gn +++ b/interfaces/innerkits/accesstoken/BUILD.gn @@ -39,6 +39,7 @@ ohos_shared_library("libaccesstoken_sdk") { ] sources = [ + "src/accesstoken_death_recipient.cpp", "src/accesstoken_kit.cpp", "src/accesstoken_manager_client.cpp", "src/accesstoken_manager_proxy.cpp", diff --git a/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h b/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h new file mode 100644 index 000000000..a48cc7703 --- /dev/null +++ b/interfaces/innerkits/accesstoken/include/accesstoken_death_recipient.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef ACCESS_TOKNE_DEATH_RECIPIENT_H +#define ACCESS_TOKNE_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class AccessTokenDeathRecipient : public IRemoteObject::DeathRecipient { +public: + AccessTokenDeathRecipient() {}; + virtual ~AccessTokenDeathRecipient() = default; + void OnRemoteDied(const wptr &object) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESS_TOKNE_DEATH_RECIPIENT_H + diff --git a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h index 495f451d9..5d1da2003 100644 --- a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h +++ b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h @@ -59,6 +59,7 @@ public: static int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoList); static int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + static AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); static int DeleteRemoteDeviceTokens(const std::string& deviceID); static int DumpToken(std::string& dumpInfo); }; diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp new file mode 100644 index 000000000..cd00a5477 --- /dev/null +++ b/interfaces/innerkits/accesstoken/src/accesstoken_death_recipient.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "accesstoken_death_recipient.h" + +#include "accesstoken_log.h" +#include "accesstoken_manager_client.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenDeathRecipient"}; +} // namespace + +void AccessTokenDeathRecipient::OnRemoteDied(const wptr &object) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + AccessTokenManagerClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp index dbdad0dab..fd2b02f46 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -321,6 +321,13 @@ int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); } +AccessTokenID AccessTokenKit::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, deviceID.c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); +} + int AccessTokenKit::DumpToken(std::string& dumpInfo) { return AccessTokenManagerClient::GetInstance().DumpToken(dumpInfo); diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp index fc9225c37..2675cf886 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp @@ -347,6 +347,19 @@ int AccessTokenManagerClient::DeleteRemoteToken(const std::string& deviceID, Acc return res; } +AccessTokenID AccessTokenManagerClient::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + AccessTokenID res = proxy->GetRemoteNativeTokenID(deviceID, tokenID); + return res; +} + int AccessTokenManagerClient::DeleteRemoteDeviceTokens(const std::string& deviceID) { ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); @@ -372,30 +385,47 @@ int AccessTokenManagerClient::DumpToken(std::string& dumpInfo) return res; } -sptr AccessTokenManagerClient::GetProxy() +void AccessTokenManagerClient::InitProxy() { + std::lock_guard lock(proxyMutex_); if (proxy_ == nullptr) { - std::lock_guard lock(proxyMutex_); + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); + return; + } + auto accesstokenSa = sam->GetSystemAbility(IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); + if (accesstokenSa == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", + IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); + return; + } + + serviceDeathObserver_ = new (std::nothrow) AccessTokenDeathRecipient(); + if (serviceDeathObserver_ != nullptr) { + accesstokenSa->AddDeathRecipient(serviceDeathObserver_); + } + proxy_ = iface_cast(accesstokenSa); if (proxy_ == nullptr) { - auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (sam == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); - return nullptr; - } - auto accesstokenSa = sam->GetSystemAbility(IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); - if (accesstokenSa == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", - IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); - return nullptr; - } - - proxy_ = iface_cast(accesstokenSa); - if (proxy_ == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); - return nullptr; - } + ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); } } +} + +void AccessTokenManagerClient::OnRemoteDiedHandle() +{ + { + std::lock_guard lock(proxyMutex_); + proxy_ = nullptr; + } + InitProxy(); +} + +sptr AccessTokenManagerClient::GetProxy() +{ + if (proxy_ == nullptr) { + InitProxy(); + } return proxy_; } } // namespace AccessToken diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h index d3cc13fca..5d4e92642 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h @@ -21,6 +21,7 @@ #include #include "access_token.h" +#include "accesstoken_death_recipient.h" #include "hap_info_parcel.h" #include "hap_policy_parcel.h" #include "hap_token_info.h" @@ -63,8 +64,10 @@ public: int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoList); int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); int DeleteRemoteDeviceTokens(const std::string& deviceID); int DumpToken(std::string& dumpInfo); + void OnRemoteDiedHandle(); private: AccessTokenManagerClient(); @@ -72,6 +75,8 @@ private: DISALLOW_COPY_AND_MOVE(AccessTokenManagerClient); std::mutex proxyMutex_; sptr proxy_ = nullptr; + sptr serviceDeathObserver_ = nullptr; + void InitProxy(); sptr GetProxy(); }; } // namespace AccessToken diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp index af6849ecb..0f7369576 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp @@ -774,6 +774,37 @@ int AccessTokenManagerProxy::DeleteRemoteToken(const std::string& deviceID, Acce return result; } +AccessTokenID AccessTokenManagerProxy::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return 0; + } + + if (!data.WriteUint32(tokenID)) { + return 0; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return 0; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_REMOTE_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return 0; + } + + AccessTokenID result = reply.ReadUint32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + int AccessTokenManagerProxy::DeleteRemoteDeviceTokens(const std::string& deviceID) { MessageParcel data; diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h index 55655a6f4..913f3022d 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h @@ -64,6 +64,7 @@ public: int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoParcel) override; int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) override; int DeleteRemoteDeviceTokens(const std::string& deviceID) override; int DumpToken(std::string& dumpInfo) override; diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp index e3fca2f8a..f2c4c6096 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp @@ -2936,7 +2936,7 @@ HWTEST_F(AccessTokenKitTest, GetHapTokenInfoFromRemote001, TestSize.Level1) /** * @tc.name: GetHapTokenInfoFromRemote002 - * @tc.desc: get normal mapping tokenInfo + * @tc.desc: get remote mapping tokenInfo * @tc.type: FUNC * @tc.require:AR000GK6TA */ @@ -2986,7 +2986,7 @@ HWTEST_F(AccessTokenKitTest, GetHapTokenInfoFromRemote002, TestSize.Level1) /** * @tc.name: GetHapTokenInfoFromRemote003 - * @tc.desc: get normal mapping tokenInfo + * @tc.desc: get wrong tokenInfo * @tc.type: FUNC * @tc.require:AR000GK6TA */ @@ -2997,3 +2997,69 @@ HWTEST_F(AccessTokenKitTest, GetHapTokenInfoFromRemote003, TestSize.Level1) int ret = AccessTokenKit::GetHapTokenInfoFromRemote(0, infoSync); ASSERT_NE(ret, RET_SUCCESS); } + +/** + * @tc.name: AllocLocalTokenID001 + * @tc.desc: get already mapping tokenInfo, makesure ipc right + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(AccessTokenKitTest, AllocLocalTokenID001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "AllocLocalTokenID001 start."); + std::string deviceID = "ea82205d1f9964346ee12e17ec0f362bb7203fca7c62d82899ffa917f9cbe6b2"; + AccessTokenKit::DeleteRemoteToken(deviceID, 0x20100000); + HapTokenInfo baseInfo = { + .apl = APL_NORMAL, + .ver = 1, + .userID = 1, + .bundleName = "com.ohos.access_token", + .instIndex = 1, + .appID = "testtesttesttest", + .deviceID = "ea82205d1f9964346ee12e17ec0f362bb7203fca7c62d82899ffa917f9cbe6b2", + .tokenID = 0x20100000, + .tokenAttr = 0 + }; + + PermissionStateFull infoManagerTestState = { + .grantFlags = {PermissionFlag::PERMISSION_USER_SET}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"}}; + std::vector permStateList; + permStateList.emplace_back(infoManagerTestState); + + HapTokenInfoForSync remoteTokenInfo = { + .baseInfo = baseInfo, + .permStateList =permStateList + }; + + int ret = AccessTokenKit::SetRemoteHapTokenInfo(deviceID, remoteTokenInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(deviceID, 0x20100000); + ASSERT_NE(mapID, 0); +} + +/** + * @tc.name: GetAllNativeTokenInfo001 + * @tc.desc: get already mapping tokenInfo, makesure ipc right + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(AccessTokenKitTest, GetAllNativeTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetAllNativeTokenInfo001 start."); +} + +/** + * @tc.name: SetRemoteNativeTokenInfo001 + * @tc.desc: get already mapping tokenInfo, makesure ipc right + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(AccessTokenKitTest, SetRemoteNativeTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetAllNativeTokenInfo001 start."); +} diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h index cbb3cfa14..9cf112728 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h @@ -64,6 +64,7 @@ public: int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoParcel) override; int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) override; int DeleteRemoteDeviceTokens(const std::string& deviceID) override; int DumpToken(std::string& dumpInfo) override; diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h index c4fbb77e1..6021a0730 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -59,6 +59,7 @@ private: void SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); void DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply); void DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply); + void GetRemoteNativeTokenIDInner(MessageParcel& data, MessageParcel& reply); void GetRemoteHapTokenIDInner(MessageParcel& data, MessageParcel& reply); void DumpTokenInner(MessageParcel& data, MessageParcel& reply); diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h index 3c4329380..dae3e0c83 100644 --- a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h @@ -62,6 +62,7 @@ public: int SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoList); int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); int DeleteRemoteDeviceTokens(const std::string& deviceID); private: diff --git a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h index add61cb1d..087d692ed 100644 --- a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h +++ b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h @@ -52,6 +52,7 @@ public: std::string GetBundleName() const; int GetInstIndex() const; AccessTokenID GetTokenID() const; + void SetTokenBaseInfo(const HapTokenInfo& baseInfo); void SetPermissionPolicySet(std::shared_ptr& policySet); void ToString(std::string& info) const; bool IsRemote() const; diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp index 4fe4e741b..f5927dc9a 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -286,6 +286,15 @@ int AccessTokenManagerService::DeleteRemoteToken(const std::string& deviceID, Ac return AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceID, tokenID); } +AccessTokenID AccessTokenManagerService::GetRemoteNativeTokenID(const std::string& deviceID, + AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: %{public}s, token id %{public}d", + __func__, deviceID.c_str(), tokenID); + + return AccessTokenInfoManager::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); +} + int AccessTokenManagerService::DeleteRemoteDeviceTokens(const std::string& deviceID) { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: %{public}s", __func__, deviceID.c_str()); diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp index afb050cda..6d4bd9123 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -355,6 +355,20 @@ void AccessTokenManagerStub::DeleteRemoteTokenInner(MessageParcel& data, Message reply.WriteInt32(result); } +void AccessTokenManagerStub::GetRemoteNativeTokenIDInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + + AccessTokenID result = this->GetRemoteNativeTokenID(deviceID, tokenID); + reply.WriteUint32(result); +} + void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply) { if (!IsAuthorizedCalling()) { @@ -436,6 +450,8 @@ AccessTokenManagerStub::AccessTokenManagerStub() &AccessTokenManagerStub::DeleteRemoteTokenInner; requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_DEVICE_TOKEN)] = &AccessTokenManagerStub::DeleteRemoteDeviceTokensInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_REMOTE_TOKEN)] = + &AccessTokenManagerStub::GetRemoteNativeTokenIDInner; requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DUMP)] = &AccessTokenManagerStub::DumpTokenInner; } diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp index c504c2c72..5b456fdfc 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -548,7 +548,8 @@ void AccessTokenInfoManager::GetAllNativeTokenInfo(std::vector& Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); for (auto nativeTokenInner : nativeTokenInfoMap_) { std::shared_ptr nativeTokenInnerPtr = nativeTokenInner.second; - if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote()) { + if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote() + || nativeTokenInnerPtr->GetDcap().size() <= 0) { continue; } NativeTokenInfo token; @@ -561,8 +562,8 @@ void AccessTokenInfoManager::GetAllNativeTokenInfo(std::vector& int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync) { std::shared_ptr infoPtr = GetHapTokenInfoInner(mapID); - if (infoPtr == nullptr) { - ACCESSTOKEN_LOG_INFO(LABEL, "token 0x%{public}x is null, can not update!", mapID); + if (infoPtr == nullptr || !infoPtr->IsRemote()) { + ACCESSTOKEN_LOG_INFO(LABEL, "token 0x%{public}x is null or not remote, can not update!", mapID); return RET_FAILED; } @@ -572,6 +573,7 @@ int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTok { Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); + infoPtr->SetTokenBaseInfo(hapSync.baseInfo); infoPtr->SetPermissionPolicySet(newPermPolicySet); } return RET_SUCCESS; @@ -579,8 +581,6 @@ int AccessTokenInfoManager::UpdateRemoteHapTokenInfo(AccessTokenID mapID, HapTok int AccessTokenInfoManager::CreateRemoteHapTokenInfo(AccessTokenID mapID, HapTokenInfoForSync& hapSync) { - // update remote token mapping id - hapSync.baseInfo.tokenID = mapID; std::shared_ptr hap = std::make_shared(mapID, hapSync.baseInfo, hapSync.permStateList); if (hap == nullptr) { @@ -618,6 +618,9 @@ int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, H if (mapID != 0) { ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x update exist remote hap token %{public}x.", deviceID.c_str(), remoteID, mapID); + // update remote token mapping id + hapSync.baseInfo.tokenID = mapID; + hapSync.baseInfo.deviceID = deviceID; return UpdateRemoteHapTokenInfo(mapID, hapSync); } @@ -628,6 +631,10 @@ int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, H return RET_FAILED; } + // update remote token mapping id + hapSync.baseInfo.tokenID = mapID; + hapSync.baseInfo.deviceID = deviceID; + if (CreateRemoteHapTokenInfo(mapID, hapSync) == RET_FAILED) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x map to local token %{public}x failed.", @@ -648,9 +655,9 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID } for (NativeTokenInfo& nativeToken : nativeTokenInfoList) { - if (!DataValidator::IsAplNumValid(nativeToken.apl) - || nativeToken.ver != DEFAULT_TOKEN_VERSION - || !DataValidator::IsProcessNameValid(nativeToken.processName)) { + if (!DataValidator::IsAplNumValid(nativeToken.apl) || nativeToken.ver != DEFAULT_TOKEN_VERSION + || !DataValidator::IsProcessNameValid(nativeToken.processName) || nativeToken.dcap.size() <= 0 + || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(nativeToken.tokenID) != TOKEN_NATIVE) { ACCESSTOKEN_LOG_ERROR( LABEL, "device %{public}s token %{public}x is invalid.", deviceID.c_str(), nativeToken.tokenID); continue; @@ -658,9 +665,14 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID AccessTokenID remoteID = nativeToken.tokenID; AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); - if (mapID == 0) { - mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); + if (mapID != 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x has maped, no need update it.", + deviceID.c_str(), nativeToken.tokenID); + continue; } + + mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); if (mapID == 0) { AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); ACCESSTOKEN_LOG_ERROR( @@ -730,6 +742,16 @@ int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, Acces return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID); } +AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) + || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", deviceID.c_str()); + return 0; + } + return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); +} + int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID) { if (!DataValidator::IsDeviceIdValid(deviceID)) { diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp index 17cb414d0..1334c19ea 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -69,6 +69,7 @@ AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const s mapPtr = &device.MappingTokenIDPairMap_; } else { AccessTokenRemoteDevice device; + device.DeviceID_ = deviceID; remoteDeviceMap_[deviceID] = device; mapPtr = &remoteDeviceMap_[deviceID].MappingTokenIDPairMap_; } diff --git a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp index bb2ab3d95..d8e846ea3 100644 --- a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp @@ -209,6 +209,11 @@ HapTokenInfo HapTokenInfoInner::GetHapInfoBasic() const return tokenInfoBasic_; } +void HapTokenInfoInner::SetTokenBaseInfo(const HapTokenInfo& baseInfo) +{ + tokenInfoBasic_ = baseInfo; +} + void HapTokenInfoInner::SetPermissionPolicySet(std::shared_ptr& policySet) { permPolicySet_ = policySet; diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp index 0e5f70d85..58d0ed35d 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -37,7 +37,7 @@ NativeTokenInfoInner::NativeTokenInfoInner() : isRemote_(false) tokenInfoBasic_.apl = APL_NORMAL; } -NativeTokenInfoInner::NativeTokenInfoInner(NativeTokenInfo& native) +NativeTokenInfoInner::NativeTokenInfoInner(NativeTokenInfo& native) : isRemote_(false) { tokenInfoBasic_ = native; } @@ -190,7 +190,7 @@ void NativeTokenInfoInner::ToString(std::string& info) const info.append(R"(, "processName": ")" + tokenInfoBasic_.processName + R"(")"); info.append(R"(, "apl": )" + std::to_string(tokenInfoBasic_.apl)); info.append(R"(, "dcap": ")" + DcapToString(tokenInfoBasic_.dcap) + R"(")"); - info.append(R"(, "isRemote": )" + std::to_string(isRemote_)); + info.append(R"(, "isRemote": )" + std::to_string(isRemote_? 1 : 0)); info.append("}"); } } // namespace AccessToken diff --git a/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/services/tokensyncmanager/src/remote/remote_command_executor.cpp index e6200b465..553decea9 100644 --- a/services/tokensyncmanager/src/remote/remote_command_executor.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -263,6 +263,10 @@ int RemoteCommandExecutor::ExecuteRemoteCommand( "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.", targetNodeId_.c_str(), uniqueId.c_str()); + // if command send failed, also try to close session + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } return Constant::FAILURE; } diff --git a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp index 6262abace..33e22c8a4 100644 --- a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp +++ b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp @@ -100,7 +100,6 @@ void SoftBusManager::Initialize() // REASON_EXIST if ((ret != Constant::SUCCESS) && (ret != REASON_EXIST)) { ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: CreateSessionServer error, result: %{public}d", ret); - std::this_thread::sleep_for(sleepTime); continue; } diff --git a/services/tokensyncmanager/test/mock/include/mock_parameter.h b/services/tokensyncmanager/test/mock/include/mock_parameter.h new file mode 100644 index 000000000..969e19745 --- /dev/null +++ b/services/tokensyncmanager/test/mock/include/mock_parameter.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef STARTUP_SYSPARAM_PARAMETER_API_H +#define STARTUP_SYSPARAM_PARAMETER_API_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int GetDevUdid(char *udid, int size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_SYSPARAM_PARAMETER_API_H diff --git a/services/tokensyncmanager/test/mock/include/session.h b/services/tokensyncmanager/test/mock/include/session.h new file mode 100644 index 000000000..a0b9d5d04 --- /dev/null +++ b/services/tokensyncmanager/test/mock/include/session.h @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup Softbus + * @{ + * + * @brief Provides high-speed, secure communication between devices. + * + * This module implements unified distributed communication capability management between + * nearby devices, and provides link-independent device discovery and transmission interfaces + * to support service publishing and data transmission. + * + * @since 1.0 + * @version 1.0 + */ + +/** + * @file session.h + * + * @brief Declares unified data transmission interfaces. + * + * This file provides data transmission capabilities, including creating and removing a session server, + * opening and closing sessions, receiving data, and querying basic session information. \n + * After multiple nearby devices are discovered and networked, these interfaces can be used to + * transmit data across devices. \n + * + * @since 1.0 + * @version 1.0 + */ +#ifndef SESSION_H +#define SESSION_H + +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +/** + * @brief bussiness type of session + * + * @since 1.0 + * @version 1.0 + */ +typedef enum { + TYPE_MESSAGE = 1, + TYPE_BYTES, + TYPE_FILE, + TYPE_STREAM, + TYPE_BUTT, +} SessionType; + +typedef enum { + INVALID = -1, + /* + * Send any segment of a frame each time. + */ + RAW_STREAM, + /* + * Send a whole video frame each time. + */ + COMMON_VIDEO_STREAM, + /* + * Send a whole audio frame each time. + */ + COMMON_AUDIO_STREAM, + /* + * Slice frame mode. + */ + VIDEO_SLICE_STREAM, +} StreamType; + +typedef enum { + LINK_TYPE_WIFI_WLAN_5G = 1, + LINK_TYPE_WIFI_WLAN_2G = 2, + LINK_TYPE_WIFI_P2P = 3, + LINK_TYPE_BR = 4, + LINK_TYPE_MAX = 4, +} LinkType; + +/** + * @brief session attribute. + * + * control the attribute of session。 + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** @brief dataType{@link SessionType} */ + int dataType; + int linkTypeNum; + LinkType linkType[LINK_TYPE_MAX]; + union { + struct StreamAttr { + int streamType; + } streamAttr; + } attr; +} SessionAttribute; + +typedef struct { + char *buf; + int bufLen; +} StreamData; + +typedef struct { + int type; + int64_t value; +} TV; + +typedef struct { + int frameType; + int64_t timeStamp; + int seqNum; + int seqSubNum; + int level; + int bitMap; + int tvCount; + TV *tvList; +} FrameInfo; + +/** + * @brief Defines session callbacks. + * + * When a session is opened or closed, or there is data to process, the related callback is invoked. + * + * @since 1.0 + * @version 1.0 + */ +typedef struct { + /** + * @brief Called when a session is opened. + * + * This function can be used to verify the session or initialize resources related to the session. + * + * @param sessionId Indicates the session ID. + * @param result 0 if the session is opened successfully, returns an error code otherwise. + * @return Returns 0 if the session connection is accepted; returns a non-zero value + * otherwise (you do not need to call {@link CloseSession} to close the session). + * @since 1.0 + * @version 1.0 + */ + int (*OnSessionOpened)(int sessionId, int result); + + /** + * @brief Called when a session is closed. + * + * This function can be used to release resources related to the session. + * You do not need to call {@link CloseSession}. + * + * @param sessionId Indicates the session ID. + * @since 1.0 + * @version 1.0 + */ + void (*OnSessionClosed)(int sessionId); + + /** + * @brief Called when data is received. + * + * This function is used to notify that data is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data received. + * @param dataLen Indicates the length of the data received. + * @since 1.0 + * @version 1.0 + */ + void (*OnBytesReceived)(int sessionId, const void *data, unsigned int dataLen); + + /** + * @brief Called when message is received. + * + * This function is used to notify that message is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data received. + * @param dataLen Indicates the length of the message received. + * @since 1.0 + * @version 1.0 + */ + void (*OnMessageReceived)(int sessionId, const void *data, unsigned int dataLen); + + void (*OnStreamReceived)(int sessionId, const StreamData *data, const StreamData *ext, const FrameInfo *param); +} ISessionListener; + +typedef struct { + int (*OnReceiveFileStarted)(int sessionId, const char *files, int fileCnt); + int (*OnReceiveFileProcess)(int sessionId, const char *firstFile, uint64_t bytesUpload, uint64_t bytesTotal); + void (*OnReceiveFileFinished)(int sessionId, const char *files, int fileCnt); + void (*OnFileTransError)(int sessionId); +} IFileReceiveListener; + +typedef struct { + int (*OnSendFileProcess)(int sessionId, uint64_t bytesUpload, uint64_t bytesTotal); + int (*OnSendFileFinished)(int sessionId, const char *firstFile); + void (*OnFileTransError)(int sessionId); +} IFileSendListener; + +/** + * @brief Creates a session server based on a package name and session name. + * + * A maximum of 18 session servers can be created. + * + * @param pkgName Indicates the pointer to the package name, which can be used to check whether the + * session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name, which is the unique ID of the session server. + * The value cannot be empty and can contain a maximum of 64 characters. + * @param listener Indicates the pointer to the session callback structure, which cannot be empty. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @see RemoveSessionServer + * @since 1.0 + * @version 1.0 + */ +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener); + +/** + * @brief Removes a session server based on a package name and session name. + * + * @param pkgName Indicates the pointer to the name of the registered package, which can be used to check + * whether the session server is in this package. The value cannot be empty and can contain a maximum of 64 characters. + * @param sessionName Indicates the pointer to the session name. The value cannot be empty and can contain + * a maximum of 64 characters. + * @return Returns 0 if the operation is successful, returns -1 otherwise. + * @see CreateSessionServer + * @since 1.0 + * @version 1.0 + */ +int RemoveSessionServer(const char *pkgName, const char *sessionName); + +/** + * @brief Initiate a session open request, which is an asynchronous process. + * + * The session connection is opened based on the service name to trigger the first packet interaction process. + * According to the {@link OnSessionOpened} Notify the user whether the session is successfully opened. + * Data can be transmitted only after the session is successfully opened. + * + * @param mySessionName local session name. + * @param peerSessionName remote session name. + * @param peerDeviceId remote device id. + * @param groupId group id. + * @param attr session attribute {@link SessionAttribute}. + * @return return sessionId if the session is opened successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, + const SessionAttribute *attr); + +/** + * @brief Closes a connected session based on a session ID. + * + * @param sessionId Indicates the session ID. + * @return no return value. + * @since 1.0 + * @version 1.0 + */ +void CloseSession(int sessionId); + +/** + * @brief Sends data based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data to send, which cannot be NULL. + * @param len Indicates the length of the data to send. The maximum length cannot exceed 984 characters. + * @return Returns 0 if the function is called successfully; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendBytes(int sessionId, const void *data, unsigned int len); + +/** + * @brief Sends message based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data to send, which cannot be NULL. + * @param len Indicates the length of the message to send. + * @return Returns 0 if the function is called successfully, returns an error code otherwise. + * @since 1.0 + * @version 1.0 + */ +int SendMessage(int sessionId, const void *data, unsigned int len); + +int SendStream(int sessionId, const StreamData *data, const StreamData *ext, const FrameInfo *param); + +/** + * @brief Obtains the session name registered by the local device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetMySessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the session name registered by the peer device based on the session ID. + * + * @param sessionId Indicates the session ID. + * @param sessionName Indicates the pointer to the buffer for storing the session name. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len); + +/** + * @brief Obtains the peer device ID based on a session ID. + * + * @param sessionId Indicates the session ID. + * @param devId Indicates the pointer to the buffer for storing the device ID. + * @param len Indicates the length of the buffer. + * @return Returns 0 if the operation is successful; returns -1 otherwise. + * @since 1.0 + * @version 1.0 + */ +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len); + +int GetSessionSide(int sessionId); + +int SetFileReceiveListener(const char *pkgName, const char *sessionName, const IFileReceiveListener *recvListener, + const char *rootDir); + +int SetFileSendListener(const char *pkgName, const char *sessionName, const IFileSendListener *sendListener); + +int SendFile(int sessionId, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); + +void DecompressMock(const unsigned char *bytes, const int length); + + +#ifdef __cplusplus +} + +void CompressMock(const std::string &json, const unsigned char *compressedBytes, int &compressedLength); +std::string GetUuidMock(); +bool GetSendMessFlagMock(); +void ResetSendMessFlagMock(); + +#endif +#endif // SESSION_H diff --git a/services/tokensyncmanager/test/mock/src/constant_mock.cpp b/services/tokensyncmanager/test/mock/src/constant_mock.cpp new file mode 100644 index 000000000..3995ac79a --- /dev/null +++ b/services/tokensyncmanager/test/mock/src/constant_mock.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "constant.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; +const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; + +std::string Constant::EncryptDevId(std::string deviceId) +{ + std::string result = deviceId; + if (deviceId.size() >= ENCRYPTLEN) { + result.replace(ENCRYPTBEGIN, ENCRYPTEND, "****"); + } else { + result.replace(ENCRYPTBEGIN, result.size() - 1, "****"); + } + return result; +} + +std::string Constant::GetLocalDeviceId() +{ + return "local:udid-001"; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/test/mock/src/mock_parameter.c b/services/tokensyncmanager/test/mock/src/mock_parameter.c new file mode 100644 index 000000000..98483045a --- /dev/null +++ b/services/tokensyncmanager/test/mock/src/mock_parameter.c @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mock_parameter.h" +#include + +int GetDevUdid(char *udid, int size) +{ + if (strcpy_s(udid, size, "ohos.deviceId.test") != EOK) { + return 1; + } else { + return 0; + } +} diff --git a/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp new file mode 100644 index 000000000..42045285b --- /dev/null +++ b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "constant.h" +#include "accesstoken_log.h" +#include "softbus_bus_center.h" + +using namespace OHOS::Security::AccessToken; +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusCenterMock"}; +static const int REG_COUNT_LIMIT = 10; +} // namespace +static int regCount_ = -1; +static INodeStateCb *callback_ = nullptr; + +bool IsRegCountOK() +{ + return regCount_ >= 0 && regCount_ < REG_COUNT_LIMIT; +} + +int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback) +{ + regCount_++; + // reg:0-9 + if (IsRegCountOK()) { + callback_ = const_cast(callback); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, pkg:%{public}s, count: %{public}d", pkgName, regCount_); + return Constant::SUCCESS; + } + + // count 10 above alway return failure for retry. + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); + return Constant::FAILURE; +} + +int32_t UnregNodeDeviceStateCb(INodeStateCb *callback) +{ + // unreg: 0-9 + if (IsRegCountOK()) { + regCount_--; + callback_ = nullptr; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d", regCount_); + return Constant::SUCCESS; + } + + if (regCount_ >= 0) { + regCount_--; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); + return Constant::SUCCESS; +} + +int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) +{ + strcpy_s(info->deviceName, sizeof(info->deviceName), "local"); + strcpy_s(info->networkId, sizeof(info->networkId), "local"); + info->deviceTypeId = 1; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d", regCount_); + return Constant::SUCCESS; +} + +int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, NodeDeviceInfoKey key, uint8_t *info, + int32_t infoLen) +{ + if (networkId == nullptr || networkId[0] == '\0') { + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, invalid networkId, pkg name: %{public}s", pkgName); + return Constant::FAILURE; + } + + if (key == NodeDeviceInfoKey::NODE_KEY_UDID) { + std::string temp = networkId; + temp += ":udid-001"; + strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + infoLen = temp.length(); + } + if (key == NodeDeviceInfoKey::NODE_KEY_UUID) { + std::string temp = networkId; + temp += ":uuid-001"; + strncpy_s((char *) info, infoLen, temp.c_str(), temp.length()); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d, id: %{public}s", regCount_, info); + return Constant::SUCCESS; +} diff --git a/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp b/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp new file mode 100644 index 000000000..a79a402bf --- /dev/null +++ b/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "session.h" +#include "constant.h" +#include "soft_bus_manager.h" +#include "accesstoken_log.h" +#include "soft_bus_session_listener.h" +#include "soft_bus_channel.h" + +using namespace OHOS::Security::AccessToken; +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusSenssionMock"}; +static const int SESSION_COUNT_LIMIT = 20; +static const int SERVER_COUNT_LIMIT = 10; +} // namespace + +#define MIN_(x, y) ((x) < (y)) ? (x) : (y) + +static int serverCount_ = -1; +bool IsServerCountOK() +{ + return serverCount_ >= 0 && serverCount_ < SERVER_COUNT_LIMIT; +} + +static ISessionListener *listener_ = nullptr; +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "pkg name: %{public}s", pkgName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionName: %{public}s", sessionName); + serverCount_++; + if (IsServerCountOK()) { + listener_ = const_cast(listener); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, server count: %{public}d", serverCount_); + return Constant::SUCCESS; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, server count: %{public}d", serverCount_); + return Constant::FAILURE; +} +int RemoveSessionServer(const char *pkgName, const char *sessionName) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "pkg name: %{public}s", pkgName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionName: %{public}s", sessionName); + if (IsServerCountOK()) { + serverCount_--; + listener_ = nullptr; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, server count: %{public}d", serverCount_); + return Constant::SUCCESS; + } + + if (serverCount_ >= 0) { + serverCount_--; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, server count: %{public}d", serverCount_); + return Constant::FAILURE; +} + +static int sessionCount_ = -1; +bool IsSessionCountOK() +{ + return sessionCount_ >= 0 && sessionCount_ < SESSION_COUNT_LIMIT; + ACCESSTOKEN_LOG_DEBUG(LABEL, "SESSION_COUNT_LIMIT: %{public}d", SESSION_COUNT_LIMIT); +} + +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, + const SessionAttribute *attr) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "mySessionName: %{public}s", mySessionName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "peerSessionName: %{public}s", peerSessionName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "peerDeviceId: %{public}s", peerDeviceId); + ACCESSTOKEN_LOG_DEBUG(LABEL, "groupId: %{public}s", groupId); + + sessionCount_++; + SoftBusSessionListener::OnSessionOpened(1, Constant::SUCCESS); + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session count: %{public}d", sessionCount_); + return 1; +} +void CloseSession(int sessionId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "sessionId: %{public}d", sessionId); + if (sessionCount_ >= 0) { + sessionCount_--; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session count: %{public}d", sessionCount_); + } +} + +static bool g_sendMessFlag = false; +int SendBytes(int sessionId, const void *data, unsigned int len) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "len: %{public}d", len); + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + DecompressMock((unsigned char *) data, len); + g_sendMessFlag = true; + return Constant::SUCCESS; +} + +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len) +{ + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + std::string x; + if (sessionId < SERVER_COUNT_LIMIT) { + x = SoftBusManager::SESSION_NAME; + } else { + x = "sessionid-" + std::to_string(sessionId); + } + if (len < x.length()) { + return Constant::FAILURE; + } + if (memcpy_s(sessionName, x.length(), x.c_str(), x.length()) != EOK) { + return Constant::FAILURE; + } + sessionName[x.length()] = '\0'; + ACCESSTOKEN_LOG_DEBUG(LABEL, "success, session name: %{public}s", sessionName); + + return 0; +} + +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len) +{ + if (sessionId == Constant::INVALID_SESSION) { + return Constant::FAILURE; + } + + std::string x = "deviceid-" + std::to_string(sessionId); + if (len < x.length()) { + return Constant::FAILURE; + } + + if (memcpy_s(devId, x.length(), x.c_str(), x.length()) != EOK) { + return Constant::FAILURE; + } + devId[x.length()] = '\0'; + return 0; +} + +static std::string uuid = ""; +void DecompressMock(const unsigned char *bytes, const int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "input length: %{public}d", length); + uLong len = 1048576; + unsigned char *buf = (unsigned char *) malloc(len + 1); + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory!"); + return; + } + memset_s(buf, len + 1, 0, len + 1); + int result = uncompress(buf, &len, (unsigned char *) bytes, length); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "uncompress failed, error code: %{public}d, bound length: %{public}d, buffer length: %{public}d", result, + (int) len, length); + free(buf); + return; + } + buf[len] = '\0'; + std::string str((char *) buf); + free(buf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "done, output: %{public}s", str.c_str()); + + int id_post = str.find("\"id\":"); + + std::string id_string = str.substr(id_post + 6, 9); + uuid = id_string; + ACCESSTOKEN_LOG_DEBUG(LABEL, "id_string: %{public}s", id_string.c_str()); + return; +} + + +void CompressMock(const std::string &json, const unsigned char *compressedBytes, int &compressedLength) +{ + uLong len = compressBound(json.size()); + // length will not so that long + if (compressedLength > 0 && (int) len > compressedLength) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "compress error. data length overflow, bound length: %{public}d, buffer length: %{public}d", (int) len, + compressedLength); + return ; + } + + int result = compress((Byte *) compressedBytes, &len, (unsigned char *) json.c_str(), json.size() + 1); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "compress failed! error code: %{public}d", result); + return; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "compress complete. compress %{public}d bytes to %{public}d", compressedLength, + (int) len); + compressedLength = len; + return ; +} + +std::string GetUuidMock() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetUuidMock called uuid: %{public}s", uuid.c_str()); + return uuid; +} + + +bool GetSendMessFlagMock() +{ + return g_sendMessFlag; +} + +void ResetSendMessFlagMock() +{ + g_sendMessFlag = false; +} diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn new file mode 100644 index 000000000..73cb6e221 --- /dev/null +++ b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn @@ -0,0 +1,100 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libtoken_sync_service_sdk_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + sources = [ + #"//base/security/access_token/services/tokensyncmanager/src/common/constant.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/base_remote_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/delete_remote_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp", + "//base/security/access_token/services/tokensyncmanager/src/device/device_info_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/device/device_info_repository.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_executor.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_factory.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/remote_command_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_channel.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_manager.cpp", + "//base/security/access_token/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_event_handler.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_manager_service.cpp", + "//base/security/access_token/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/constant_mock.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp", + "//base/security/access_token/services/tokensyncmanager/test/mock/src/soft_bus_session_mock.cpp", + + #"//base/security/access_token/services/tokensyncmanager/test/mock/src/mock_parameter.c", + "//base/security/access_token/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp", + ] + + include_dirs = [ + "//utils/native/base/include", + "//third_party/googletest/include", + "//base/security/access_token/services/tokensyncmanager/include/service", + "//base/security/access_token/services/tokensyncmanager/include/remote", + "//base/security/access_token/services/tokensyncmanager/include/command", + "//base/security/access_token/services/tokensyncmanager/include/common", + "//base/security/access_token/services/tokensyncmanager/include/device", + "//base/security/access_token/services/tokensyncmanager/include/protocol", + "//base/security/access_token/services/tokensyncmanager/test/mock/include", + "//third_party/json/include", + "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/frameworks/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/nativetoken/include", + "//base/security/access_token/frameworks/common/include", + "//foundation/communication/dsoftbus/interfaces/kits/transport", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + + #"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + ] + + deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//third_party/zlib:libz", + "//utils/native/base:utils", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libtoken_sync_service_sdk_test" ] +} diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp new file mode 100644 index 000000000..f27049517 --- /dev/null +++ b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.cpp @@ -0,0 +1,606 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "token_sync_service_test.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "gtest/gtest.h" +#include "session.h" +#include "soft_bus_device_connection_listener.h" +#include "soft_bus_session_listener.h" + +#define private public +#include "token_sync_manager_service.h" +#undef private + +using namespace std; +using namespace OHOS::Security::AccessToken; +using namespace testing::ext; +static std::vector threads_; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKitTest"}; +} + +TokenSyncServiceTest::TokenSyncServiceTest() +{ + DelayedSingleton::GetInstance()->Initialize(); +} +TokenSyncServiceTest::~TokenSyncServiceTest() +{} +void TokenSyncServiceTest::SetUpTestCase() +{} +void TokenSyncServiceTest::TearDownTestCase() +{} +void TokenSyncServiceTest::SetUp() +{ +} +void TokenSyncServiceTest::TearDown() +{ + for (auto it = threads_.begin(); it != threads_.end(); it++) { + it->join(); + } + threads_.clear(); +} + +namespace { + std::string g_jsonBefore; + std::string g_jsonAfter; +} + +void SendTaskThread() +{ + while (!GetSendMessFlagMock()) { + sleep(1); + } + + ResetSendMessFlagMock(); + + std::string uuidMessage = GetUuidMock(); + std::string sendJson = g_jsonBefore + uuidMessage + g_jsonAfter; + + unsigned char *sendBuffer = (unsigned char *)malloc(0x1000); + if (sendBuffer == nullptr) { + return; + } + int sendLen = 0x1000; + CompressMock(sendJson, sendBuffer, sendLen); + + SoftBusSessionListener::OnBytesReceived(1, sendBuffer, sendLen); +} + +/** + * @tc.name: GetRemoteHapTokenInfo001 + * @tc.desc: test remote hap send func + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo001 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0,\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + int ret = OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + ASSERT_EQ(ret, RET_SUCCESS); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_NE(mapID, (AccessTokenID)0); + + HapTokenInfo tokeInfo; + ret = AccessTokenKit::GetHapTokenInfo(mapID, tokeInfo); + ASSERT_EQ(ret, RET_SUCCESS); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +static PermissionDef g_infoManagerTestPermDef1 = { + .permissionName = "ohos.permission.test1", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +static PermissionDef g_infoManagerTestPermDef2 = { + .permissionName = "ohos.permission.test2", + .bundleName = "accesstoken_test", + .grantMode = 1, + .label = "label", + .labelId = 1, + .description = "break the door", + .descriptionId = 1, + .availableLevel = APL_NORMAL +}; + +static PermissionStateFull g_infoManagerTestState1 = { + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .permissionName = "ohos.permission.test1", + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestState2 = { + .permissionName = "ohos.permission.test2", + .isGeneral = false, + .grantFlags = {1, 2}, + .grantStatus = {PermissionState::PERMISSION_GRANTED, PermissionState::PERMISSION_GRANTED}, + .resDeviceID = {"device 1", "device 2"} +}; + +static HapInfoParams g_infoManagerTestInfoParms = { + .bundleName = "accesstoken_test", + .userID = 1, + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +static HapPolicyParams g_infoManagerTestPolicyPrams = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, + .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} +}; + +/** + * @tc.name: GetRemoteHapTokenInfo002 + * @tc.desc: test remote hap recv func + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo002, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo002 start."); + // create local token + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + ASSERT_NE(0, tokenIdEx.tokenIdExStruct.tokenID); + + // create recv message + std::string jsonBefore = + "{\"commandName\":\"SyncRemoteHapTokenCommand\",\"id\":\"0065e65f-\",\"jsonPayload\":" + "\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":\\\"\\\",\\\"bundleName\\\":\\\"\\\"," + "\\\"deviceID\\\":\\\"\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":0,\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"local:udid-001\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":"; + std::string tokenJsonStr = std::to_string(tokenIdEx.tokenIdExStruct.tokenID); + std::string jsonAfter = ",\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"\\\",\\\"responseVersion\\\":2," + "\\\"srcDeviceId\\\":\\\"deviceid-1\\\",\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":100001," + "\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"request\"}"; + + std::string recvJson = jsonBefore + tokenJsonStr + jsonAfter; + + unsigned char *recvBuffer = (unsigned char *)malloc(0x1000); + int recvLen = 0x1000; + CompressMock(recvJson, recvBuffer, recvLen); + + // device online + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + SoftBusSessionListener::OnBytesReceived(1, recvBuffer, recvLen); + + int count = 0; + while (!GetSendMessFlagMock() && count < 10) { + sleep(1); + count ++; + } + + ResetSendMessFlagMock(); + std::string uuidMessage = GetUuidMock(); + ASSERT_EQ(uuidMessage, "0065e65f-"); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo003 + * @tc.desc: test remote hap send func, but get tokenInfo is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo003, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo003 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // apl is error + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":11,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0,\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo004 + * @tc.desc: test remote hap send func, but json payload lost parameter + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo004, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo004 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // lost tokenID + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo005 + * @tc.desc: test remote hap send func, but json payload parameter type is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo005, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo005 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // instIndex is not number + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":\\\"aaa\\\"," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo006 + * @tc.desc: test remote hap send func, but json payload parameter format is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo006, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo006 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // mock_token_sync lost \\\" + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync,\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo007 + * @tc.desc: test remote hap send func, statusCode is wrong + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo007, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo007 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteHapTokenCommand\", \"id\":\""; + // statusCode error + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":11,\\\"appID\\\":" + "\\\"test\\\",\\\"bundleName\\\":\\\"mock_token_sync\\\",\\\"deviceID\\\":" + "\\\"111111\\\",\\\"instIndex\\\":1,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":537919488," + "\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":537919488,\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"" + ",\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\",\\\"srcDeviceLevel\\\":\\\"\\\"," + "\\\"statusCode\\\":-2,\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + OHOS::DelayedSingleton::GetInstance()->GetRemoteHapTokenInfo( + networkID, 0x20100000); + + AccessTokenID mapID = AccessTokenKit::AllocLocalTokenID(networkID, 0x20100000); + ASSERT_EQ(mapID, (AccessTokenID)0); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: GetRemoteHapTokenInfo008 + * @tc.desc: test remote hap recv func, tokenID is not exist + * @tc.type: FUNC + * @tc.require:AR000GK6T5 + */ +HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo008, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetRemoteHapTokenInfo008 start."); + // create local token + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + AccessTokenKit::DeleteToken(tokenID); + + // tokenID is not exist + std::string jsonBefore = + "{\"commandName\":\"SyncRemoteHapTokenCommand\",\"id\":\"0065e65f-\",\"jsonPayload\":" + "\"{\\\"HapTokenInfo\\\":{\\\"apl\\\":1,\\\"appID\\\":\\\"\\\",\\\"bundleName\\\":\\\"\\\"," + "\\\"deviceID\\\":\\\"\\\",\\\"instIndex\\\":0,\\\"permState\\\":null,\\\"tokenAttr\\\":0," + "\\\"tokenID\\\":0,\\\"userID\\\":0,\\\"version\\\":1},\\\"commandName\\\":\\\"SyncRemoteHapTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"local:udid-001\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestTokenId\\\":"; + std::string tokenJsonStr = std::to_string(tokenID); + std::string jsonAfter = ",\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"\\\",\\\"responseVersion\\\":2," + "\\\"srcDeviceId\\\":\\\"deviceid-1\\\",\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":100001," + "\\\"uniqueId\\\":\\\"SyncRemoteHapTokenCommand\\\"}\",\"type\":\"request\"}"; + + // create recv message + std::string recvJson = jsonBefore + tokenJsonStr + jsonAfter; + unsigned char *recvBuffer = (unsigned char *)malloc(0x1000); + int recvLen = 0x1000; + CompressMock(recvJson, recvBuffer, recvLen); + + // device online + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + SoftBusSessionListener::OnBytesReceived(1, recvBuffer, recvLen); + + int count = 0; + while (!GetSendMessFlagMock() && count < 10) { + sleep(1); + count ++; + } + + ResetSendMessFlagMock(); + std::string uuidMessage = GetUuidMock(); + ASSERT_EQ(uuidMessage, "0065e65f-"); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} + +/** + * @tc.name: SyncNativeTokens001 + * @tc.desc: when device is online, sync remote nativetokens which has dcap + * @tc.type: FUNC + * @tc.require:AR000GK6T6 + */ +HWTEST_F(TokenSyncServiceTest, SyncNativeTokens001, TestSize.Level1) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "SyncNativeTokens001 start."); + g_jsonBefore = "{\"commandName\":\"SyncRemoteNativeTokenCommand\", \"id\":\""; + g_jsonAfter = + "\",\"jsonPayload\":\"{\\\"NativeTokenInfos\\\":[{\\\"apl\\\":3,\\\"processName\\\":\\\"attest\\\"," + "\\\"tokenAttr\\\":0,\\\"tokenId\\\":671836008,\\\"version\\\":1," + "\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}," + "{\\\"APL\\\":3,\\\"processName\\\":\\\"attest1\\\",\\\"tokenAttr\\\":0,\\\"tokenId\\\":671836018," + "\\\"version\\\":1,\\\"dcaps\\\":[\\\"SYSDCAP\\\",\\\"DMSDCAP\\\"]}]," + "\\\"commandName\\\":\\\"SyncRemoteNativeTokenCommand\\\"," + "\\\"dstDeviceId\\\":\\\"deviceid-1\\\",\\\"dstDeviceLevel\\\":\\\"\\\",\\\"message\\\":\\\"success\\\"," + "\\\"requestVersion\\\":2,\\\"responseDeviceId\\\":\\\"deviceid-1:udid-001\\\"," + "\\\"responseVersion\\\":2,\\\"srcDeviceId\\\":\\\"local:udid-001\\\"," + "\\\"srcDeviceLevel\\\":\\\"\\\",\\\"statusCode\\\":0,\\\"uniqueId\\\":\\\"SyncRemoteNativeTokenCommand\\\"}\"," + "\"type\":\"response\"}"; + + threads_.emplace_back(std::thread(SendTaskThread)); + + std::string networkID = "deviceid-1"; + std::string deviceName = "remote_mock"; + // udid = deviceid-1:udid-001 uuid = deviceid-1:uuid-001 + DmDeviceInfo devInfo; + strcpy(devInfo.deviceId, networkID.c_str()); + strcpy(devInfo.deviceName, deviceName.c_str()); + devInfo.deviceTypeId = 1; + + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + + ptrDeviceStateCallback->OnDeviceOnline(devInfo); + + sleep(6); + + AccessTokenID mapID = AccessTokenKit::GetRemoteNativeTokenID(networkID, 0x280b6768); + ASSERT_NE(mapID, (AccessTokenID)0); + int ret = AccessTokenKit::CheckNativeDCap(mapID, "SYSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenKit::CheckNativeDCap(mapID, "DMSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + + mapID = AccessTokenKit::GetRemoteNativeTokenID(networkID, 0x280b6772); + ASSERT_NE(mapID, (AccessTokenID)0); + ret = AccessTokenKit::CheckNativeDCap(mapID, "SYSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + ret = AccessTokenKit::CheckNativeDCap(mapID, "DMSDCAP"); + ASSERT_EQ(ret, RET_SUCCESS); + + ptrDeviceStateCallback->OnDeviceOffline(devInfo); +} diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h new file mode 100644 index 000000000..06e60116d --- /dev/null +++ b/services/tokensyncmanager/test/unittest/token_sync_service/token_sync_service_test.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TOKEN_SYNC_SERVICE_TEST_H +#define TOKEN_SYNC_SERVICE_TEST_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncServiceTest : public testing::Test { +public: + TokenSyncServiceTest(); + ~TokenSyncServiceTest(); + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_SERVICE_TEST_H \ No newline at end of file -- Gitee