1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "session_manager/session_manager.h"
17
18 #include <cstdint>
19
20 #include "access_check/app_access_check_config_manager.h"
21 #include "accesstoken_kit.h"
22 #include "account_delegate_mock.h"
23 #include "auth_delegate_mock.h"
24 #include "bootstrap.h"
25 #include "db_store_mock.h"
26 #include "device_manager_adapter.h"
27 #include "device_manager_adapter_mock.h"
28 #include "gtest/gtest.h"
29 #include "meta_data_manager_mock.h"
30 #include "metadata/meta_data_manager.h"
31 #include "metadata/store_meta_data.h"
32 #include "nativetoken_kit.h"
33 #include "session_manager/route_head_handler_impl.h"
34 #include "session_manager/upgrade_manager.h"
35 #include "token_setproc.h"
36 #include "user_delegate.h"
37 #include "user_delegate_mock.h"
38 #include "utils/endian_converter.h"
39
40 namespace {
41 using namespace testing;
42 using namespace testing::ext;
43 using namespace OHOS::DistributedKv;
44 using namespace OHOS::DistributedData;
45 using namespace DistributedDB;
46 using namespace OHOS;
47 using namespace OHOS::Security::AccessToken;
48 using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo;
49 using UserInfo = DistributedDB::UserInfo;
50 using AppMappingInfo = OHOS::DistributedData::AppAccessCheckConfigManager::AppMappingInfo;
51 constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID";
52 constexpr const char *DEFAULT_USERID = "0";
53 constexpr int PEER_USER_ID1 = 101;
54 constexpr int PEER_USER_ID2 = 100;
55 constexpr int32_t USER_MAXID = 4;
56 constexpr int METADATA_UID = 2000000;
57 static constexpr int32_t OH_OS_TYPE = 10;
58
GrantPermissionNative()59 void GrantPermissionNative()
60 {
61 const char **perms = new const char *[2];
62 perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC";
63 perms[1] = "ohos.permission.ACCESS_SERVICE_DM";
64 TokenInfoParams infoInstance = {
65 .dcapsNum = 0,
66 .permsNum = 2,
67 .aclsNum = 0,
68 .dcaps = nullptr,
69 .perms = perms,
70 .acls = nullptr,
71 .processName = "distributed_data_test",
72 .aplStr = "system_basic",
73 };
74 uint64_t tokenId = GetAccessTokenId(&infoInstance);
75 SetSelfTokenID(tokenId);
76 AccessTokenKit::ReloadNativeTokenInfo();
77 delete[] perms;
78 }
79
80 class SessionManagerTest : public testing::Test {
81 public:
CreateUserStatus(std::vector<UserStatus> & users)82 void CreateUserStatus(std::vector<UserStatus> &users)
83 {
84 for (int32_t i = 0; i < USER_MAXID; i++) {
85 UserStatus stat;
86 stat.id = i;
87 users.push_back(stat);
88 }
89 }
90
CreateStoreMetaData(std::vector<StoreMetaData> & datas,SessionPoint local)91 static void CreateStoreMetaData(std::vector<StoreMetaData> &datas, SessionPoint local)
92 {
93 StoreMetaData data;
94 data.appId = local.appId;
95 data.storeId = local.storeId;
96 data.bundleName = "com.test.session";
97 StoreMetaData data1;
98 data1.appId = local.appId;
99 data1.storeId = "local.storeId";
100 data1.bundleName = "com.test.session1";
101 StoreMetaData data2;
102 data2.appId = "local.appId";
103 data2.storeId = local.storeId;
104 data2.bundleName = "com.test.session2";
105 StoreMetaData data3;
106 data3.appId = "local.appId";
107 data3.storeId = "local.storeId";
108 data3.bundleName = "com.test.session3";
109 datas.push_back(data);
110 datas.push_back(data1);
111 datas.push_back(data2);
112 datas.push_back(data3);
113 }
114
SetUpTestCase()115 static void SetUpTestCase()
116 {
117 MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, "");
118 auto executors = std::make_shared<ExecutorPool>(12, 5);
119 Bootstrap::GetInstance().LoadComponents();
120 Bootstrap::GetInstance().LoadDirectory();
121 Bootstrap::GetInstance().LoadCheckers();
122 DeviceManagerAdapter::GetInstance().Init(executors);
123
124 // init peer device
125 UserMetaData userMetaData;
126 userMetaData.deviceId = PEER_DEVICE_ID;
127
128 UserStatus status;
129 status.isActive = true;
130 status.id = PEER_USER_ID1;
131 userMetaData.users = { status };
132 status.id = PEER_USER_ID2;
133 userMetaData.users.emplace_back(status);
134
135 auto peerUserMetaKey = UserMetaRow::GetKeyFor(userMetaData.deviceId);
136 MetaDataManager::GetInstance().SaveMeta({ peerUserMetaKey.begin(), peerUserMetaKey.end() }, userMetaData);
137
138 CapMetaData capMetaData;
139 capMetaData.version = CapMetaData::CURRENT_VERSION;
140
141 auto peerCapMetaKey = CapMetaRow::GetKeyFor(userMetaData.deviceId);
142 MetaDataManager::GetInstance().SaveMeta({ peerCapMetaKey.begin(), peerCapMetaKey.end() }, capMetaData);
143 InitSystemMetaData();
144 InitNormalMetaData();
145 GrantPermissionNative();
146 }
147
TearDownTestCase()148 static void TearDownTestCase()
149 {
150 auto peerUserMetaKey = UserMetaRow::GetKeyFor(PEER_DEVICE_ID);
151 MetaDataManager::GetInstance().DelMeta(std::string(peerUserMetaKey.begin(), peerUserMetaKey.end()));
152 auto peerCapMetaKey = CapMetaRow::GetKeyFor(PEER_DEVICE_ID);
153 MetaDataManager::GetInstance().DelMeta(std::string(peerCapMetaKey.begin(), peerCapMetaKey.end()));
154 }
155
SetUp()156 void SetUp()
157 {
158 deviceManagerAdapterMock = std::make_shared<DeviceManagerAdapterMock>();
159 BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock;
160 userDelegateMock = std::make_shared<UserDelegateMock>();
161 BUserDelegate::userDelegate = userDelegateMock;
162 ConstructValidData();
163 auto res = MetaDataManager::GetInstance().SaveMeta(systemMetaData_.GetKey(), systemMetaData_);
164 EXPECT_EQ(res, true);
165 res = MetaDataManager::GetInstance().SaveMeta(normalMetaData_.GetKey(), normalMetaData_);
166 EXPECT_EQ(res, true);
167 }
168
TearDown()169 void TearDown()
170 {
171 deviceManagerAdapterMock = nullptr;
172 BDeviceManagerAdapter::deviceManagerAdapter = nullptr;
173 userDelegateMock = nullptr;
174 BUserDelegate::userDelegate = nullptr;
175 MetaDataManager::GetInstance().DelMeta(systemMetaData_.GetKey());
176 MetaDataManager::GetInstance().DelMeta(normalMetaData_.GetKey());
177 }
178
ConstructValidData()179 void ConstructValidData()
180 {
181 const std::string storeId = "test_store";
182 InitializeBuffer();
183 ConstructRouteHead(storeId);
184 ConstructSessionDevicePair();
185 ConstructSessionUserPair();
186 ConstructSessionAppId();
187 ConstructSessionStoreId(storeId);
188
189 const size_t validlLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair)
190 + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId)
191 + storeId.size();
192 validTotalLen = validlLen;
193 }
194
195 static void InitSystemMetaData();
196 static void InitNormalMetaData();
197 static std::shared_ptr<DBStoreMock> dbStoreMock_;
198 static StoreMetaData systemMetaData_;
199 static StoreMetaData normalMetaData_;
200
201 static inline std::shared_ptr<DeviceManagerAdapterMock> deviceManagerAdapterMock = nullptr;
202 static inline std::shared_ptr<UserDelegateMock> userDelegateMock = nullptr;
203
204 private:
InitializeBuffer()205 void InitializeBuffer()
206 {
207 memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE);
208 ptr = dataBuffer;
209 remaining = BUFFER_SIZE;
210 }
211
ConstructRouteHead(const std::string & storeId)212 void ConstructRouteHead(const std::string &storeId)
213 {
214 RouteHead head{};
215 head.magic = HostToNet(RouteHead::MAGIC_NUMBER);
216 head.version = HostToNet(RouteHead::VERSION);
217 head.dataLen = HostToNet(sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1
218 + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + storeId.size());
219 head.checkSum = 0;
220
221 errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead));
222 ASSERT_EQ(err, 0) << "Failed to copy RouteHead";
223 ptr += sizeof(RouteHead);
224 remaining -= sizeof(RouteHead);
225 }
226
ConstructSessionDevicePair()227 void ConstructSessionDevicePair()
228 {
229 SessionDevicePair devPair{ .sourceId = "PEER_DEVICE_ID", .targetId = "PEER_DEVICE_ID" };
230 constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId);
231
232 errno_t err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1);
233 ASSERT_EQ(err, 0) << "Failed to init sourceId";
234 devPair.sourceId[DEV_ID_SIZE - 1] = '\0';
235
236 err = memset_s(devPair.targetId, DEV_ID_SIZE, 'B', DEV_ID_SIZE - 1);
237 ASSERT_EQ(err, 0) << "Failed to init targetId";
238 devPair.targetId[DEV_ID_SIZE - 1] = '\0';
239
240 err = memcpy_s(ptr, remaining, &devPair, sizeof(SessionDevicePair));
241 ASSERT_EQ(err, 0) << "Failed to copy SessionDevicePair";
242 ptr += sizeof(SessionDevicePair);
243 remaining -= sizeof(SessionDevicePair);
244 }
245
ConstructSessionUserPair()246 void ConstructSessionUserPair()
247 {
248 SessionUserPair userPair{};
249 userPair.sourceUserId = HostToNet(100U);
250 userPair.targetUserCount = HostToNet(1U);
251
252 errno_t err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair));
253 ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair";
254 ptr += sizeof(SessionUserPair);
255 remaining -= sizeof(SessionUserPair);
256
257 uint32_t targetUser = HostToNet(200U);
258 err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t));
259 ASSERT_EQ(err, 0) << "Failed to copy targetUser";
260 ptr += sizeof(uint32_t);
261 remaining -= sizeof(uint32_t);
262 }
263
ConstructSessionAppId()264 void ConstructSessionAppId()
265 {
266 SessionAppId appId{};
267 const char *appStr = "test";
268 appId.len = HostToNet(static_cast<uint32_t>(APP_STR_LEN));
269
270 errno_t err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId));
271 ASSERT_EQ(err, 0) << "Failed to copy SessionAppId";
272 ptr += sizeof(SessionAppId);
273 remaining -= sizeof(SessionAppId);
274
275 err = memcpy_s(ptr, remaining, appStr, APP_STR_LEN);
276 ASSERT_EQ(err, 0) << "Failed to copy appId data";
277 ptr += APP_STR_LEN;
278 remaining -= APP_STR_LEN;
279 }
280
ConstructSessionStoreId(const std::string & storeId)281 void ConstructSessionStoreId(const std::string &storeId)
282 {
283 SessionStoreId storeIdHeader{};
284 storeIdHeader.len = HostToNet(static_cast<uint32_t>(storeId.size()));
285
286 errno_t err = memcpy_s(ptr, remaining, &storeIdHeader, sizeof(SessionStoreId));
287 ASSERT_EQ(err, 0) << "Failed to copy storeId length";
288 ptr += sizeof(SessionStoreId);
289 remaining -= sizeof(SessionStoreId);
290
291 err = memcpy_s(ptr, remaining, storeId.c_str(), storeId.size());
292 ASSERT_EQ(err, 0) << "Failed to copy storeId data";
293 ptr += storeId.size();
294 remaining -= storeId.size();
295 }
296
297 size_t validTotalLen;
298 uint8_t dataBuffer[1024];
299 static constexpr size_t APP_STR_LEN = 4;
300 uint8_t *ptr = dataBuffer;
301 size_t remaining = BUFFER_SIZE;
302 static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer);
303 };
304
305 std::shared_ptr<DBStoreMock> SessionManagerTest::dbStoreMock_ = std::make_shared<DBStoreMock>();
306 StoreMetaData SessionManagerTest::systemMetaData_;
307 StoreMetaData SessionManagerTest::normalMetaData_;
308
InitNormalMetaData()309 void SessionManagerTest::InitNormalMetaData()
310 {
311 normalMetaData_.bundleName = "ohos.test.demo";
312 normalMetaData_.appId = "ohos.test.demo";
313 normalMetaData_.storeId = "test_store";
314 normalMetaData_.user = "100";
315 normalMetaData_.deviceId = "local_device";
316 normalMetaData_.tokenId = AccessTokenKit::GetHapTokenID(PEER_USER_ID2, "ohos.test.demo", 0);
317 normalMetaData_.uid = METADATA_UID;
318 normalMetaData_.storeType = 1;
319 }
320
InitSystemMetaData()321 void SessionManagerTest::InitSystemMetaData()
322 {
323 systemMetaData_.bundleName = "ohos.test.demo";
324 systemMetaData_.appId = "ohos.test.demo";
325 systemMetaData_.storeId = "test_store";
326 systemMetaData_.user = DEFAULT_USERID;
327 systemMetaData_.deviceId = "local_device";
328 systemMetaData_.tokenId = AccessTokenKit::GetHapTokenID(PEER_USER_ID2, "ohos.test.demo", 0);
329 systemMetaData_.uid = METADATA_UID;
330 systemMetaData_.storeType = 1;
331 }
332
333 /**
334 * @tc.name: PackAndUnPack01
335 * @tc.desc: test get db dir
336 * @tc.type: FUNC
337 * @tc.require:
338 * @tc.author: illybyy
339 */
340 HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2)
341 {
342 const DistributedDB::ExtendInfo info = {
343 .appId = "ohos.test.demo", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
344 };
345 auto sendHandler = RouteHeadHandlerImpl::Create(info);
346 ASSERT_NE(sendHandler, nullptr);
347 uint32_t routeHeadSize = 0;
348 sendHandler->GetHeadDataSize(routeHeadSize);
349 ASSERT_EQ(routeHeadSize, 0);
350 std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t[]>(routeHeadSize);
351 sendHandler->FillHeadData(data.get(), routeHeadSize, routeHeadSize);
352
353 std::vector<DistributedDB::UserInfo> users;
354 auto recvHandler = RouteHeadHandlerImpl::Create({});
355 ASSERT_NE(recvHandler, nullptr);
356 uint32_t parseSize = 0;
357 std::string device = "";
358 recvHandler->ParseHeadDataLen(data.get(), routeHeadSize, parseSize, device);
359 EXPECT_EQ(routeHeadSize, parseSize);
360 recvHandler->ParseHeadDataUser(data.get(), routeHeadSize, "", users);
361 ASSERT_EQ(users.size(), 0);
362 }
363
364 /**
365 * @tc.name: GetHeadDataSize_Test1
366 * @tc.desc: test appId equal processLabel.
367 * @tc.type: FUNC
368 * @tc.author: guochao
369 */
370 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1)
371 {
372 ExtendInfo info;
373 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
374 uint32_t headSize = 0;
375 routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel();
376 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
377 EXPECT_EQ(status, DistributedDB::OK);
378 EXPECT_EQ(headSize, 0);
379 }
380
381 /**
382 * @tc.name: GetHeadDataSize_Test2
383 * @tc.desc: test appId not equal processLabel.
384 * @tc.type: FUNC
385 * @tc.author: guochao
386 */
387 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1)
388 {
389 ExtendInfo info;
390 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
391 uint32_t headSize = 0;
392 routeHeadHandlerImpl.appId_ = "otherAppId";
393 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
394 EXPECT_EQ(status, DistributedDB::DB_ERROR);
395 EXPECT_EQ(headSize, 0);
396 }
397
398 /**
399 * @tc.name: GetHeadDataSize_Test3
400 * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel.
401 * @tc.type: FUNC
402 * @tc.author: guochao
403 */
404 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1)
405 {
406 DeviceInfo deviceInfo;
407 deviceInfo.osType = OH_OS_TYPE;
408 EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo));
409 ExtendInfo info;
410 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
411 uint32_t headSize = 0;
412 routeHeadHandlerImpl.appId_ = "otherAppId";
413 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
414 EXPECT_EQ(status, DistributedDB::DB_ERROR);
415 EXPECT_EQ(headSize, 0);
416 }
417
418 /**
419 * @tc.name: GetHeadDataSize_Test4
420 * @tc.desc: test GetHeadDataSize
421 * @tc.type: FUNC
422 * @tc.author: guochao
423 */
424 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1)
425 {
426 DeviceInfo deviceInfo;
427 deviceInfo.osType = OH_OS_TYPE;
428 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
429 EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo));
430
431 const DistributedDB::ExtendInfo info = {
432 .appId = "otherAppId", .storeId = "test_store", .userId = DEFAULT_USERID, .dstTarget = PEER_DEVICE_ID
433 };
434 auto sendHandler = RouteHeadHandlerImpl::Create(info);
435 ASSERT_NE(sendHandler, nullptr);
436
437 auto userId = sendHandler->GetTargetUserId();
438 EXPECT_EQ(userId, "0");
439
440 std::vector<UserStatus> userStatus;
441 UserStatus userStat1;
442 UserStatus userStat2;
443 UserStatus userStat3;
444 userStat1.id = 1;
445 userStat2.id = 2;
446 userStat3.id = 3;
447 userStatus.push_back(userStat1);
448 userStatus.push_back(userStat2);
449 userStatus.push_back(userStat3);
450 EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillRepeatedly(Return(userStatus));
451
452 uint32_t headSize = 0;
453 auto status = sendHandler->GetHeadDataSize(headSize);
454 EXPECT_EQ(status, DistributedDB::OK);
455 EXPECT_EQ(headSize, 208);
456
457 uint32_t routeHeadSize = 10;
458 std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t[]>(routeHeadSize);
459 status = sendHandler->FillHeadData(data.get(), routeHeadSize, routeHeadSize);
460 EXPECT_EQ(status, DistributedDB::DB_ERROR);
461 }
462
463 /**
464 * @tc.name: GetHeadDataSize_Test5
465 * @tc.desc: test device is not OH_OS_TYPE and appId is empty.
466 * @tc.type: FUNC
467 * @tc.author: guochao
468 */
469 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test5, TestSize.Level1)
470 {
471 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillOnce(Return(true)).WillOnce(Return(false));
472 const DistributedDB::ExtendInfo info = {
473 .appId = "", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
474 };
475 auto sendHandler = RouteHeadHandlerImpl::Create(info);
476 ASSERT_NE(sendHandler, nullptr);
477 uint32_t headSize;
478 auto status = sendHandler->GetHeadDataSize(headSize);
479 EXPECT_EQ(status, DistributedDB::DB_ERROR);
480 EXPECT_EQ(headSize, 0);
481 }
482
483 /**
484 * @tc.name: GetHeadDataSize_Test6
485 * @tc.desc: test device != OH_OS_TYPE && appId.isNotEmpty && appId.isTrusted.
486 * @tc.type: FUNC
487 * @tc.author: guochao
488 */
489 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test6, TestSize.Level1)
490 {
491 const DistributedDB::ExtendInfo info = {
492 .appId = "com.test.demo", .storeId = "test", .userId = "100", .dstTarget = PEER_DEVICE_ID
493 };
494 std::vector<AppMappingInfo> mapper = { { .appId = info.appId, .bundleName = info.appId } };
495 AppAccessCheckConfigManager::GetInstance().Initialize(mapper);
496 auto sendHandler = RouteHeadHandlerImpl::Create(info);
497 ASSERT_NE(sendHandler, nullptr);
498 uint32_t headSize;
499 auto status = sendHandler->GetHeadDataSize(headSize);
500 EXPECT_EQ(status, DistributedDB::OK);
501 EXPECT_EQ(headSize, 0);
502 }
503
504 /**
505 * @tc.name: GetHeadDataSize_Test7
506 * @tc.desc: test GetCapability is failed.
507 * @tc.type: FUNC
508 * @tc.author: guochao
509 */
510 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test7, TestSize.Level1)
511 {
512 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
513 const DistributedDB::ExtendInfo info = {
514 .appId = "otherAppId", .storeId = "test", .userId = "100", .dstTarget = "10"
515 };
516 auto sendHandler = RouteHeadHandlerImpl::Create(info);
517 ASSERT_NE(sendHandler, nullptr);
518 uint32_t headSize;
519 auto status = sendHandler->GetHeadDataSize(headSize);
520 EXPECT_EQ(status, DistributedDB::DB_ERROR);
521 EXPECT_EQ(headSize, 0);
522 }
523
524 /**
525 * @tc.name: GetHeadDataSize_Test8
526 * @tc.desc: test peerCap.version != INALID_VERSION && session is invalid.
527 * @tc.type: FUNC
528 * @tc.author: guochao
529 */
530 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test8, TestSize.Level1)
531 {
532 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
533 const DistributedDB::ExtendInfo info = {
534 .appId = "otherAppId", .storeId = "test", .userId = "100", .dstTarget = PEER_DEVICE_ID
535 };
536 auto sendHandler = RouteHeadHandlerImpl::Create(info);
537 ASSERT_NE(sendHandler, nullptr);
538 uint32_t headSize;
539 auto status = sendHandler->GetHeadDataSize(headSize);
540 EXPECT_EQ(status, DistributedDB::DB_ERROR);
541 EXPECT_EQ(headSize, 0);
542 }
543
544 /**
545 * @tc.name: GetHeadDataSize_Test9
546 * @tc.desc: test peerCap.version != INALID_VERSION && session is valid.
547 * @tc.type: FUNC
548 * @tc.author: guochao
549 */
550 HWTEST_F(SessionManagerTest, GetHeadDataSize_Test9, TestSize.Level1)
551 {
552 DeviceInfo deviceInfo;
553 deviceInfo.uuid = PEER_DEVICE_ID;
554 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
555 EXPECT_CALL(*deviceManagerAdapterMock, GetLocalDevice()).WillRepeatedly(Return(deviceInfo));
556 const DistributedDB::ExtendInfo info = {
557 .appId = "test", .storeId = "test_store", .userId = DEFAULT_USERID, .dstTarget = PEER_DEVICE_ID
558 };
559 auto sendHandler = RouteHeadHandlerImpl::Create(info);
560 ASSERT_NE(sendHandler, nullptr);
561 uint32_t headSize;
562 auto status = sendHandler->GetHeadDataSize(headSize);
563 EXPECT_EQ(status, DistributedDB::OK);
564 EXPECT_EQ(headSize, 200);
565
566 uint32_t totalLen = 300;
567 std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t[]>(totalLen);
568 status = sendHandler->FillHeadData(data.get(), headSize, totalLen);
569 EXPECT_EQ(status, DistributedDB::OK);
570 uint32_t parseHeadSize;
571 auto res = sendHandler->ParseHeadDataLen(data.get(), totalLen, parseHeadSize, info.storeId);
572 EXPECT_EQ(res, true);
573 EXPECT_EQ(parseHeadSize, 200);
574
575 std::vector<UserInfo> userInfos;
576 std::string label;
577 res = sendHandler->ParseHeadDataUser(data.get(), totalLen, label, userInfos);
578 EXPECT_EQ(res, true);
579 EXPECT_EQ(label, "");
580 EXPECT_EQ(userInfos.size(), 1);
581 }
582
583 /**
584 * @tc.name: ParseHeadDataLenTest001
585 * @tc.desc: test ParseHeadDataLen data is nullptr.
586 * @tc.type: FUNC
587 * @tc.author: guochao
588 */
589 HWTEST_F(SessionManagerTest, ParseHeadDataLenTest001, TestSize.Level1)
590 {
591 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
592 const DistributedDB::ExtendInfo info = {
593 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
594 };
595 auto sendHandler = RouteHeadHandlerImpl::Create(info);
596 ASSERT_NE(sendHandler, nullptr);
597
598 uint32_t totalLen = 10;
599 uint32_t headSize;
600 std::string device = "device";
601
602 bool result = sendHandler->ParseHeadDataLen(nullptr, totalLen, headSize, device);
603 EXPECT_EQ(result, false);
604
605 auto status = sendHandler->FillHeadData(nullptr, headSize, headSize);
606 EXPECT_EQ(status, DistributedDB::DB_ERROR);
607 }
608
609 /**
610 * @tc.name: ParseHeadDataLenTest002
611 * @tc.desc: test ParseHeadDataLen totalLen < sizeof(RouteHead).
612 * @tc.type: FUNC
613 * @tc.author: guochao
614 */
615 HWTEST_F(SessionManagerTest, ParseHeadDataLenTest002, TestSize.Level1)
616 {
617 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
618 const DistributedDB::ExtendInfo info = {
619 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
620 };
621 auto sendHandler = RouteHeadHandlerImpl::Create(info);
622 ASSERT_NE(sendHandler, nullptr);
623
624 uint32_t totalLen = 10;
625 uint32_t headSize;
626 std::string device = "device";
627
628 bool result = sendHandler->ParseHeadDataLen(dataBuffer, totalLen, headSize, device);
629 EXPECT_EQ(result, false);
630 EXPECT_EQ(headSize, 0);
631 }
632
633 /**
634 * @tc.name: ParseHeadDataLenTest003
635 * @tc.desc: test ParseHeadDataLen totalLen - sizeof(RouteHead) < routeHead.dataLen.
636 * @tc.type: FUNC
637 * @tc.author: guochao
638 */
639 HWTEST_F(SessionManagerTest, ParseHeadDataLenTest003, TestSize.Level1)
640 {
641 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
642 const DistributedDB::ExtendInfo info = {
643 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
644 };
645 auto sendHandler = RouteHeadHandlerImpl::Create(info);
646 ASSERT_NE(sendHandler, nullptr);
647
648 uint32_t totalLen = 20;
649 uint32_t headSize;
650 std::string device = "device";
651
652 bool result = sendHandler->ParseHeadDataLen(dataBuffer, totalLen, headSize, device);
653 EXPECT_EQ(result, false);
654 EXPECT_EQ(headSize, 0);
655 }
656
657 /**
658 * @tc.name: ParseHeadDataUserTest001
659 * @tc.desc: test parse null data.
660 * @tc.type: FUNC
661 * @tc.author: guochao
662 */
663 HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1)
664 {
665 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
666 const DistributedDB::ExtendInfo info = {
667 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
668 };
669 auto sendHandler = RouteHeadHandlerImpl::Create(info);
670 ASSERT_NE(sendHandler, nullptr);
671
672 auto userId = sendHandler->GetTargetUserId();
673 EXPECT_EQ(userId, "");
674 uint32_t totalLen = 10;
675 std::string label = "testLabel";
676 std::vector<UserInfo> userInfos;
677
678 bool result = sendHandler->ParseHeadDataUser(nullptr, totalLen, label, userInfos);
679
680 EXPECT_FALSE(result);
681 EXPECT_EQ(userInfos.size(), 0);
682 }
683
684 /**
685 * @tc.name: ParseHeadDataUserTest002
686 * @tc.desc: test totalLen < sizeof(RouteHead).
687 * @tc.type: FUNC
688 * @tc.author: guochao
689 */
690 HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1)
691 {
692 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
693 const DistributedDB::ExtendInfo info = {
694 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
695 };
696 auto sendHandler = RouteHeadHandlerImpl::Create(info);
697 ASSERT_NE(sendHandler, nullptr);
698
699 uint8_t data[10] = { 0 };
700 std::string label = "testLabel";
701 std::vector<UserInfo> userInfos;
702
703 bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead) - 1, label, userInfos);
704
705 EXPECT_FALSE(result);
706 EXPECT_EQ(userInfos.size(), 0);
707 }
708
709 /**
710 * @tc.name: ParseHeadDataUserTest003
711 * @tc.desc: test totalLen < sizeof(RouteHead).
712 * @tc.type: FUNC
713 * @tc.author: guochao
714 */
715 HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1)
716 {
717 EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
718 const DistributedDB::ExtendInfo info = {
719 .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
720 };
721 auto sendHandler = RouteHeadHandlerImpl::Create(info);
722 ASSERT_NE(sendHandler, nullptr);
723
724 uint8_t data[10] = { 0 };
725 std::string label = "testLabel";
726 std::vector<UserInfo> userInfos;
727
728 RouteHead head = { 0 };
729 head.version = RouteHead::VERSION;
730 head.dataLen = static_cast<uint32_t>(sizeof(data) - sizeof(RouteHead));
731
732 bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos);
733
734 EXPECT_FALSE(result);
735 EXPECT_EQ(userInfos.size(), 0);
736 }
737
738 /**
739 * @tc.name: PackDataTest1
740 * @tc.desc: test headSize_ > totalLen.
741 * @tc.type: FUNC
742 * @tc.author: guochao
743 */
744 HWTEST_F(SessionManagerTest, PackDataTest1, TestSize.Level1)
745 {
746 ExtendInfo info;
747 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
748 routeHeadHandlerImpl.headSize_ = 1;
749 uint32_t totalLen = 0;
750 EXPECT_EQ(routeHeadHandlerImpl.PackData(dataBuffer, totalLen), false);
751 }
752
753 /**
754 * @tc.name: PackDataTest2
755 * @tc.desc: test headSize_ < sizeof(RouteHead).
756 * @tc.type: FUNC
757 * @tc.author: guochao
758 */
759 HWTEST_F(SessionManagerTest, PackDataTest2, TestSize.Level1)
760 {
761 ExtendInfo info;
762 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
763 routeHeadHandlerImpl.headSize_ = 10;
764 uint32_t totalLen = 11;
765 EXPECT_EQ(routeHeadHandlerImpl.PackData(dataBuffer, totalLen), false);
766 }
767
768 /**
769 * @tc.name: UnPackData_InvalidMagic
770 * @tc.desc: test invalid magic.
771 * @tc.type: FUNC
772 * @tc.author: guochao
773 */
774 HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1)
775 {
776 RouteHead *head = reinterpret_cast<RouteHead *>(dataBuffer);
777 head->magic = 0xFFFF;
778 ExtendInfo info;
779 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
780 uint32_t unpackedSize;
781 EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize));
782 }
783
784 /**
785 * @tc.name: UnPackData_VersionMismatch
786 * @tc.desc: test version mismatch.
787 * @tc.type: FUNC
788 * @tc.author: guochao
789 */
790 HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1)
791 {
792 RouteHead *head = reinterpret_cast<RouteHead *>(dataBuffer);
793 head->version = 0x00;
794 ExtendInfo info;
795 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
796 uint32_t unpackedSize;
797 EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize));
798 }
799
800 /**
801 * @tc.name: UnPackDataBody01
802 * @tc.desc: test leftSize < sizeof(SessionDevicePair).
803 * @tc.type: FUNC
804 * @tc.author: guochao
805 */
806 HWTEST_F(SessionManagerTest, UnPackDataBody01, TestSize.Level1)
807 {
808 ExtendInfo info;
809 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
810 uint32_t totalLen = 100;
811 auto res = routeHeadHandlerImpl.UnPackDataBody(dataBuffer, totalLen);
812 EXPECT_EQ(res, false);
813 }
814
815 /**
816 * @tc.name: UnPackDataBody02
817 * @tc.desc: test leftSize < sizeof(SessionUserPair).
818 * @tc.type: FUNC
819 * @tc.author: guochao
820 */
821 HWTEST_F(SessionManagerTest, UnPackDataBody02, TestSize.Level1)
822 {
823 ExtendInfo info;
824 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
825 uint32_t totalLen = 133;
826 auto res = routeHeadHandlerImpl.UnPackDataBody(dataBuffer, totalLen);
827 EXPECT_EQ(res, false);
828 }
829
830 /**
831 * @tc.name: UnPackDataBody03
832 * @tc.desc: test leftSize < userPairSize.
833 * @tc.type: FUNC
834 * @tc.author: guochao
835 */
836 HWTEST_F(SessionManagerTest, UnPackDataBody03, TestSize.Level1)
837 {
838 ExtendInfo info;
839 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
840 uint32_t totalLen = 136;
841 auto res = routeHeadHandlerImpl.UnPackDataBody(dataBuffer, totalLen);
842 EXPECT_EQ(res, false);
843 }
844
845 /**
846 * @tc.name: UnPackDataBody05
847 * @tc.desc: test leftSize < sizeof(SessionAppId).
848 * @tc.type: FUNC
849 * @tc.author: guochao
850 */
851 HWTEST_F(SessionManagerTest, UnPackDataBody05, TestSize.Level1)
852 {
853 ExtendInfo info;
854 RouteHeadHandlerImpl routeHeadHandlerImpl(info);
855 uint32_t totalLen = 400;
856 auto res = routeHeadHandlerImpl.UnPackDataBody(dataBuffer, totalLen);
857 EXPECT_EQ(res, false);
858 }
859
860 /**
861 * @tc.name: ShouldAddSystemUserWhenLocalUserIdIsSystem
862 * @tc.desc: test GetSession.
863 * @tc.type: FUNC
864 * @tc.author: guochao
865 */
866 HWTEST_F(SessionManagerTest, ShouldAddSystemUserWhenLocalUserIdIsSystem, TestSize.Level1)
867 {
868 SessionPoint local;
869 local.userId = UserDelegate::SYSTEM_USER;
870 local.appId = "ohos.test.demo";
871 local.deviceId = "local_device";
872 local.storeId = "test_store";
873
874 std::vector<UserStatus> users;
875 CreateUserStatus(users);
876 EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(users));
877 EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _))
878 .WillOnce(Return(std::pair(true, true)))
879 .WillOnce(Return(std::pair(true, false)))
880 .WillOnce(Return(std::pair(false, true)))
881 .WillOnce(Return(std::pair(false, false)));
882 Session session = SessionManager::GetInstance().GetSession(local, local.deviceId);
883 ASSERT_EQ(2, session.targetUserIds.size());
884 EXPECT_EQ(UserDelegate::SYSTEM_USER, session.targetUserIds[0]);
885 }
886
887 /**
888 * @tc.name: ShouldReturnEarlyWhenGetSendAuthParamsFails
889 * @tc.desc: test GetSession.
890 * @tc.type: FUNC
891 * @tc.author: guochao
892 */
893 HWTEST_F(SessionManagerTest, ShouldReturnEarlyWhenGetSendAuthParamsFails, TestSize.Level1)
894 {
895 SessionPoint local;
896 local.userId = 100;
897 local.appId = "test_app";
898 local.deviceId = "local_device";
899 EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(std::vector<UserStatus>{}));
900
901 Session session = SessionManager::GetInstance().GetSession(local, "target_device");
902
903 EXPECT_TRUE(session.targetUserIds.empty());
904 }
905
906 /**
907 * @tc.name: CheckSession
908 * @tc.desc: test CheckSession.
909 * @tc.type: FUNC
910 * @tc.author: guochao
911 */
912 HWTEST_F(SessionManagerTest, CheckSession, TestSize.Level1)
913 {
914 SessionPoint localSys;
915 localSys.userId = UserDelegate::SYSTEM_USER;
916 localSys.appId = "ohos.test.demo";
917 localSys.deviceId = "local_device";
918 localSys.storeId = "test_store";
919 SessionPoint localNormal;
920 localNormal.userId = 100;
921 localNormal.appId = "ohos.test.demo";
922 localNormal.deviceId = "local_device";
923 localNormal.storeId = "test_store";
924 localNormal.accountId = "test_account";
925 SessionPoint invalidPoint;
926 EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _))
927 .WillOnce(Return(std::pair(false, true)))
928 .WillOnce(Return(std::pair(true, false)));
929 bool result = SessionManager::GetInstance().CheckSession(invalidPoint, invalidPoint, true);
930 EXPECT_FALSE(result);
931 result = SessionManager::GetInstance().CheckSession(localSys, localNormal, true);
932 EXPECT_FALSE(result);
933 result = SessionManager::GetInstance().CheckSession(localNormal, localSys, true);
934 EXPECT_TRUE(result);
935 }
936 } // namespace