From e287facaee065a31e038008ca2fcecbcf5d10b26 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Sat, 30 Oct 2021 19:02:16 +0800 Subject: [PATCH] =?UTF-8?q?[L2=E7=BC=BA=E5=A4=B1=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E8=A1=A5=E9=BD=90]=E5=8D=B8=E8=BD=BD=E3=80=81=E5=A4=87?= =?UTF-8?q?=E4=BB=BD=E3=80=81=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zuojiangjiang --- .../src/client_permission_validator.cpp | 16 ++ .../src/client_permission_validator.h | 20 ++ .../app/src/backup_handler.cpp | 15 +- .../app/src/kvstore_data_service.cpp | 121 +++++---- .../app/src/kvstore_data_service.h | 6 + .../app/src/kvstore_impl.cpp | 3 +- .../app/src/kvstore_meta_manager.cpp | 41 ++- .../app/src/kvstore_meta_manager.h | 6 +- .../app/src/single_kvstore_impl.cpp | 2 +- .../app/src/uninstaller/uninstaller_impl.cpp | 5 +- .../app/src/uninstaller/uninstaller_impl.h | 7 +- .../app/test/unittest/kvstore_backup_test.cpp | 245 +++++++++++++++++- .../test/unittest/kvstore_data_service.cpp | 72 +++-- .../app/test/unittest/uninstaller_test.cpp | 2 +- 14 files changed, 433 insertions(+), 128 deletions(-) diff --git a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp index 0c8390ef2..5a9611c4f 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp @@ -22,6 +22,22 @@ namespace OHOS { namespace DistributedKv { +ClientPermissionChangedCallback::ClientPermissionChangedCallback(std::int32_t pid, std::int32_t uid) +{ + this->pid_ = pid; + this->uid_ = uid; +} + +std::int32_t ClientPermissionChangedCallback::GetPid() +{ + return this->pid_; +} + +void ClientPermissionChangedCallback::OnChanged(const int32_t uid) +{ + return; +} + void ClientPermissionValidator::UpdatePermissionStatus( int32_t uid, const std::string &permissionType, bool permissionStatus) { diff --git a/services/distributeddataservice/adapter/permission/src/client_permission_validator.h b/services/distributeddataservice/adapter/permission/src/client_permission_validator.h index eaece3cd6..d228d9be9 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.h +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.h @@ -20,12 +20,32 @@ #include #include #include +#include "bundlemgr/on_permission_changed_callback_host.h" namespace OHOS { namespace DistributedKv { const std::string DISTRIBUTED_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC"; +// Callback registered with BMS to listen App permission changes. +class ClientPermissionChangedCallback : public OnPermissionChangedCallbackHost { +public: + ClientPermissionChangedCallback(std::int32_t pid, std::int32_t uid); + + ~ClientPermissionChangedCallback() override = default; + + std::int32_t GetPid(); + + void OnChanged(const int32_t uid) override; +private: + std::int32_t pid_; + std::int32_t uid_; +}; + +struct AppPermissionInfo : AppThreadInfo { + sptr callback; +}; + class ClientPermissionValidator { public: static ClientPermissionValidator &GetInstance() diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index 85962c626..1639ca698 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -1,4 +1,4 @@ -/* + /* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ void BackupHandler::BackSchedule() } std::map results; ZLOGI("BackupHandler Schedule Every start."); - if (KvStoreMetaManager::GetInstance().GetFullMetaData(results)) { + if (!KvStoreMetaManager::GetInstance().GetFullMetaData(results)) { ZLOGE("GetFullMetaData failed."); return; } @@ -108,9 +108,7 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, metaData.kvStoreMetaData.bundleName, pathType); - delegateMgr->SetKvStoreConfig( - { Constant::Concatenate({appDataStoragePath, "/", metaData.kvStoreMetaData.bundleName })}); - + delegateMgr->SetKvStoreConfig({Constant::Concatenate({ appDataStoragePath })}); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreNbDelegate *delegate) { auto del = std::shared_ptr(delegateMgr); @@ -179,8 +177,7 @@ void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(metaData.kvStoreMetaData.bundleName)); std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, metaData.kvStoreMetaData.bundleName, pathType); - delegateMgr->SetKvStoreConfig( - {Constant::Concatenate({appDataStoragePath, "/", metaData.kvStoreMetaData.bundleName})}); + delegateMgr->SetKvStoreConfig({Constant::Concatenate({ appDataStoragePath })}); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreDelegate *delegate) { auto del = std::shared_ptr(delegateMgr); @@ -292,9 +289,9 @@ bool BackupHandler::MultiKvStoreRecover(MetaData &metaData, std::string BackupHandler::backupDirCe_; std::string BackupHandler::backupDirDe_; -const std::string &BackupHandler::GetBackupPath(const std::string &deviceAccountId, int type) +const std::string &BackupHandler::GetBackupPath(const std::string &deviceAccountId, int pathType) { - if (type == KvStoreAppManager::PATH_DE) { + if (pathType == KvStoreAppManager::PATH_DE) { if (backupDirDe_.empty()) { backupDirDe_ = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index d0d01d151..4053b32d0 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -206,27 +206,15 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId bool outdated = false; auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(deviceAccountId, bundleName, storeIdTmp); + auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } + auto getSecretKey = GetSecretKey(alreadyCreated, outdated, metaSecretKey, secretKey, secretKeyFile); + if (getSecretKey != Status::SUCCESS) { + callback(nullptr); + return getSecretKey; } } else { if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { @@ -274,10 +262,10 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId .kvStoreType = options.kvStoreType, .schema = options.schema, .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, + .userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName), .uid = IPCSkeleton::GetCallingUid(), .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, + .securityLevel = options.securityLevel, }; std::string jsonStr = metaData.Marshal(); std::vector jsonVec(jsonStr.begin(), jsonStr.end()); @@ -391,27 +379,15 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId bool outdated = false; auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(deviceAccountId, bundleName, storeIdTmp); + auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } + auto getSecretKey = GetSecretKey(alreadyCreated, outdated, metaSecretKey, secretKey, secretKeyFile); + if (getSecretKey != Status::SUCCESS) { + callback(nullptr); + return getSecretKey; } } else { if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { @@ -453,10 +429,10 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId .kvStoreType = options.kvStoreType, .schema = options.schema, .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, + .userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName), .uid = IPCSkeleton::GetCallingUid(), .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, + .securityLevel = options.securityLevel, }; std::string jsonStr = metaData.Marshal(); std::vector jsonVec(jsonStr.begin(), jsonStr.end()); @@ -791,15 +767,13 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor } auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) + BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", - BackupHandler::GetHashedBackupName(backupFileName) + BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); @@ -962,7 +936,11 @@ void KvStoreDataService::OnStart() return; } } + StartService(); +} +void KvStoreDataService::StartService() +{ // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { @@ -974,14 +952,20 @@ void KvStoreDataService::OnStart() // add softbus permission. AddPermission(); + std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, + KvStoreAppManager::PATH_DE); + ZLOGI("backupPath is : %s ", backupPath.c_str()); + if (!ForceCreateDirectory(backupPath)) { + ZLOE("backup create directory failed"); + } // Initialize meta db delegate manager. KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { if (!metaData.isDirty) { return; } - CloseKvStore({metaData.bundleName}, {metaData.storeId}); - DeleteKvStore({metaData.bundleName}, {metaData.storeId}); + CloseKvStore({ metaData.bundleName }, { metaData.storeId }); + DeleteKvStore({ metaData.bundleName }, { metaData.storeId }); }); // subscribe account event listener to EventNotificationMgr @@ -1006,13 +990,8 @@ void KvStoreDataService::OnStart() DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); backup_ = std::make_unique(this); - std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, - KvStoreAppManager::PATH_CE); - ZLOGI("backupPath is : %s ", backupPath.c_str()); - if (!ForceCreateDirectory(backupPath)) { - ZLOGE("backup create directory failed."); - } backup_->BackSchedule(); + std::thread th = std::thread([]() { sleep(TEN_SEC); KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); @@ -1102,6 +1081,34 @@ void KvStoreDataService::OnStop() } } +Status KvStoreDataService::GetSecretKey(Status alreadyCreated, bool &outdated, const std::vector &metaSecretKey, + std::vector &secretKey, const std::string &secretKeyFile) +{ + if (alreadyCreated != Status::SUCCESS) { + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGI("new secret key"); + CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length + KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + } + } else { + KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGW("get secret key from meta failed, try to recover"); + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + } + if (secretKey.empty()) { + ZLOGW("recover failed"); + return Status::CRYPT_ERROR; + } + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + } + return Status::SUCCESS; +} + KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl( const AppId &appId, KvStoreDataService &service, sptr observer) : appId_(appId), dataService_(service), observerProxy_(std::move(observer)), @@ -1231,12 +1238,12 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) deviceAccountMap_.erase(eventInfo.deviceAccountId); } std::string deviceAccountKvStoreDataDir = - Constant::Concatenate({Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, - "/", eventInfo.deviceAccountId}); + Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, + "/", eventInfo.deviceAccountId }); ForceRemoveDirectory(deviceAccountKvStoreDataDir); deviceAccountKvStoreDataDir = - Constant::Concatenate({Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, - "/", eventInfo.deviceAccountId}); + Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, + "/", eventInfo.deviceAccountId }); ForceRemoveDirectory(deviceAccountKvStoreDataDir); g_kvStoreAccountEventStatus = 0; break; @@ -1278,7 +1285,7 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); - deviceListeners_.insert({objectPtr, observer}); + deviceListeners_.insert({ objectPtr, observer }); ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index fcec10db5..18f367709 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -124,6 +124,12 @@ private: void Initialize(); + void StartService(); + + Status GetSecretKey(Status alreadyCreated, bool &outdated, const std::vector &metaSecretKey, + std::vector &secretKey, const std::string &secretKeyFile); + + Status AppExit(const AppId &appId); bool CheckBundleName(const std::string &bundleName) const; diff --git a/services/distributeddataservice/app/src/kvstore_impl.cpp b/services/distributeddataservice/app/src/kvstore_impl.cpp index 6ea4f718d..6b8acbafc 100755 --- a/services/distributeddataservice/app/src/kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/kvstore_impl.cpp @@ -780,7 +780,7 @@ bool KvStoreImpl::Import(const std::string &bundleName) const ZLOGI("KvStoreImpl Import start"); const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, - "SINGLE_KEY"); + "KEY"); std::vector secretKey; bool outdated = false; auto trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); @@ -792,6 +792,7 @@ bool KvStoreImpl::Import(const std::string &bundleName) const metaData.kvStoreMetaData.bundleName = bundleName; metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.storeId = storeId_; + metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; std::shared_lock lock(storeDelegateMutex_); return std::make_unique()->MultiKvStoreRecover(metaData, kvStoreDelegate_); diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 54417a641..4eb7f5354 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -32,6 +32,7 @@ #include "log_print.h" #include "reporter.h" #include "directory_utils.h" +#include "kvstore_app_manager.h" namespace OHOS { namespace DistributedKv { @@ -202,7 +203,7 @@ std::vector KvStoreMetaManager::GetMetaKey(const std::string &deviceAcc } std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId) + const std::string &storeId, int securityLevel) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -210,13 +211,15 @@ std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccoun ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - return Constant::ROOT_PATH_DE + "/" + Constant::SERVICE_NAME + "/" + + auto pathType = KvStoreAppManager::ConvertPathType(appId, securityLevel); + std::string miscPath = (pathType == KvStoreAppManager::PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + deviceAccountId + "/" + Constant::GetDefaultHarmonyAccountName() + "/" + appId + "/" + hashedStoreId + ".mul.key"; } std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId) + const std::string &storeId, int securityLevel) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -224,7 +227,9 @@ std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &device ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - return Constant::ROOT_PATH_DE + "/" + Constant::SERVICE_NAME + "/" + + auto pathType = KvStoreAppManager::ConvertPathType(appId, securityLevel); + std::string miscPath = (pathType == KvStoreAppManager::PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + deviceAccountId + "/" + Constant::GetDefaultHarmonyAccountName() + "/" + appId + "/" + hashedStoreId + ".sig.key"; } @@ -239,7 +244,7 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me return Status::DB_ERROR; } - KvStoreAppManager::PathType pathType = KvStoreAppManager::PATH_CE; + KvStoreAppManager::PathType pathType = KvStoreAppManager::PATH_DE; DistributedDB::Key dbKey = metaKey; DistributedDB::Value dbValue = val; DistributedDB::DBStatus dbStatus; @@ -533,13 +538,15 @@ Status KvStoreMetaManager::RemoveSecretKey(const std::string &deviceAccountId, c status = Status::DB_ERROR; } - std::string secretKeyFile = GetSecretKeyFile(deviceAccountId, bundleName, storeId); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + std::string secretKeyFile = GetSecretKeyFile(deviceAccountId, bundleName, storeId, securityLevel); bool rmFile = RemoveFile(secretKeyFile); if (!rmFile) { ZLOGW("remove secretKeyFile fail."); status = Status::DB_ERROR; } - secretKeyFile = GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId); + secretKeyFile = GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId, securityLevel); rmFile = RemoveFile(secretKeyFile); if (!rmFile) { ZLOGW("remove secretKeyFile Single fail."); @@ -632,7 +639,9 @@ void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::st WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "KEY"), key); Status status = kvStoreimpl->ReKey(key); if (status == Status::SUCCESS) { - WriteSecretKeyToFile(GetSecretKeyFile(deviceAccountId, bundleName, storeId), key); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + WriteSecretKeyToFile(GetSecretKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); } key.assign(key.size(), 0); } @@ -649,7 +658,9 @@ void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::st WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "SINGLE_KEY"), key); Status status = kvStoreImpl->ReKey(key); if (status == Status::SUCCESS) { - WriteSecretKeyToFile(GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId), key); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + WriteSecretKeyToFile(GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); } key.assign(key.size(), 0); } @@ -1222,6 +1233,18 @@ bool KvStoreMetaManager::GetFullMetaData(std::map &entrie return true; } +bool KvStoreMetaManager::GetSecurityLevelByBundleName(const std::string &bundleName, int &securityLevel) +{ + KvStoreMetaData kvStoreMetaData; + auto getKvStoreMetaBMeta = GetKvStoreMetaByType(KvStoreMetaData::BUNDLE_NAME, bundleName, kvStoreMetaData); + if (!getKvStoreMetaBMeta) { + ZLOGE("getkvstore meta by type failed"); + return false; + } + securityLevel = kvStoreMetaData.securityLevel; + return true; +} + bool KvStoreMetaManager::GetKvStoreMetaByType(const std::string &name, const std::string &val, KvStoreMetaData &metaData) { diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 05aa7bdf7..d54c3e01c 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -198,10 +198,10 @@ public: const std::string &storeId, const std::string &key = ""); static std::string GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId); + const std::string &storeId, int securityLevel); static std::string GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId); + const std::string &storeId, int securityLevel); Status GetSecretKeyFromMeta(const std::vector &metaSecretKey, std::vector &key, bool &outdated); @@ -269,6 +269,8 @@ private: Status GetStategyMeta(const std::string &key, std::map> &strategies); + bool GetSecurityLevelByBundleName(const std::string &bundleName, int &securityLevel); + bool GetKvStoreMetaByType(const std::string &name, const std::string &val, KvStoreMetaData &metaData); class KvStoreMetaObserver : public DistributedDB::KvStoreObserver { diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index c67beddd1..3d8143330 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -1391,6 +1391,7 @@ bool SingleKvStoreImpl::Import(const std::string &bundleName) const metaData.kvStoreMetaData.bundleName = bundleName; metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.storeId = storeId_; + metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; std::shared_lock lock(storeNbDelegateMutex_); return std::make_unique()->SingleKvStoreRecover(metaData, kvStoreNbDelegate_); @@ -1481,7 +1482,6 @@ Status SingleKvStoreImpl::GetSecurityLevel(SecurityLevel &securityLevel) } return Status::SUCCESS; } - void SingleKvStoreImpl::OnDump(int fd) const { const std::string prefix(12, ' '); diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp index 60104ce49..21af99766 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp @@ -91,16 +91,15 @@ Status UninstallerImpl::Init(KvStoreDataService *kvStoreDataService) matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); CommonEventSubscribeInfo info(matchingSkills); auto callback = [kvStoreDataService](const std::string &bundleName, int userId) { - ZLOGI("uninstalled bundleName:%s, userId:%d", bundleName.c_str(), userId); KvStoreMetaData kvStoreMetaData; if (!KvStoreMetaManager::GetInstance().GetKvStoreMetaDataByBundleName(bundleName, kvStoreMetaData)) { return; } if (!kvStoreMetaData.appId.empty() && !kvStoreMetaData.storeId.empty()) { ZLOGI("Has been uninstalled bundleName:%s", bundleName.c_str()); - AppId appid = {kvStoreMetaData.bundleName}; + AppId appId = {kvStoreMetaData.bundleName}; StoreId storeId = {kvStoreMetaData.storeId}; - kvStoreDataService->DeleteKvStore(appid, storeId, kvStoreMetaData.appId); + kvStoreDataService->DeleteKvStore(appId, storeId); } }; subscriber_ = std::make_shared(info, callback); diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h index a3c8bf064..b433152b1 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h @@ -20,16 +20,15 @@ #include "uninstaller.h" namespace OHOS::DistributedKv { -using namespace OHOS::EventFwk; using UninstallEventCallback = std::function; -class UninstallEventSubscriber : public CommonEventSubscriber { +class UninstallEventSubscriber : public EventFwk::CommonEventSubscriber { public: - UninstallEventSubscriber(const CommonEventSubscribeInfo &info, + UninstallEventSubscriber(const EventFwk::CommonEventSubscribeInfo &info, UninstallEventCallback callback); ~UninstallEventSubscriber() {}; - void OnReceiveEvent(const CommonEventData &event) override; + void OnReceiveEvent(const EventFwk::CommonEventData &event) override; private: static const std::string USER_ID; UninstallEventCallback callback_; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp index 01e88e6d2..7cbcbf2ff 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp @@ -49,10 +49,13 @@ void KvStoreBackupTest::TearDownTestCase(void) void KvStoreBackupTest::SetUp(void) { - const std::string backupDir = "/data/misc_ce/0/mdds/0/default/backup"; + const std::string backupDirCe = "/data/misc_ce/0/mdds/0/default/backup"; + unlink(backupDirCe.c_str()); + mkdir(backupDirCe.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); - unlink(backupDir.c_str()); - mkdir(backupDir.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); + const std::string backupDirDe = "/data/misc_de/0/mdds/0/default/backup"; + unlink(backupDirDe.c_str()); + mkdir(backupDirDe.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); } void KvStoreBackupTest::TearDown(void) @@ -75,7 +78,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest001, TestSize.Level1) kvDataService.DeleteKvStore(appId, storeId); sptr kvStorePtr; Status status = kvDataService.GetSingleKvStore(options, appId, storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest001 set backup true failed"; kvDataService.CloseKvStore(appId, storeId); } @@ -101,7 +104,6 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest002 set backup true failed"; - Key key1("test1_key"); Value value1("test1_value"); kvStorePtr->Put(key1, value1); @@ -113,10 +115,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); MetaData metaData{0}; metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = false; + metaData.kvStoreMetaData.isBackup = true; metaData.kvStoreType = KvStoreType::SINGLE_VERSION; backupHandler->SingleKvStoreBackup(metaData); @@ -124,14 +127,14 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) kvStorePtr->Delete(key2); Value value22; kvStorePtr->Get(key2, value22); - auto kptr = static_cast(kvStorePtr.GetRefPtr()); - kptr->Import(appId.appId); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest002 NO_LABEL single kvstore import failed"; kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest002 single kvstore backup failed"; kvDataService.CloseKvStore(appId, storeId); } - /** * @tc.name: KvStoreBackupTest003 * @tc.desc: kvstore backup test for multi db @@ -150,7 +153,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) kvDataService.DeleteKvStore(appId, storeId); sptr kvStorePtr; Status status = kvDataService.GetKvStore(options, appId, storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest003 set backup true failed"; @@ -166,10 +169,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) MetaData metaData{0}; metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = false; + metaData.kvStoreMetaData.isBackup = true; metaData.kvStoreType = KvStoreType::MULTI_VERSION; backupHandler->MultiKvStoreBackup(metaData); @@ -189,7 +193,222 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) Value value22; kvStoreSnapshotPtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest003 muti kvstore backup failed"; kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr)); kvDataService.CloseKvStore(appId, storeId); } +/** +* @tc.name: KvStoreBackupTest004 +* @tc.desc: kvstore backup delete test +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .autoSync = true, .backup = true, + .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup4" }; + StoreId storeId = { "store4" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest004 set backup true failed"; + + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + auto currentAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + auto backupFileName = Constant::Concatenate({ currentAccountId, "_", trueAppId, "_", storeId.storeId }); + auto backupFileNameHashed = BackupHandler::GetHashedBackupName(backupFileName); + auto pathType = KvStoreAppManager::ConvertPathType(appId.appId, metaData.kvStoreMetaData.securityLevel); + auto backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath("0", pathType), "/", backupFileNameHashed }); + bool ret = BackupHandler::FileExists(backFilePath); + EXPECT_EQ(ret, true) << "KvStoreBackupTest004 backup file failed"; + + kvDataService.CloseKvStore(appId, storeId); + kvDataService.DeleteKvStore(appId, storeId); + ret = BackupHandler::FileExists(backFilePath); + EXPECT_EQ(ret, false) << "KvStoreBackupTest004 delete backup file failed"; +} +/** +* @tc.name: KvStoreBackupTest005 +* @tc.desc: S0 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest005, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S0, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup5" }; + StoreId storeId = { "store5" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest005 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S0; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest005 S0 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest005 S0 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} +/** +* @tc.name: KvStoreBackupTest006 +* @tc.desc: S2 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest006, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S2, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup6" }; + StoreId storeId = { "store6" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest006 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S2; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest006 S2 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest006 S2 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} +/** +* @tc.name: KvStoreBackupTest007 +* @tc.desc: S4 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest007, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S4, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup7" }; + StoreId storeId = { "store7" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest007 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appId.appId); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S4; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest007 S4 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest007 S0 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} \ No newline at end of file diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp index c5ee3beea..7dfc29971 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -202,15 +202,20 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId bool outdated = false; auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(deviceAccountId, bundleName, storeIdTmp); + auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGI("new secret key"); + CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length + KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + } } else { KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); if (secretKey.empty()) { @@ -223,6 +228,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId callback(nullptr); return Status::CRYPT_ERROR; } + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); } } else { if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { @@ -270,10 +276,10 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId .kvStoreType = options.kvStoreType, .schema = options.schema, .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, + .userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName), .uid = IPCSkeleton::GetCallingUid(), .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, + .securityLevel = options.securityLevel, }; std::string jsonStr = metaData.Marshal(); std::vector jsonVec(jsonStr.begin(), jsonStr.end()); @@ -388,15 +394,20 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId bool outdated = false; auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(deviceAccountId, bundleName, storeIdTmp); + auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGI("new secret key"); + CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length + KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); + } } else { KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); if (secretKey.empty()) { @@ -409,6 +420,7 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId callback(nullptr); return Status::CRYPT_ERROR; } + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); } } else { if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { @@ -450,10 +462,10 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId .kvStoreType = options.kvStoreType, .schema = options.schema, .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, + .userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName), .uid = IPCSkeleton::GetCallingUid(), .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, + .securityLevel = options.securityLevel, }; std::string jsonStr = metaData.Marshal(); std::vector jsonVec(jsonStr.begin(), jsonStr.end()); @@ -792,15 +804,13 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor } auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) + BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", - BackupHandler::GetHashedBackupName(backupFileName) + BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); @@ -940,24 +950,36 @@ void KvStoreDataService::OnStart() return; } } + StartService(); +} +void KvStoreDataService::StartService() +{ // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { FaultMsg msg = {FaultType::SERVICE_FAULT, "service", __FUNCTION__, Fault::SF_SERVICE_PUBLISH}; Reporter::GetInstance()->ServiceFault()->Report(msg); } - Uninstaller::GetInstance().Init(this); + // add softbus permission. + AddPermission(); + + std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, + KvStoreAppManager::PATH_DE); + ZLOGI("backupPath is : %s ", backupPath.c_str()); + if (!ForceCreateDirectory(backupPath)) { + ZLOE("backup create directory failed"); + } // Initialize meta db delegate manager. KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { if (!metaData.isDirty) { return; } - CloseKvStore({metaData.bundleName}, {metaData.storeId}); - DeleteKvStore({metaData.bundleName}, {metaData.storeId}); + CloseKvStore({ metaData.bundleName }, { metaData.storeId }); + DeleteKvStore({ metaData.bundleName }, { metaData.storeId }); }); // subscribe account event listener to EventNotificationMgr @@ -973,7 +995,6 @@ void KvStoreDataService::OnStart() if (dbStatus != DistributedDB::DBStatus::OK) { ZLOGE("SetPermissionCheck callback failed."); } - ZLOGI("autoLaunchRequestCallback start"); auto autoLaunchRequestCallback = [this](const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) -> bool { @@ -983,13 +1004,8 @@ void KvStoreDataService::OnStart() DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); backup_ = std::make_unique(this); - std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, - KvStoreAppManager::PATH_CE); - ZLOGI("backupPath is : %s ", backupPath.c_str()); - if (!ForceCreateDirectory(backupPath)) { - ZLOGE("backup create directory failed."); - } backup_->BackSchedule(); + std::thread th = std::thread([]() { sleep(TEN_SEC); KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); diff --git a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp index 48972cc05..fd385ec70 100755 --- a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp +++ b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp @@ -50,4 +50,4 @@ HWTEST_F(UninstallerTest, Test001, TestSize.Level0) { auto &unin = Uninstaller::GetInstance(); unin.Init(nullptr); -} +} \ No newline at end of file -- Gitee