From 226546ad12dab1990e3a9212e91f351aee60b689 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Tue, 19 Oct 2021 22:16:56 +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=A4=87=E4=BB=BD=E3=80=81=E5=8D=B8?= =?UTF-8?q?=E8=BD=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 --- .../app/src/backup_handler.cpp | 12 +- .../app/src/kvstore_data_service.cpp | 55 ++-- .../app/src/kvstore_impl.cpp | 3 +- .../app/src/kvstore_meta_manager.cpp | 46 +++- .../app/src/kvstore_meta_manager.h | 6 +- .../app/src/single_kvstore_impl.cpp | 2 +- .../app/src/uninstaller/uninstaller.cpp | 14 +- .../app/src/uninstaller/uninstaller.h | 5 +- .../app/src/uninstaller/uninstaller_impl.cpp | 4 +- .../app/src/uninstaller/uninstaller_impl.h | 7 +- .../app/test/unittest/kvstore_backup_test.cpp | 245 +++++++++++++++++- .../test/unittest/kvstore_data_service.cpp | 91 ++++--- .../app/test/unittest/uninstaller_test.cpp | 7 +- 13 files changed, 393 insertions(+), 104 deletions(-) diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index 85962c626..fdd01566f 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -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,8 +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) { @@ -179,8 +178,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 +290,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..1dc700a90 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -206,15 +206,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()) { @@ -227,6 +232,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)) { @@ -274,10 +280,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,15 +397,19 @@ 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()) { @@ -412,6 +422,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)) { @@ -453,10 +464,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()); @@ -534,7 +545,7 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId { auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); auto backupFileName = Constant::Concatenate({ Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId }); - auto backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, pathType), + auto backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, pathType), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::FileExists(backFilePath)) { ZLOGE("BackupHandler file is not exist."); @@ -791,14 +802,14 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor } auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", + 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::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { @@ -962,14 +973,14 @@ void KvStoreDataService::OnStart() return; } } - // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { + ZLOGE("publish SystemAbility fail"); FaultMsg msg = {FaultType::SERVICE_FAULT, "service", __FUNCTION__, Fault::SF_SERVICE_PUBLISH}; Reporter::GetInstance()->ServiceFault()->Report(msg); } - Uninstaller::GetInstance().Init(this); + Uninstaller::GetInstance()->Init(this); // add softbus permission. AddPermission(); @@ -980,8 +991,8 @@ void KvStoreDataService::OnStart() 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 @@ -1278,7 +1289,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_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..da1320e21 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(bundleName, 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(bundleName, 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,6 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me return Status::DB_ERROR; } - KvStoreAppManager::PathType pathType = KvStoreAppManager::PATH_CE; DistributedDB::Key dbKey = metaKey; DistributedDB::Value dbValue = val; DistributedDB::DBStatus dbStatus; @@ -248,22 +252,18 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me switch (flag) { case UPDATE: dbStatus = metaDelegate->Put(dbKey, dbValue); - metaDelegate->Export(BackupHandler::GetBackupPath(deviceAccountId, pathType), dbPassword); break; case DELETE: dbStatus = metaDelegate->Delete(dbKey); - metaDelegate->Export(BackupHandler::GetBackupPath(deviceAccountId, pathType), dbPassword); break; case CHECK_EXIST: dbStatus = metaDelegate->Get(dbKey, dbValue); break; case UPDATE_LOCAL: dbStatus = metaDelegate->PutLocal(dbKey, dbValue); - metaDelegate->Export(BackupHandler::GetBackupPath(deviceAccountId, pathType), dbPassword); break; case DELETE_LOCAL: dbStatus = metaDelegate->DeleteLocal(dbKey); - metaDelegate->Export(BackupHandler::GetBackupPath(deviceAccountId, pathType), dbPassword); break; case CHECK_EXIST_LOCAL: dbStatus = metaDelegate->GetLocal(dbKey, dbValue); @@ -533,13 +533,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 +634,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 +653,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 +1228,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) { @@ -1230,7 +1248,7 @@ bool KvStoreMetaManager::GetKvStoreMetaByType(const std::string &name, const std return false; } - DistributedDB::Key metaKeyPrefix = KvStoreMetaRow::GetKeyFor(KvStoreMetaRow::KEY_PREFIX); + DistributedDB::Key metaKeyPrefix = KvStoreMetaRow::GetKeyFor(""); std::vector metaEntries; DistributedDB::DBStatus dbStatus = metaDelegate->GetEntries(metaKeyPrefix, metaEntries); if (dbStatus != DistributedDB::DBStatus::OK) { 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.cpp b/services/distributeddataservice/app/src/uninstaller/uninstaller.cpp index 5cdf855f9..4f3d45d5c 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller.cpp +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller.cpp @@ -17,9 +17,17 @@ #include "uninstaller_impl.h" namespace OHOS::DistributedKv { -Uninstaller &Uninstaller::GetInstance() +std::mutex Uninstaller::mutex_; +std::shared_ptr Uninstaller::uninstallerInstance_; +std::shared_ptr Uninstaller::GetInstance() { - static UninstallerImpl uninstaller; - return uninstaller; + if (uninstallerInstance_ == nullptr) { + std::lock_guard lg(mutex_); + if (uninstallerInstance_ == nullptr) { + auto delegate = std::make_shared(); + uninstallerInstance_ = std::dynamic_pointer_cast(delegate); + } + } + return uninstallerInstance_; } } diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller.h b/services/distributeddataservice/app/src/uninstaller/uninstaller.h index 8895d473e..f5bbc178f 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller.h +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller.h @@ -27,7 +27,10 @@ class Uninstaller { public: KVSTORE_API virtual Status Init(KvStoreDataService *kvStoreDataService) = 0; KVSTORE_API virtual ~Uninstaller() {}; - KVSTORE_API static Uninstaller &GetInstance(); + KVSTORE_API static std::shared_ptr GetInstance(); +private: + static std::mutex mutex_; + static std::shared_ptr uninstallerInstance_; }; } #endif // DISTRIBUTEDDATAMGR_UNINSTALLER_H diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp index 60104ce49..ed72fc3db 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp @@ -98,9 +98,9 @@ Status UninstallerImpl::Init(KvStoreDataService *kvStoreDataService) } 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..1f55886fb 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -32,12 +32,15 @@ #include "dds_trace.h" #include "device_change_listener_impl.h" #include "device_kvstore_impl.h" +#include "if_system_ability_manager.h" #include "iservice_registry.h" #include "kvstore_account_observer.h" #include "kvstore_app_accessor.h" #include "kvstore_meta_manager.h" #include "kvstore_utils.h" #include "log_print.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" #include "permission_validator.h" #include "process_communicator_impl.h" #include "reporter.h" @@ -48,6 +51,7 @@ namespace OHOS { namespace DistributedKv { using json = nlohmann::json; using namespace std::chrono; +using namespace OHOS::Security::Permission; REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true); @@ -86,6 +90,7 @@ void KvStoreDataService::Initialize() ZLOGI("begin."); KvStoreMetaManager::GetInstance().InitMetaParameter(); std::thread th = std::thread([]() { + DistributedDB::KvStoreDelegateManager::SetProcessLabel(Constant::PROCESS_LABEL, "default"); auto communicator = std::make_shared(); auto ret = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); ZLOGI("set communicator ret:%d.", static_cast(ret)); @@ -142,7 +147,6 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId { ZLOGI("begin."); DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (callback == nullptr) { ZLOGW("callback is nullptr"); return Status::ERROR; @@ -202,15 +206,18 @@ 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 +230,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 +278,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()); @@ -328,7 +336,6 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId std::function)> callback) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("begin."); if (callback == nullptr) { ZLOGW("callback is nullptr"); @@ -388,15 +395,18 @@ 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 +419,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 +461,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()); @@ -626,7 +637,6 @@ void KvStoreDataService::GetAllKvStoreId( const AppId &appId, std::function &)> callback) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("GetAllKvStoreId begin."); std::string bundleName = Constant::TrimCopy(appId.appId); std::vector storeIdList; @@ -693,7 +703,6 @@ void KvStoreDataService::GetAllKvStoreId( Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &storeId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("begin."); std::string bundleName = Constant::TrimCopy(appId.appId); std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); @@ -736,7 +745,6 @@ Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &store Status KvStoreDataService::CloseAllKvStore(const AppId &appId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGD("begin."); std::string bundleName = Constant::TrimCopy(appId.appId); if (!CheckBundleName(bundleName)) { @@ -768,7 +776,6 @@ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &storeId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - std::string bundleName = appId.appId; if (!CheckBundleName(bundleName)) { ZLOGE("invalid bundleName."); @@ -819,12 +826,10 @@ Status KvStoreDataService::DeleteAllKvStore(const AppId &appId) ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - if (KvStoreUtils::GetAppIdByBundleName(bundleName).empty()) { ZLOGE("invalid appId."); return Status::PERMISSION_DENIED; } - Status statusTmp; std::vector existStoreIds; GetAllKvStoreId(appId, [&statusTmp, &existStoreIds](Status status, std::vector &storeIds) { @@ -858,12 +863,10 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); if (trueAppId.empty()) { return Status::PERMISSION_DENIED; } - std::lock_guard lg(clientDeathObserverMutex_); auto it = clientDeathObserverMap_.emplace(std::piecewise_construct, std::forward_as_tuple(bundleName), std::forward_as_tuple(appId, *this, std::move(observer))); @@ -873,7 +876,6 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< return Status::ERROR; } ZLOGI("insert success"); - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); KvStoreTuple kvStoreTuple {userId, trueAppId}; AppThreadInfo appThreadInfo {IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()}; @@ -921,12 +923,40 @@ int KvStoreDataService::Dump(int fd, const std::vector &args) dprintf(fd, "------------------------------------------------------------------\n"); dprintf(fd, "DeviceAccount count : %u\n", static_cast(deviceAccountMap_.size())); for (const auto &pair : deviceAccountMap_) { - dprintf(fd, "DeviceAccountID : %s\n", pair.first.c_str()); + dprintf(fd, "DeviceAccountID : %s\n", KvStoreUtils::GetAppIdByBundleName(pair.first).c_str()); pair.second.Dump(fd); } return 0; } +const std::string PKGNAME = "ohos.distributeddata"; +const std::string APP_DATASYNC_PERMISSION = "ohos.permission.DISTRIBUTED_DATASYNC"; +const std::string LABEL = "distributeddata"; +const std::string DESCRIPTION = "distributeddata service"; +const int LABEL_ID = 9527; +const int DESCRIPTION_ID = 9528; + +void KvStoreDataService::AddPermission() const +{ + std::vector permissionDefs { + { + .permissionName = APP_DATASYNC_PERMISSION, + .bundleName = PKGNAME, + .grantMode = GrantMode::SYSTEM_GRANT, + .availableScope = AVAILABLE_SCOPE_ALL, + .label = LABEL, + .labelId = LABEL_ID, + .description = DESCRIPTION, + .descriptionId = DESCRIPTION_ID + } + }; + PermissionKit::AddDefPermissions(permissionDefs); + std::vector permissions; + permissions.push_back(APP_DATASYNC_PERMISSION); + PermissionKit::AddSystemGrantedReqPermissions(PKGNAME, permissions); + PermissionKit::GrantSystemGrantedPermission(PKGNAME, APP_DATASYNC_PERMISSION); +} + void KvStoreDataService::OnStart() { ZLOGI("distributeddata service onStart"); @@ -940,15 +970,17 @@ void KvStoreDataService::OnStart() return; } } - // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { + ZLOGE("publish SystemAbility fail"); FaultMsg msg = {FaultType::SERVICE_FAULT, "service", __FUNCTION__, Fault::SF_SERVICE_PUBLISH}; Reporter::GetInstance()->ServiceFault()->Report(msg); } + Uninstaller::GetInstance()->Init(this); - Uninstaller::GetInstance().Init(this); + // add softbus permission. + AddPermission(); // Initialize meta db delegate manager. KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { @@ -973,7 +1005,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 { @@ -1051,7 +1082,6 @@ bool KvStoreDataService::CheckPermissions(const std::string &userId, const std:: ZLOGD("default, dont check sync permission."); return true; } - Status status = instance.CheckSyncPermission(userId, appId, storeId, flag, deviceId); if (status != Status::SUCCESS) { ZLOGW("PermissionCheck failed."); @@ -1142,7 +1172,6 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor ZLOGE("invalid storeIdTmp."); return Status::INVALID_ARGUMENT; } - const int32_t uid = IPCSkeleton::GetCallingUid(); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { diff --git a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp index 48972cc05..236644b94 100755 --- a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp +++ b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp @@ -48,6 +48,7 @@ void UninstallerTest::TearDown(void) */ HWTEST_F(UninstallerTest, Test001, TestSize.Level0) { - auto &unin = Uninstaller::GetInstance(); - unin.Init(nullptr); -} + auto unin = Uninstaller::GetInstance(); + ASSERT_TRUE(unin != nullptr) << "UninstallerTest001 get uninstaller instance failed"; + unin->Init(nullptr); +} \ No newline at end of file -- Gitee