From 7adcbad8409288a6078b5822e80eda53fdf81f36 Mon Sep 17 00:00:00 2001 From: wangpggg Date: Wed, 4 Jun 2025 23:00:52 +0800 Subject: [PATCH] acl check Signed-off-by: wangpeng --- bundle.json | 3 + common/include/dscreen_errcode.h | 2 + .../test/unittest/resource/cfi_blocklist.txt | 14 +- distributedscreen.gni | 8 + .../screentransport/screensinktrans/BUILD.gn | 8 + .../screensourcetrans/BUILD.gn | 8 + .../softbusadapter/include/softbus_adapter.h | 4 +- .../include/softbus_permission_check.h | 53 +++ .../softbusadapter/src/softbus_adapter.cpp | 48 +- .../src/softbus_permission_check.cpp | 274 ++++++++++++ .../softbusadapter/test/unittest/BUILD.gn | 75 +++- .../include/device_manager_impl_mock.h | 75 ++++ .../test/unittest/include/mock_other_method.h | 42 ++ .../test/unittest/include/socket_mock.h | 48 ++ .../unittest/src/device_manager_impl_mock.cpp | 113 +++++ .../test/unittest/src/mock_other_method.cpp | 100 +++++ .../test/unittest/src/socket_mock.cpp | 48 ++ .../unittest/src/softbus_adapter_test.cpp | 95 +++- .../src/softbus_permission_check_test.cpp | 418 ++++++++++++++++++ 19 files changed, 1421 insertions(+), 15 deletions(-) create mode 100644 services/softbusadapter/include/softbus_permission_check.h create mode 100644 services/softbusadapter/src/softbus_permission_check.cpp create mode 100644 services/softbusadapter/test/unittest/include/device_manager_impl_mock.h create mode 100644 services/softbusadapter/test/unittest/include/mock_other_method.h create mode 100644 services/softbusadapter/test/unittest/include/socket_mock.h create mode 100644 services/softbusadapter/test/unittest/src/device_manager_impl_mock.cpp create mode 100644 services/softbusadapter/test/unittest/src/mock_other_method.cpp create mode 100644 services/softbusadapter/test/unittest/src/socket_mock.cpp create mode 100644 services/softbusadapter/test/unittest/src/softbus_permission_check_test.cpp diff --git a/bundle.json b/bundle.json index 3821efb8..4d2c75d7 100644 --- a/bundle.json +++ b/bundle.json @@ -29,6 +29,7 @@ "access_token", "accessibility", "av_codec", + "device_manager", "dsoftbus", "eventhandler", "hisysevent", @@ -41,6 +42,7 @@ "graphic_2d", "graphic_surface", "media_foundation", + "os_account", "samgr", "safwk", "selinux_adapter", @@ -101,6 +103,7 @@ "//foundation/distributedhardware/distributed_screen/services/screentransport/test/fuzztest:fuzztest", "//foundation/distributedhardware/distributed_screen/services/screentransport/test/unittest:screen_transport_test", "//foundation/distributedhardware/distributed_screen/services/softbusadapter/test/unittest:SoftBusAdapterTest", + "//foundation/distributedhardware/distributed_screen/services/softbusadapter/test/unittest:SoftbusPermissionCheckTest", "//foundation/distributedhardware/distributed_screen/services/common/test/unittest:service_common_test", "//foundation/distributedhardware/distributed_screen/interfaces/innerkits/native_cpp/test/unittest:screen_interface_test", "//foundation/distributedhardware/distributed_screen/services/screenclient/test/unittest:ScreenClientTest", diff --git a/common/include/dscreen_errcode.h b/common/include/dscreen_errcode.h index f2de0565..68a52a8b 100644 --- a/common/include/dscreen_errcode.h +++ b/common/include/dscreen_errcode.h @@ -84,6 +84,8 @@ enum DScreenErrorCode { ERR_DH_SCREEN_ADAPTER_BAD_VALUE = -52004, ERR_DH_SCREEN_ADAPTER_OPEN_SESSION_FAIL = -52005, ERR_DH_SCREEN_ADAPTER_PARA_ERROR = -52006, + ERR_DH_SCREEN_ADAPTER_PERMISSION_DENIED = -52007, + ERR_DH_SCREEN_ADAPTER_CONTEXT = -52008, // Encoder & Decoder ERR_DH_SCREEN_CODEC_RELEASE_FAILED = -53000, ERR_DH_SCREEN_CODEC_PREPARE_FAILED = -53001, diff --git a/common/test/unittest/resource/cfi_blocklist.txt b/common/test/unittest/resource/cfi_blocklist.txt index a3b6e425..0eee4aa1 100644 --- a/common/test/unittest/resource/cfi_blocklist.txt +++ b/common/test/unittest/resource/cfi_blocklist.txt @@ -13,4 +13,16 @@ [cfi] type:*testing::UnitTest* -src:*third_party/googletest/* +type:*OHOS::Parcel* +type:*OHOS::RefBase* +type:*OHOS::MessageParcel* +type:*OHOS::IRemoteObject* +type:*OHOS::IRemoteBroker* +type:*OHOS::ISystemAbilityManager* +type:*OHOS::ThreadPool* +type:*OHOS::IPCSkeleton* +type:*OHOS::Security::AccessToken::AccessTokenKit* +type:*OHOS::AAFwk::SystemAbilityManagerClient* +type:*OHOS::SystemAbility* +src:*third_party/googletest/googlemock/include/gmock/* +src:*third_party/googletest/googletest/include/gtest/* diff --git a/distributedscreen.gni b/distributedscreen.gni index 2fe9ad80..55e1f776 100644 --- a/distributedscreen.gni +++ b/distributedscreen.gni @@ -16,3 +16,11 @@ fuzz_test_path = "distributed_screen/distributed_screen" common_path = "${distributedscreen_path}/common" services_path = "${distributedscreen_path}/services" interfaces_path = "${distributedscreen_path}/interfaces" + +declare_args() { + need_same_account = true + if (!defined(global_parts_info) || !defined( + global_parts_info.distributedhardware_distributed_hardware_adapter)) { + need_same_account = false + } +} \ No newline at end of file diff --git a/services/screentransport/screensinktrans/BUILD.gn b/services/screentransport/screensinktrans/BUILD.gn index f94472c7..dcbdbfac 100644 --- a/services/screentransport/screensinktrans/BUILD.gn +++ b/services/screentransport/screensinktrans/BUILD.gn @@ -53,6 +53,7 @@ ohos_shared_library("distributed_screen_sinktrans") { "${services_path}/screentransport/screensinkprocessor/decoder/src/image_sink_decoder.cpp", "${services_path}/screentransport/screensinkprocessor/src/image_sink_processor.cpp", "${services_path}/softbusadapter/src/softbus_adapter.cpp", + "${services_path}/softbusadapter/src/softbus_permission_check.cpp", "src/screen_sink_trans.cpp", ] @@ -64,9 +65,14 @@ ohos_shared_library("distributed_screen_sinktrans") { "LOG_DOMAIN=0xD004140", ] + if (need_same_account) { + defines += [ "SUPPORT_SAME_ACCOUNT" ] + } + external_deps = [ "av_codec:av_codec_client", "c_utils:utils", + "device_manager:devicemanagersdk", "distributed_hardware_fwk:distributed_av_receiver", "distributed_hardware_fwk:distributedhardwareutils", "distributed_hardware_fwk:libdhfwk_sdk", @@ -79,6 +85,8 @@ ohos_shared_library("distributed_screen_sinktrans") { "json:nlohmann_json_static", "libjpeg-turbo:turbojpeg", "media_foundation:media_foundation", + "os_account:libaccountkits", + "os_account:os_account_innerkits", ] cflags = [ "-fstack-protector-strong" ] diff --git a/services/screentransport/screensourcetrans/BUILD.gn b/services/screentransport/screensourcetrans/BUILD.gn index 7b7e10b8..5e85a462 100644 --- a/services/screentransport/screensourcetrans/BUILD.gn +++ b/services/screentransport/screensourcetrans/BUILD.gn @@ -52,6 +52,7 @@ ohos_shared_library("distributed_screen_sourcetrans") { "${services_path}/screentransport/screensourceprocessor/encoder/src/image_source_encoder.cpp", "${services_path}/screentransport/screensourceprocessor/src/image_source_processor.cpp", "${services_path}/softbusadapter/src/softbus_adapter.cpp", + "${services_path}/softbusadapter/src/softbus_permission_check.cpp", "src/screen_source_trans.cpp", ] @@ -63,9 +64,14 @@ ohos_shared_library("distributed_screen_sourcetrans") { "LOG_DOMAIN=0xD004140", ] + if (need_same_account) { + defines += [ "SUPPORT_SAME_ACCOUNT" ] + } + external_deps = [ "av_codec:av_codec_client", "c_utils:utils", + "device_manager:devicemanagersdk", "distributed_hardware_fwk:distributed_av_sender", "distributed_hardware_fwk:distributedhardwareutils", "distributed_hardware_fwk:libdhfwk_sdk", @@ -80,6 +86,8 @@ ohos_shared_library("distributed_screen_sourcetrans") { "json:nlohmann_json_static", "libjpeg-turbo:turbojpeg", "media_foundation:media_foundation", + "os_account:libaccountkits", + "os_account:os_account_innerkits", ] cflags = [ "-fstack-protector-strong" ] diff --git a/services/softbusadapter/include/softbus_adapter.h b/services/softbusadapter/include/softbus_adapter.h index 4780047d..c184b3d0 100644 --- a/services/softbusadapter/include/softbus_adapter.h +++ b/services/softbusadapter/include/softbus_adapter.h @@ -58,13 +58,13 @@ public: void OnStreamReceived(int32_t sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *frameInfo); void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen) const; - + bool OnNegotiate2(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, SocketAccessInfo *localInfo); private: SoftbusAdapter(); ~SoftbusAdapter(); std::shared_ptr &GetSoftbusListenerByName(int32_t sessionId); std::shared_ptr &GetSoftbusListenerById(int32_t sessionId); - + int32_t HandleAfterOpenSession(const int32_t socketId); private: static const constexpr char *DSCREEN_LOG_TAG = "SoftbusAdapter"; std::mutex listenerMtx_; diff --git a/services/softbusadapter/include/softbus_permission_check.h b/services/softbusadapter/include/softbus_permission_check.h new file mode 100644 index 00000000..8993797d --- /dev/null +++ b/services/softbusadapter/include/softbus_permission_check.h @@ -0,0 +1,53 @@ +/* + * 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_SOFTBUS_ADAPTER_SOFTBUS_PERMISSION_CHECK_H +#define OHOS_SOFTBUS_ADAPTER_SOFTBUS_PERMISSION_CHECK_H + +#include + +#include "transport/trans_type.h" + +namespace OHOS { +namespace DistributedHardware { +const int32_t INVALID_USER_ID = -1; +struct AccountInfo { + int32_t userId_ = INVALID_USER_ID; + uint64_t tokenId_ = 0; + std::string accountId_; + std::string networkId_; +}; + +class SoftBusPermissionCheck { +public: + static bool CheckSrcPermission(const std::string &sinkNetworkId); + static bool CheckSinkPermission(const AccountInfo &callerAccountInfo); + static bool GetLocalAccountInfo(AccountInfo &localAccountInfo); + static int32_t GetCurrentUserId(); + static bool TransCallerInfo(SocketAccessInfo *callerInfo, + AccountInfo &callerAccountInfo, const std::string &networkId); + static bool FillLocalInfo(SocketAccessInfo *localInfo); + static bool SetAccessInfoToSocket(const int32_t sessionId); +private: + static bool CheckSrcIsSameAccount(const std::string &sinkNetworkId, const AccountInfo &localAccountInfo); + static bool CheckSinkIsSameAccount(const AccountInfo &callerAccountInfo, const AccountInfo &calleeAccountInfo); + static bool CheckSrcAccessControl(const std::string &sinkNetworkId, const AccountInfo &localAccountInfo); + static bool CheckSinkAccessControl(const AccountInfo &callerAccountInfo, const AccountInfo &calleeAccountInfo); + static bool GetLocalNetworkId(std::string &networkId); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_SOFTBUS_ADAPTER_SOFTBUS_PERMISSION_CHECK_H \ No newline at end of file diff --git a/services/softbusadapter/src/softbus_adapter.cpp b/services/softbusadapter/src/softbus_adapter.cpp index 950e9245..c57fc013 100644 --- a/services/softbusadapter/src/softbus_adapter.cpp +++ b/services/softbusadapter/src/softbus_adapter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,6 +20,7 @@ #include "softbus_bus_center.h" #include "softbus_common.h" +#include "softbus_permission_check.h" #include "dscreen_errcode.h" #include "dscreen_hisysevent.h" @@ -54,6 +55,12 @@ static void ScreenOnMessageReceived(int sessionId, const void *data, unsigned in SoftbusAdapter::GetInstance().OnMessageReceived(sessionId, data, dataLen); } +static bool ScreenOnNegotiate2(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, + SocketAccessInfo *localInfo) +{ + return SoftbusAdapter::GetInstance().OnNegotiate2(socket, info, peerInfo, localInfo); +} + SoftbusAdapter::SoftbusAdapter() { DHLOGI("SoftbusAdapter"); @@ -66,6 +73,7 @@ SoftbusAdapter::SoftbusAdapter() sessListener_.OnQos = nullptr; sessListener_.OnError = nullptr; sessListener_.OnNegotiate = nullptr; + sessListener_.OnNegotiate2 = ScreenOnNegotiate2; } SoftbusAdapter::~SoftbusAdapter() @@ -182,6 +190,10 @@ int32_t SoftbusAdapter::OpenSoftbusSession(const std::string &mySessionName, con { DHLOGI("%{public}s: OpenSoftbusSession mysess:%{public}s peersess:%{public}s id:%{public}s.", DSCREEN_LOG_TAG, mySessionName.c_str(), peerSessionName.c_str(), GetAnonyString(peerDevId).c_str()); + if (!SoftBusPermissionCheck::CheckSrcPermission(peerDevId)) { + DHLOGE("Permission denied"); + return ERR_DH_SCREEN_ADAPTER_PERMISSION_DENIED; + } QosTV qos[] = { {.qos = QOS_TYPE_MIN_BW, .value = 40 * 1024 * 1024}, @@ -201,22 +213,33 @@ int32_t SoftbusAdapter::OpenSoftbusSession(const std::string &mySessionName, con DHLOGE("Create OpenSoftbusChannel Socket error"); return ERR_DH_SCREEN_ADAPTER_PARA_ERROR; } + if (!SoftBusPermissionCheck::SetAccessInfoToSocket(socketId)) { + DHLOGW("Fill and set accessInfo failed"); + Shutdown(socketId); + return ERR_DH_SCREEN_ADAPTER_CONTEXT; + } int32_t ret = Bind(socketId, qos, sizeof(qos) / sizeof(qos[0]), &sessListener_); if (ret != DH_SUCCESS) { DHLOGE("Bind SocketClient error"); + Shutdown(socketId); return ERR_DH_SCREEN_ADAPTER_PARA_ERROR; } { std::lock_guard lock(idMapMutex_); devId2SessIdMap_.insert(std::make_pair(socketId, mySessionName + "_" + peerDevId)); } + return HandleAfterOpenSession(socketId); +} + +int32_t SoftbusAdapter::HandleAfterOpenSession(const int32_t socketId) +{ std::shared_ptr &listener = GetSoftbusListenerByName(socketId); if (listener == nullptr) { DHLOGE("Get softbus listener failed."); return ERR_DH_SCREEN_TRANS_ERROR; } PeerSocketInfo info; - ret = OnSoftbusSessionOpened(socketId, info); + int32_t ret = OnSoftbusSessionOpened(socketId, info); if (ret != DH_SUCCESS) { return ret; } @@ -391,5 +414,26 @@ void SoftbusAdapter::OnMessageReceived(int sessionId, const void *data, unsigned (void)dataLen; DHLOGD("%{public}s OnMessageReceived, sessionId:%{public}" PRId32, DSCREEN_LOG_TAG, sessionId); } + +bool SoftbusAdapter::OnNegotiate2(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, + SocketAccessInfo *localInfo) +{ + if (peerInfo == nullptr) { + DHLOGE("peerInfo is nullptr. sink must be old version"); + return true; + } + + AccountInfo callerAccountInfo; + std::string networkId = info.networkId; + if (!SoftBusPermissionCheck::TransCallerInfo(peerInfo, callerAccountInfo, networkId)) { + DHLOGE("extraAccessInfo is nullptr."); + return false; + } + if (!SoftBusPermissionCheck::FillLocalInfo(localInfo)) { + DHLOGE("FillLocalInfo failed."); + return false; + } + return SoftBusPermissionCheck::CheckSinkPermission(callerAccountInfo); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/softbusadapter/src/softbus_permission_check.cpp b/services/softbusadapter/src/softbus_permission_check.cpp new file mode 100644 index 00000000..91d0f975 --- /dev/null +++ b/services/softbusadapter/src/softbus_permission_check.cpp @@ -0,0 +1,274 @@ +/* + * 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 "softbus_permission_check.h" + +#include "device_manager.h" +#include "dm_device_info.h" +#include "dscreen_errcode.h" +#include "dscreen_log.h" +#include "dscreen_util.h" +#include "ipc_skeleton.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" +#include "transport/socket.h" + +namespace OHOS { +namespace DistributedHardware { +constexpr const char *ACCOUNT_ID = "accountId"; +static inline const std::string SERVICE_NAME { "ohos.dhardware.dscreen" }; +using namespace DistributedHardware; +bool SoftBusPermissionCheck::CheckSrcPermission(const std::string &sinkNetworkId) +{ + DHLOGI("Begin"); + AccountInfo localAccountInfo; + if (!GetLocalAccountInfo(localAccountInfo)) { + DHLOGE("Get os account data failed"); + return false; + } +#ifdef SUPPORT_SAME_ACCOUNT + if (!CheckSrcIsSameAccount(sinkNetworkId, localAccountInfo)) { + DHLOGE("Check src same account failed"); + return false; + } +#endif + return true; +} + +bool SoftBusPermissionCheck::CheckSinkPermission(const AccountInfo &callerAccountInfo) +{ + DHLOGI("Begin"); + AccountInfo localAccountInfo; + if (!GetLocalAccountInfo(localAccountInfo)) { + DHLOGE("Get local account info failed"); + return false; + } +#ifdef SUPPORT_SAME_ACCOUNT + if (!CheckSinkIsSameAccount(callerAccountInfo, localAccountInfo)) { + DHLOGE("Check sink same account failed"); + return false; + } +#endif + return true; +} + +bool SoftBusPermissionCheck::GetLocalAccountInfo(AccountInfo &localAccountInfo) +{ + int32_t userId = GetCurrentUserId(); + if (userId == INVALID_USER_ID) { + DHLOGE("Get current userid failed"); + return false; + } + localAccountInfo.userId_ = userId; +#ifdef SUPPORT_SAME_ACCOUNT + AccountSA::OhosAccountInfo osAccountInfo; + int ret = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(osAccountInfo); + if (ret != 0 || osAccountInfo.uid_ == "") { + DHLOGE("Get accountId from Ohos account info failed, ret: %{public}d.", ret); + return false; + } + localAccountInfo.accountId_ = osAccountInfo.uid_; +#endif + localAccountInfo.tokenId_ = IPCSkeleton::GetSelfTokenID(); + + if (!GetLocalNetworkId(localAccountInfo.networkId_)) { + DHLOGE("Get local networkid failed"); + return false; + } + DHLOGI("Get local accountinfo success, accountId %{public}s, userId %{public}s, networkId %{public}s.", + GetAnonyString(localAccountInfo.accountId_).c_str(), std::to_string(localAccountInfo.userId_).c_str(), + GetAnonyString(localAccountInfo.networkId_).c_str()); + return true; +} + +bool SoftBusPermissionCheck::CheckSrcIsSameAccount(const std::string &sinkNetworkId, + const AccountInfo &localAccountInfo) +{ +#ifdef SUPPORT_SAME_ACCOUNT + DmAccessCaller caller = { + .accountId = localAccountInfo.accountId_, + .networkId = localAccountInfo.networkId_, + .userId = localAccountInfo.userId_, + }; + DmAccessCallee callee = { + .networkId = sinkNetworkId + }; + if (!DeviceManager::GetInstance().CheckSrcIsSameAccount(caller, callee)) { + DHLOGE("Check src same account failed"); + return false; + } +#endif + return true; +} + +bool SoftBusPermissionCheck::CheckSinkIsSameAccount(const AccountInfo &callerAccountInfo, + const AccountInfo &calleeAccountInfo) +{ +#ifdef SUPPORT_SAME_ACCOUNT + DmAccessCaller caller = { + .accountId = callerAccountInfo.accountId_, + .networkId = callerAccountInfo.networkId_, + .userId = callerAccountInfo.userId_, + }; + DmAccessCallee callee = { + .accountId = calleeAccountInfo.accountId_, + .networkId = calleeAccountInfo.networkId_, + .userId = calleeAccountInfo.userId_, + }; + if (!DeviceManager::GetInstance().CheckSinkIsSameAccount(caller, callee)) { + DHLOGE("Check sink same account failed"); + return false; + } +#endif + return true; +} + +bool SoftBusPermissionCheck::CheckSrcAccessControl(const std::string &sinkNetworkId, + const AccountInfo &localAccountInfo) +{ + DmAccessCaller caller { + .accountId = localAccountInfo.accountId_, + .pkgName = SERVICE_NAME, + .networkId = localAccountInfo.networkId_, + .userId = localAccountInfo.userId_, + .tokenId = localAccountInfo.tokenId_, + }; + DmAccessCallee callee = { + .networkId = sinkNetworkId, + }; + if (!DeviceManager::GetInstance().CheckSrcAccessControl(caller, callee)) { + DHLOGE("Check src acl failed"); + return false; + } + return true; +} + +bool SoftBusPermissionCheck::CheckSinkAccessControl(const AccountInfo &callerAccountInfo, + const AccountInfo &calleeAccountInfo) +{ + DmAccessCaller caller { + .accountId = callerAccountInfo.accountId_, + .pkgName = SERVICE_NAME, + .networkId = callerAccountInfo.networkId_, + .userId = callerAccountInfo.userId_, + .tokenId = callerAccountInfo.tokenId_, + }; + DmAccessCallee callee { + .accountId = calleeAccountInfo.accountId_, + .networkId = calleeAccountInfo.networkId_, + .pkgName = SERVICE_NAME, + .userId = calleeAccountInfo.userId_, + .tokenId = calleeAccountInfo.tokenId_, + }; + if (!DeviceManager::GetInstance().CheckSinkAccessControl(caller, callee)) { + DHLOGE("Check sink acl failed"); + return false; + } + return true; +} + +int32_t SoftBusPermissionCheck::GetCurrentUserId() +{ + std::vector userIds{}; + auto ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(userIds); + if (ret != NO_ERROR || userIds.empty()) { + DHLOGE("Query active os account id failed, ret = %{public}d", ret); + return INVALID_USER_ID; + } + return userIds[0]; +} + +bool SoftBusPermissionCheck::GetLocalNetworkId(std::string &networkId) +{ + DistributedHardware::DmDeviceInfo localDeviceInfo{}; + int errCode = DeviceManager::GetInstance().GetLocalDeviceInfo(SERVICE_NAME, localDeviceInfo); + if (errCode != 0) { + DHLOGE("Get localdeviceInfo failed, ret = %{public}d", errCode); + return false; + } + networkId = localDeviceInfo.networkId; + return true; +} + +bool SoftBusPermissionCheck::SetAccessInfoToSocket(const int32_t sessionId) +{ +#ifdef SUPPORT_SAME_ACCOUNT + AccountInfo accountInfo; + if (!GetLocalAccountInfo(accountInfo)) { + DHLOGE("GetOsAccountData failed."); + return false; + } + nlohmann::json jsonObj; + jsonObj[ACCOUNT_ID] = accountInfo.accountId_; + + SocketAccessInfo accessInfo; + accessInfo.userId = accountInfo.userId_; + std::string jsonStr = jsonObj.dump(); + size_t len = jsonStr.size(); + std::shared_ptr charArr(new char[len + 1], [](char *p) {delete[] p;}); + if (strcpy_s(charArr.get(), len + 1, jsonStr.c_str()) != 0) { + DHLOGE("strcpy_s failed."); + return false; + } + accessInfo.extraAccessInfo = charArr.get(); + accessInfo.localTokenId = accountInfo.tokenId_; + if (SetAccessInfo(sessionId, accessInfo) != 0) { + DHLOGE("set access info failed"); + return false; + } +#endif + return true; +} + +bool SoftBusPermissionCheck::TransCallerInfo(SocketAccessInfo *callerInfo, + AccountInfo &callerAccountInfo, const std::string &networkId) +{ + if (callerInfo == nullptr || callerInfo->extraAccessInfo == nullptr) { + DHLOGE("callerInfo or extraAccessInfo is nullptr."); + return true; + } + nlohmann::json jsonObj = nlohmann::json::parse(std::string(callerInfo->extraAccessInfo), nullptr, false); + if (jsonObj.is_discarded()) { + DHLOGE("jsonObj parse failed."); + return false; + } + if (!jsonObj.contains(ACCOUNT_ID) || !jsonObj[ACCOUNT_ID].is_string()) { + DHLOGE("get ext jsonObj parse failed."); + return false; + } + callerAccountInfo.accountId_ = jsonObj[ACCOUNT_ID].get(); + callerAccountInfo.userId_ = callerInfo->userId; + callerAccountInfo.networkId_ = networkId; + DHLOGI("TransCallerInfo success"); + return true; +} + +bool SoftBusPermissionCheck::FillLocalInfo(SocketAccessInfo *localInfo) +{ + if (localInfo == nullptr) { + DHLOGE("localInfo is nullptr."); + return false; + } + int32_t userId = GetCurrentUserId(); + if (userId == INVALID_USER_ID) { + DHLOGE("get current user id falied"); + return false; + } + localInfo->userId = userId; + localInfo->localTokenId = IPCSkeleton::GetSelfTokenID(); + return true; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/BUILD.gn b/services/softbusadapter/test/unittest/BUILD.gn index e9777b16..68ac56b5 100644 --- a/services/softbusadapter/test/unittest/BUILD.gn +++ b/services/softbusadapter/test/unittest/BUILD.gn @@ -36,11 +36,6 @@ config("module_private_config") { ## UnitTest screen_soft_bus_adapter_test ohos_unittest("SoftBusAdapterTest") { - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false - } module_out_path = module_out_path sources = [ "${services_path}/softbusadapter/test/unittest/src/softbus_adapter_test.cpp" ] @@ -50,6 +45,13 @@ ohos_unittest("SoftBusAdapterTest") { "${common_path}/test/unittest/resource:dscreen_unittest_public_config", ] + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"SoftbusAdapterTest\"", + "LOG_DOMAIN=0xD004140", + "NORMAL_MOCK", + ] + deps = [ "${services_path}/screentransport/screensourcetrans:distributed_screen_sourcetrans" ] external_deps = [ @@ -57,15 +59,76 @@ ohos_unittest("SoftBusAdapterTest") { "access_token:libnativetoken_shared", "access_token:libtokensetproc_shared", "c_utils:utils", + "device_manager:devicemanagersdk", "distributed_hardware_fwk:distributedhardwareutils", "dsoftbus:softbus_client", "googletest:gmock", "googletest:gtest_main", "hilog:libhilog", + "os_account:libaccountkits", + "os_account:os_account_innerkits", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (need_same_account) { + defines += [ "SUPPORT_SAME_ACCOUNT" ] + } +} + +ohos_unittest("SoftbusPermissionCheckTest") { + module_out_path = module_out_path + + include_dirs = [ + "${services_path}/softbusadapter/include", + "${services_path}/softbusadapter/test/unittest/include" + ] + + sources = [ + "${services_path}/softbusadapter/src/softbus_permission_check.cpp", + "${services_path}/softbusadapter/test/unittest/src/device_manager_impl_mock.cpp", + "${services_path}/softbusadapter/test/unittest/src/mock_other_method.cpp", + "${services_path}/softbusadapter/test/unittest/src/socket_mock.cpp", + "${services_path}/softbusadapter/test/unittest/src/softbus_permission_check_test.cpp", + ] + + configs = [ + ":module_private_config", + "${common_path}/test/unittest/resource:dscreen_unittest_public_config", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"SoftbusPermissionCheckTest\"", + "LOG_DOMAIN=0xD004140", + "NORMAL_MOCK", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "dsoftbus:softbus_client", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "os_account:libaccountkits", + "os_account:os_account_innerkits", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] + + if (need_same_account) { + defines += [ "SUPPORT_SAME_ACCOUNT" ] + } } group("soft_bus_adapter_test") { testonly = true - deps = [ ":SoftBusAdapterTest" ] + deps = [ + ":SoftBusAdapterTest", + ":SoftbusPermissionCheckTest", + ] } diff --git a/services/softbusadapter/test/unittest/include/device_manager_impl_mock.h b/services/softbusadapter/test/unittest/include/device_manager_impl_mock.h new file mode 100644 index 00000000..7b52aad1 --- /dev/null +++ b/services/softbusadapter/test/unittest/include/device_manager_impl_mock.h @@ -0,0 +1,75 @@ +/* + * 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_SOFTBUS_ADAPTER_DEVICE_MANAGER_MOCK_H +#define OHOS_SOFTBUS_ADAPTER_DEVICE_MANAGER_MOCK_H + +#include +#include +#include + +#include "device_manager.h" +#include "softbus_bus_center.h" + +namespace OHOS::DistributedHardware { +class DeviceManagerBase { +public: + virtual ~DeviceManagerBase() = default; +public: + virtual int32_t InitDeviceManager(const std::string &pkgName, + std::shared_ptr dmInitCallback) = 0; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, + const std::string &extra, std::vector &deviceList) = 0; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) = 0; + virtual bool CheckSrcAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; + virtual bool CheckSinkAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; + virtual bool CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; + virtual bool CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; + #ifdef NORMAL_MOCK + virtual int32_t GetNetworkTypeByNetworkId(const std::string &pkgName, const std::string &netWorkId, + int32_t &netWorkType) = 0; + #endif +public: + virtual int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) = 0; +public: + static inline std::shared_ptr deviceManager = nullptr; +}; + +class DeviceManagerMock : public DeviceManagerBase { +public: + MOCK_METHOD2(InitDeviceManager, int32_t(const std::string &pkgName, + std::shared_ptr dmInitCallback)); + MOCK_METHOD1(UnInitDeviceManager, int32_t(const std::string &pkgName)); + MOCK_METHOD3(GetTrustedDeviceList, int32_t(const std::string &pkgName, + const std::string &extra, std::vector &deviceList)); + MOCK_METHOD3(RegisterDevStateCallback, int32_t(const std::string &pkgName, + const std::string &extra, std::shared_ptr callback)); + MOCK_METHOD1(UnRegisterDevStateCallback, int32_t(const std::string &pkgName)); + MOCK_METHOD2(GetLocalNodeDeviceInfo, int32_t(const char *pkgName, NodeBasicInfo *info)); + MOCK_METHOD2(GetLocalDeviceInfo, int32_t(const std::string &pkgName, DmDeviceInfo &info)); + MOCK_METHOD2(CheckSrcAccessControl, bool(const DmAccessCaller &caller, const DmAccessCallee &callee)); + MOCK_METHOD2(CheckSinkAccessControl, bool(const DmAccessCaller &caller, const DmAccessCallee &callee)); + MOCK_METHOD2(CheckSrcIsSameAccount, bool(const DmAccessCaller &caller, const DmAccessCallee &callee)); + MOCK_METHOD2(CheckSinkIsSameAccount, bool(const DmAccessCaller &caller, const DmAccessCallee &callee)); + #ifdef NORMAL_MOCK + MOCK_METHOD3(GetNetworkTypeByNetworkId, int32_t(const std::string &pkgName, const std::string &netWorkId, + int32_t &netWorkType)); + #endif +}; +} +#endif \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/include/mock_other_method.h b/services/softbusadapter/test/unittest/include/mock_other_method.h new file mode 100644 index 00000000..8b020b22 --- /dev/null +++ b/services/softbusadapter/test/unittest/include/mock_other_method.h @@ -0,0 +1,42 @@ +/* + * 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_SOFTBUS_ADAPTER_DEVICE_OTHER_METHOD_MOCK_H +#define OHOS_SOFTBUS_ADAPTER_DEVICE_OTHER_METHOD_MOCK_H + +#include + +#include + +#include "ohos_account_kits.h" +#include "os_account_manager.h" + +namespace OHOS::DistributedHardware { +class DeviceOtherMethod { +public: + virtual ~DeviceOtherMethod() = default; +public: + virtual int QueryActiveOsAccountIds(std::vector& ids) = 0; + virtual int GetOhosAccountInfo(AccountSA::OhosAccountInfo &accountInfo) = 0; +public: + static inline std::shared_ptr otherMethod = nullptr; +}; + +class DeviceOtherMethodMock : public DeviceOtherMethod { +public: + MOCK_METHOD1(QueryActiveOsAccountIds, int(std::vector& ids)); + MOCK_METHOD1(GetOhosAccountInfo, int(AccountSA::OhosAccountInfo &accountInfo)); +}; +} +#endif \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/include/socket_mock.h b/services/softbusadapter/test/unittest/include/socket_mock.h new file mode 100644 index 00000000..806257f3 --- /dev/null +++ b/services/softbusadapter/test/unittest/include/socket_mock.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 OHOS_SOFTBUS_ADAPTER_SOCKET_MOCK_H +#define OHOS_SOFTBUS_ADAPTER_SOCKET_MOCK_H + +#include +#include + +#include "socket.h" + +namespace OHOS::DistributedHardware { +class DSocket { +public: + virtual ~DSocket() = default; +public: + virtual int32_t Socket(SocketInfo info) = 0; + virtual int32_t Listen(int32_t, const QosTV qos[], uint32_t, const ISocketListener *) = 0; + virtual int32_t Bind(int32_t, const QosTV qos[], uint32_t, const ISocketListener *) = 0; + virtual int SendFile(int32_t, const char *sFileList[], const char *dFileList[], uint32_t) = 0; + virtual int32_t Bind(int32_t socket, const ISocketListener *listener) = 0; + virtual int32_t SetAccessInfo(int32_t socket, SocketAccessInfo accessInfo) = 0; +public: + static inline std::shared_ptr dSocket = nullptr; +}; + +class SocketMock : public DSocket { +public: + MOCK_METHOD1(Socket, int32_t(SocketInfo info)); + MOCK_METHOD4(Listen, int32_t(int32_t, const QosTV qos[], uint32_t, const ISocketListener *)); + MOCK_METHOD4(Bind, int32_t(int32_t, const QosTV qos[], uint32_t, const ISocketListener *)); + MOCK_METHOD4(SendFile, int(int32_t, const char *sFileList[], const char *dFileList[], uint32_t)); + MOCK_METHOD2(Bind, int32_t(int32_t socket, const ISocketListener *listener)); + MOCK_METHOD2(SetAccessInfo, int32_t(int32_t socket, SocketAccessInfo accessInfo)); +}; +} +#endif \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/src/device_manager_impl_mock.cpp b/services/softbusadapter/test/unittest/src/device_manager_impl_mock.cpp new file mode 100644 index 00000000..19b24efe --- /dev/null +++ b/services/softbusadapter/test/unittest/src/device_manager_impl_mock.cpp @@ -0,0 +1,113 @@ +/* + * 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_impl.h" +#include "device_manager_impl_mock.h" +#include "dm_constants.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +#ifndef NORMAL_MOCK +const std::string NETWORKID_ONE = "45656596896323231"; +const std::string NETWORKID_TWO = "45656596896323232"; +const std::string NETWORKID_THREE = "45656596896323233"; +constexpr int32_t NETWORKTYPE_WITH_WIFI = 2; +constexpr int32_t NETWORKTYPE_NONE_WIFI = 4; +#endif + +int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) +{ + return DeviceManagerBase::deviceManager->InitDeviceManager(pkgName, dmInitCallback); +} + +int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) +{ + return DeviceManagerBase::deviceManager->UnInitDeviceManager(pkgName); +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, + const std::string &extra, + std::vector &deviceList) +{ + return DeviceManagerBase::deviceManager->GetTrustedDeviceList(pkgName, extra, deviceList); +} + +int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) +{ + return DeviceManagerBase::deviceManager->GetLocalDeviceInfo(pkgName, info); +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, + const std::string &extra, + std::shared_ptr callback) +{ + return DeviceManagerBase::deviceManager->RegisterDevStateCallback(pkgName, extra, callback); +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) +{ + return DeviceManagerBase::deviceManager->UnRegisterDevStateCallback(pkgName); +} + +#ifdef NORMAL_MOCK +int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + int32_t &netWorkType) +{ + return DeviceManagerBase::deviceManager->GetNetworkTypeByNetworkId(pkgName, netWorkId, netWorkType); +} +#else +int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + int32_t &netWorkType) +{ + GTEST_LOG_(INFO) << "GetTrustedDeviceList start"; + if (netWorkId == NETWORKID_ONE) { + return ERR_DM_INPUT_PARA_INVALID; + } + + if (netWorkId == NETWORKID_TWO) { + netWorkType = NETWORKTYPE_WITH_WIFI; + return DM_OK; + } + + netWorkType = NETWORKTYPE_NONE_WIFI; + return DM_OK; +} +#endif + +bool DeviceManagerImpl::CheckSrcAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + return DeviceManagerBase::deviceManager->CheckSrcAccessControl(caller, callee); +} + +bool DeviceManagerImpl::CheckSinkAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + return DeviceManagerBase::deviceManager->CheckSinkAccessControl(caller, callee); +} + +bool DeviceManagerImpl::CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + return DeviceManagerBase::deviceManager->CheckSrcIsSameAccount(caller, callee); +} + +bool DeviceManagerImpl::CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + return DeviceManagerBase::deviceManager->CheckSinkIsSameAccount(caller, callee); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/softbusadapter/test/unittest/src/mock_other_method.cpp b/services/softbusadapter/test/unittest/src/mock_other_method.cpp new file mode 100644 index 00000000..abf90094 --- /dev/null +++ b/services/softbusadapter/test/unittest/src/mock_other_method.cpp @@ -0,0 +1,100 @@ +/* + * 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 "os_account_manager.h" + +#include "mock_other_method.h" + +namespace OHOS { +namespace AccountSA { +/** + * Interfaces for ohos account subsystem. + */ +class OhosAccountKitsImpl : public OhosAccountKits { +public: + std::pair QueryOhosAccountInfo() + { + return {}; + } + + ErrCode GetOhosAccountInfo(OhosAccountInfo &accountInfo); + + ErrCode GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &accountInfo) + { + return 0; + } + + std::pair QueryOsAccountDistributedInfo(std::int32_t localId) + { + return {}; + } + + ErrCode UpdateOhosAccountInfo(const std::string& accountName, const std::string& uid, + const std::string& eventStr) + { + return 0; + } + + ErrCode SetOhosAccountInfo(const OhosAccountInfo &ohosAccountInfo, + const std::string &eventStr) + { + return 0; + } + + ErrCode SetOsAccountDistributedInfo( + const int32_t localId, const OhosAccountInfo& ohosAccountInfo, const std::string& eventStr) + { + return 0; + } + + ErrCode QueryDeviceAccountId(std::int32_t& accountId) + { + return 0; + } + + std::int32_t GetDeviceAccountIdByUID(std::int32_t& uid) + { + return 0; + } + + ErrCode SubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type, + const std::shared_ptr &callback) + { + return 0; + } + + ErrCode UnsubscribeDistributedAccountEvent(const DISTRIBUTED_ACCOUNT_SUBSCRIBE_TYPE type, + const std::shared_ptr &callback) + { + return 0; + } +}; + +ErrCode OsAccountManager::QueryActiveOsAccountIds(std::vector& ids) +{ + return OHOS::DistributedHardware::DeviceOtherMethod::otherMethod->QueryActiveOsAccountIds(ids); +} + +ErrCode OhosAccountKitsImpl::GetOhosAccountInfo(AccountSA::OhosAccountInfo &accountInfo) +{ + return OHOS::DistributedHardware::DeviceOtherMethod::otherMethod->GetOhosAccountInfo(accountInfo); +} + +OhosAccountKits &OhosAccountKits::GetInstance() +{ + static OhosAccountKitsImpl test; + return test; +} +} // namespace AccountSA +} // namespace OHOS diff --git a/services/softbusadapter/test/unittest/src/socket_mock.cpp b/services/softbusadapter/test/unittest/src/socket_mock.cpp new file mode 100644 index 00000000..c0e7a96e --- /dev/null +++ b/services/softbusadapter/test/unittest/src/socket_mock.cpp @@ -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. + */ + +#include "socket_mock.h" + +#include "inner_socket.h" + +int32_t Socket(SocketInfo info) +{ + return OHOS::DistributedHardware::DSocket::dSocket->Socket(info); +} + +int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + return OHOS::DistributedHardware::DSocket::dSocket->Listen(socket, qos, qosCount, listener); +} + +int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + return OHOS::DistributedHardware::DSocket::dSocket->Bind(socket, qos, qosCount, listener); +} + +void Shutdown(int32_t socket) +{ + (void)socket; +} + +int SendFile(int32_t socket, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) +{ + return OHOS::DistributedHardware::DSocket::dSocket->SendFile(socket, sFileList, dFileList, fileCnt); +} + +int32_t SetAccessInfo(int32_t socket, SocketAccessInfo accessInfo) +{ + return OHOS::DistributedHardware::DSocket::dSocket->SetAccessInfo(socket, accessInfo); +} \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/src/softbus_adapter_test.cpp b/services/softbusadapter/test/unittest/src/softbus_adapter_test.cpp index 331eeecd..15fcd999 100644 --- a/services/softbusadapter/test/unittest/src/softbus_adapter_test.cpp +++ b/services/softbusadapter/test/unittest/src/softbus_adapter_test.cpp @@ -14,10 +14,16 @@ */ #include "softbus_adapter_test.h" +#include "device_manager_impl_mock.h" +#include "dscreen_errcode.h" +#include "dscreen_util.h" +#include "mock_other_method.h" #include "socket.h" #include "softbus_adapter.h" +#include "softbus_permission_check.h" #include "token_setproc.h" +using namespace testing; using namespace testing::ext; static int g_mockBindReturnIntValue = 0; @@ -28,14 +34,50 @@ static int g_mockSocketReturnIntValue = 0; namespace OHOS { namespace DistributedHardware { - namespace { +namespace { const std::string PEER_SESSION_NAME = "ohos.dhardware.dscreen.session8647073e02e7a78f09473aa125"; const std::string REMOTE_DEV_ID = "f6d4c0864707aefte7a78f09473aa122ff57fc81c00981fcf5be989e7d112125"; const std::string DSCREEN_PKG_NAME_TEST = "ohos.dhardware.dscreen"; } -void SoftbusAdapterTest::SetUpTestCase(void) {} -void SoftbusAdapterTest::TearDownTestCase(void) {} +static bool g_checkSrc = true; +static bool g_checkSink = true; +static bool g_setAccess = true; +static bool g_transCaller = true; +static bool g_fillLocal = true; + +bool SoftBusPermissionCheck::CheckSrcPermission(const std::string &sinkNetworkId) +{ + return g_checkSrc; +} + +bool SoftBusPermissionCheck::CheckSinkPermission(const AccountInfo &callerAccountInfo) +{ + return g_checkSink; +} + +bool SoftBusPermissionCheck::SetAccessInfoToSocket(const int32_t sessionId) +{ + return g_setAccess; +} +bool SoftBusPermissionCheck::TransCallerInfo(SocketAccessInfo *callerInfo, + AccountInfo &callerAccountInfo, const std::string &networkId) +{ + return g_transCaller; +} + +bool SoftBusPermissionCheck::FillLocalInfo(SocketAccessInfo *localInfo) +{ + return g_fillLocal; +} + +void SoftbusAdapterTest::SetUpTestCase(void) +{ +} + +void SoftbusAdapterTest::TearDownTestCase(void) +{ +} void SoftbusAdapterTest::SetUp(void) { @@ -44,6 +86,11 @@ void SoftbusAdapterTest::SetUp(void) g_mockSendBytesReturnIntValue = 0; g_mockSendStreamReturnIntValue = 0; g_mockSocketReturnIntValue = 0; + g_checkSrc = true; + g_checkSink = true; + g_setAccess = true; + g_transCaller = true; + g_fillLocal = true; softbusAdapter_ = std::make_shared(); } @@ -287,9 +334,20 @@ HWTEST_F(SoftbusAdapterTest, OpenSoftbusSession_001, TestSize.Level1) std::string mySessionName = DATA_SESSION_NAME; std::string peerSessionName = DATA_SESSION_NAME; std::string peerDevId = "testDevId"; + int32_t actual = softbusAdapter_->OpenSoftbusSession(mySessionName, peerSessionName, peerDevId); EXPECT_NE(DH_SUCCESS, actual); + g_setAccess = false; + actual = softbusAdapter_->OpenSoftbusSession(mySessionName, peerSessionName, peerDevId); + EXPECT_EQ(ERR_DH_SCREEN_ADAPTER_CONTEXT, actual); + + g_checkSrc = false; + actual = softbusAdapter_->OpenSoftbusSession(mySessionName, peerSessionName, peerDevId); + EXPECT_EQ(ERR_DH_SCREEN_ADAPTER_PERMISSION_DENIED, actual); + + g_checkSrc = true; + g_setAccess = true; g_mockBindReturnIntValue = -1; actual = softbusAdapter_->OpenSoftbusSession(mySessionName, peerSessionName, peerDevId); EXPECT_EQ(ERR_DH_SCREEN_ADAPTER_PARA_ERROR, actual); @@ -536,6 +594,35 @@ HWTEST_F(SoftbusAdapterTest, GetSoftbusListenerById_002, TestSize.Level1) std::shared_ptr actual = softbusAdapter_->GetSoftbusListenerById(sessionId); EXPECT_EQ(nullptr, actual); } + +/** + * @tc.name: OnNegotiate2_001 + * @tc.desc: Verify the GetSoftbusListenerById function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(SoftbusAdapterTest, OnNegotiate2_001, TestSize.Level1) +{ + PeerSocketInfo info; + EXPECT_TRUE(softbusAdapter_->OnNegotiate2(0, info, nullptr, nullptr)); + + char networkId[10] = "networkId"; + SocketAccessInfo peerInfo; + info.networkId = networkId; + g_transCaller = false; + EXPECT_FALSE(softbusAdapter_->OnNegotiate2(0, info, &peerInfo, nullptr)); + + g_transCaller = true; + g_fillLocal = false; + EXPECT_FALSE(softbusAdapter_->OnNegotiate2(0, info, &peerInfo, nullptr)); + + g_fillLocal = true; + g_checkSink = false; + EXPECT_FALSE(softbusAdapter_->OnNegotiate2(0, info, &peerInfo, nullptr)); + + g_checkSink = true; + EXPECT_TRUE(softbusAdapter_->OnNegotiate2(0, info, &peerInfo, nullptr)); +} } // DistributedHardware } // OHOS @@ -567,4 +654,4 @@ extern "C" __attribute__((constructor)) int SendStream(int32_t socket, const Str const StreamFrameInfo *param) { return g_mockSendStreamReturnIntValue; -} +} \ No newline at end of file diff --git a/services/softbusadapter/test/unittest/src/softbus_permission_check_test.cpp b/services/softbusadapter/test/unittest/src/softbus_permission_check_test.cpp new file mode 100644 index 00000000..7fae14aa --- /dev/null +++ b/services/softbusadapter/test/unittest/src/softbus_permission_check_test.cpp @@ -0,0 +1,418 @@ +/* + * 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 "gtest/gtest.h" +#include +#include + +#include "device_manager_impl_mock.h" +#include "dscreen_errcode.h" +#include "dscreen_util.h" +#include "mock_other_method.h" +#include "socket_mock.h" +#include "softbus_permission_check.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class SoftbusPermissionCheckTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {}; + void TearDown() {}; +public: + static inline shared_ptr otherMethodMock_ = nullptr; + static inline shared_ptr socketMock_ = nullptr; + static inline shared_ptr deviceManagerMock_ = nullptr; +}; + +void SoftbusPermissionCheckTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + otherMethodMock_ = make_shared(); + DeviceOtherMethodMock::otherMethod = otherMethodMock_; + deviceManagerMock_ = make_shared(); + DeviceManagerMock::deviceManager = deviceManagerMock_; + socketMock_ = make_shared(); + SocketMock::dSocket = socketMock_; +} + +void SoftbusPermissionCheckTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + SocketMock::dSocket = nullptr; + socketMock_ = nullptr; + DeviceManagerMock::deviceManager = nullptr; + deviceManagerMock_ = nullptr; + DeviceOtherMethodMock::otherMethod = nullptr; + otherMethodMock_ = nullptr; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_GetLocalNetworkId_001 + * @tc.desc: Verify the GetLocalNetworkId function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_GetLocalNetworkId_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetLocalNetworkId_001 start"; + std::string networkId; + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_TRUE(SoftBusPermissionCheck::GetLocalNetworkId(networkId)); + + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::GetLocalNetworkId(networkId)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetLocalNetworkId_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_GetCurrentUserId_001 + * @tc.desc: Verify the GetCurrentUserId function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_GetCurrentUserId_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetCurrentUserId_001 start"; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + auto userId = SoftBusPermissionCheck::GetCurrentUserId(); + EXPECT_EQ(userId, INVALID_USER_ID); + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(DH_SUCCESS)); + userId = SoftBusPermissionCheck::GetCurrentUserId(); + EXPECT_EQ(userId, INVALID_USER_ID); + + std::vector userIds{100, 101}; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + userId = SoftBusPermissionCheck::GetCurrentUserId(); + EXPECT_EQ(userId, userIds[0]); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetCurrentUserId_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_FillLocalInfo_001 + * @tc.desc: Verify the FillLocalInfo function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_FillLocalInfo_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_FillLocalInfo_001 start"; + SocketAccessInfo *localInfoPtr = nullptr; + EXPECT_FALSE(SoftBusPermissionCheck::FillLocalInfo(localInfoPtr)); + + SocketAccessInfo localInfo; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::FillLocalInfo(&localInfo)); + + std::vector userIds{100, 101}; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_TRUE(SoftBusPermissionCheck::FillLocalInfo(&localInfo)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_FillLocalInfo_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_TransCallerInfo_001 + * @tc.desc: Verify the TransCallerInfo function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_TransCallerInfo_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_TransCallerInfo_001 start"; + SocketAccessInfo *localInfoPtr = nullptr; + AccountInfo callerAccountInfo; + std::string networkId; + EXPECT_TRUE(SoftBusPermissionCheck::TransCallerInfo(localInfoPtr, callerAccountInfo, networkId)); + + SocketAccessInfo localInfo; + localInfo.extraAccessInfo = nullptr; + EXPECT_TRUE(SoftBusPermissionCheck::TransCallerInfo(&localInfo, callerAccountInfo, networkId)); + + localInfo.extraAccessInfo = const_cast("test"); + EXPECT_FALSE(SoftBusPermissionCheck::TransCallerInfo(&localInfo, callerAccountInfo, networkId)); + + localInfo.extraAccessInfo = const_cast("{\"accountId\":1}"); + EXPECT_FALSE(SoftBusPermissionCheck::TransCallerInfo(&localInfo, callerAccountInfo, networkId)); + + localInfo.extraAccessInfo = const_cast("{\"accountId\":\"test\"}"); + EXPECT_TRUE(SoftBusPermissionCheck::TransCallerInfo(&localInfo, callerAccountInfo, networkId)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_TransCallerInfo_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_GetLocalAccountInfo_001 + * @tc.desc: Verify the GetLocalAccountInfo function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_GetLocalAccountInfo_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetLocalAccountInfo_001 start"; + AccountInfo localAccountInfo; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::GetLocalAccountInfo(localAccountInfo)); + + std::vector userIds{100, 101}; +#ifdef SUPPORT_SAME_ACCOUNT + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + AccountSA::OhosAccountInfo osAccountInfo; + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(INVALID_USER_ID))); + EXPECT_FALSE(SoftBusPermissionCheck::GetLocalAccountInfo(localAccountInfo)); + + osAccountInfo.uid_ = ""; // accountinfo uid = "" + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_FALSE(SoftBusPermissionCheck::GetLocalAccountInfo(localAccountInfo)); +#endif + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); +#ifdef SUPPORT_SAME_ACCOUNT + osAccountInfo.uid_ = "test"; + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); +#endif + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::GetLocalAccountInfo(localAccountInfo)); + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); +#ifdef SUPPORT_SAME_ACCOUNT + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); +#endif + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_TRUE(SoftBusPermissionCheck::GetLocalAccountInfo(localAccountInfo)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_GetLocalAccountInfo_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_SetAccessInfoToSocket_001 + * @tc.desc: Verify the SetAccessInfoToSocket function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_SetAccessInfoToSocket_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_SetAccessInfoToSocket_001 start"; + int32_t socketId = 0; +#ifdef SUPPORT_SAME_ACCOUNT + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::SetAccessInfoToSocket(socketId)); + + std::vector userIds{100, 101}; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + AccountSA::OhosAccountInfo osAccountInfo; + osAccountInfo.uid_ = "test"; + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*socketMock_, SetAccessInfo(_, _)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::SetAccessInfoToSocket(socketId)); + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*socketMock_, SetAccessInfo(_, _)).WillOnce(Return(DH_SUCCESS)); + EXPECT_TRUE(SoftBusPermissionCheck::SetAccessInfoToSocket(socketId)); +#else + EXPECT_TRUE(SoftBusPermissionCheck::SetAccessInfoToSocket(socketId)); +#endif + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_SetAccessInfoToSocket_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSrcIsSameAccount_001 + * @tc.desc: Verify the CheckSrcIsSameAccount function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSrcIsSameAccount_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcIsSameAccount_001 start"; + std::string networkId; + AccountInfo callerAccountInfo; +#ifdef SUPPORT_SAME_ACCOUNT + EXPECT_CALL(*deviceManagerMock_, CheckSrcIsSameAccount(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSrcIsSameAccount(networkId, callerAccountInfo)); + + EXPECT_CALL(*deviceManagerMock_, CheckSrcIsSameAccount(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSrcIsSameAccount(networkId, callerAccountInfo)); +#else + EXPECT_TRUE(SoftBusPermissionCheck::CheckSrcIsSameAccount(networkId, callerAccountInfo)); + +#endif + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcIsSameAccount_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSinkIsSameAccount_001 + * @tc.desc: Verify the CheckSinkIsSameAccount function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSinkIsSameAccount_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkIsSameAccount_001 start"; + const AccountInfo callerAccountInfo; + const AccountInfo calleeAccountInfo; +#ifdef SUPPORT_SAME_ACCOUNT + EXPECT_CALL(*deviceManagerMock_, CheckSinkIsSameAccount(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSinkIsSameAccount(callerAccountInfo, calleeAccountInfo)); + + EXPECT_CALL(*deviceManagerMock_, CheckSinkIsSameAccount(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSinkIsSameAccount(callerAccountInfo, calleeAccountInfo)); +#else + EXPECT_TRUE(SoftBusPermissionCheck::CheckSinkIsSameAccount(callerAccountInfo, calleeAccountInfo)); +#endif + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkIsSameAccount_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSrcAccessControl_001 + * @tc.desc: Verify the CheckSrcAccessControl function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSrcAccessControl_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcAccessControl_001 start"; + std::string networkId; + AccountInfo localAccountInfo; + EXPECT_CALL(*deviceManagerMock_, CheckSrcAccessControl(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSrcAccessControl(networkId, localAccountInfo)); + + EXPECT_CALL(*deviceManagerMock_, CheckSrcAccessControl(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSrcAccessControl(networkId, localAccountInfo)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcAccessControl_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSinkAccessControl_001 + * @tc.desc: Verify the CheckSinkAccessControl function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSinkAccessControl_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkAccessControl_001 start"; + const AccountInfo callerAccountInfo; + const AccountInfo calleeAccountInfo; + EXPECT_CALL(*deviceManagerMock_, CheckSinkAccessControl(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSinkAccessControl(callerAccountInfo, calleeAccountInfo)); + + EXPECT_CALL(*deviceManagerMock_, CheckSinkAccessControl(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSinkAccessControl(callerAccountInfo, calleeAccountInfo)); + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkAccessControl_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSrcPermission_001 + * @tc.desc: Verify the CheckSrcPermission function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSrcPermission_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcPermission_001 start"; + std::string networkId; // GetLocalAccount failed + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSrcPermission(networkId)); + + std::vector userIds{100, 101}; +#ifdef SUPPORT_SAME_ACCOUNT + AccountSA::OhosAccountInfo osAccountInfo; + osAccountInfo.uid_ = "test"; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerMock_, CheckSrcIsSameAccount(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSrcPermission(networkId)); + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerMock_, CheckSrcIsSameAccount(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSrcPermission(networkId)); +#else + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSrcPermission(networkId)); +#endif + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSrcPermission_001 end"; +} + +/** + * @tc.name: SoftbusPermissionCheckTest_CheckSinkPermission_001 + * @tc.desc: Verify the CheckSinkPermission function. + * @tc.type: FUNC + * @tc.require: ICCNFW + */ +HWTEST_F(SoftbusPermissionCheckTest, SoftbusPermissionCheckTest_CheckSinkPermission_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkPermission_001 start"; + AccountInfo callerAccountInfo; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSinkPermission(callerAccountInfo)); + + std::vector userIds{100, 101}; +#ifdef SUPPORT_SAME_ACCOUNT + AccountSA::OhosAccountInfo osAccountInfo; + osAccountInfo.uid_ = "test"; + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerMock_, CheckSinkIsSameAccount(_, _)).WillOnce(Return(true)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSinkPermission(callerAccountInfo)); + + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*otherMethodMock_, GetOhosAccountInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(osAccountInfo), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerMock_, CheckSinkIsSameAccount(_, _)).WillOnce(Return(false)); + EXPECT_FALSE(SoftBusPermissionCheck::CheckSinkPermission(callerAccountInfo)); +#else + EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(userIds), Return(DH_SUCCESS))); + EXPECT_CALL(*deviceManagerMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)); + EXPECT_TRUE(SoftBusPermissionCheck::CheckSinkPermission(callerAccountInfo)); +#endif + GTEST_LOG_(INFO) << "SoftbusPermissionCheckTest_CheckSinkPermission_001 end"; +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee