From b26d3a1071f9c80adb60924ebd82c03e430081cb Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 1 Nov 2021 20:16:02 +0800 Subject: [PATCH] fix the Backup,broadcast,uninstaller,encryption function Signed-off-by: zuojiangjiang --- .../src/client_permission_validator.cpp | 16 + .../src/client_permission_validator.h | 22 +- .../app/src/backup_handler.cpp | 32 +- .../app/src/kvstore_data_service.cpp | 276 +++++++++--------- .../app/src/kvstore_data_service.h | 18 +- .../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 | 246 +++++++++++++++- .../test/unittest/kvstore_data_service.cpp | 251 ++++++++-------- 13 files changed, 589 insertions(+), 336 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..b004c9376 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) +{ + +} + 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..b31bcc902 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.h +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.h @@ -16,16 +16,36 @@ #ifndef CLIENT_PERMISSION_VALIDATOR_H #define CLIENT_PERMISSION_VALIDATOR_H -#include "permission_validator.h" #include #include #include +#include "bundlemgr/on_permission_changed_callback_host.h" +#include "permission_validator.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 AppExecFwk::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..0fe5f1a64 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,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); @@ -129,13 +127,10 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) ZLOGW("SingleKvStoreBackup export"); if (status == DistributedDB::DBStatus::OK) { - std::string backupName = Constant::Concatenate( - { metaData.kvStoreMetaData.userId, "_", metaData.kvStoreMetaData.appId, "_", - metaData.kvStoreMetaData.storeId }); - auto backupFullName = Constant::Concatenate({ - BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName) - }); + std::string backupName = Constant::Concatenate({ metaData.kvStoreMetaData.userId, "_", + metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId }); + auto backupFullName = Constant::Concatenate({ BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), + "/", GetHashedBackupName(backupName) }); auto backupBackFullName = Constant::Concatenate({ backupFullName, ".", "backup" }); RenameFile(backupFullName, backupBackFullName); status = delegate->Export(backupFullName, dbOption.passwd); @@ -154,8 +149,8 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) { - auto pathType = KvStoreAppManager::ConvertPathType(metaData.kvStoreMetaData.bundleName, - metaData.kvStoreMetaData.securityLevel); + auto pathType = KvStoreAppManager::ConvertPathType( + metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { ZLOGE("MultiKvStoreBackup backup create directory failed."); return; @@ -179,8 +174,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); @@ -191,8 +185,8 @@ void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) ZLOGW("MultiKvStoreBackup export"); if (status == DistributedDB::DBStatus::OK) { std::string backupName = - Constant::Concatenate({metaData.kvStoreMetaData.userId, "_", - metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId}); + Constant::Concatenate({ metaData.kvStoreMetaData.userId, "_", + metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId }); auto backupFullName = Constant::Concatenate({ BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", GetHashedBackupName(backupName) @@ -292,9 +286,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..e949824a2 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -151,48 +151,17 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION && - kvStoreType != KvStoreType::MULTI_VERSION) { - ZLOGE("invalid kvStore type."); + std::string deviceAccountId; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, deviceAccountId); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); std::string bundleName = Constant::TrimCopy(appId.appId); std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); - callback(nullptr); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { @@ -206,27 +175,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 +231,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()); @@ -322,7 +279,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId return Status::DB_ERROR; } // recover database - return RecoverMultiKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverMultiKvStore(options, bundleName, storeId, secretKey, callback); } return statusTmp; @@ -337,46 +294,17 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION) { - ZLOGE("invalid kvStore type."); + std::string deviceAccountId; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::SINGLE_VERSION, deviceAccountId); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + std::string bundleName = Constant::TrimCopy(appId.appId); std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - callback(nullptr); - ZLOGW("appId empty(permission issues?)"); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { @@ -384,6 +312,7 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId ZLOGE("encrypt type or kvStore type is not the same"); return Status::INVALID_ARGUMENT; } + std::vector secretKey; std::unique_ptr, void (*)(std::vector *)> cleanGuard( &secretKey, [](std::vector *ptr) { ptr->assign(ptr->size(), 0); }); @@ -391,27 +320,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 +370,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()); @@ -494,11 +411,52 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId return Status::DB_ERROR; } // recover database - return RecoverSingleKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverSingleKvStore(options, bundleName, storeId, secretKey, callback); } return statusTmp; } +Status KvStoreDataService::CheckParameters(const Options &options, const AppId &appId, + const StoreId &storeId, const KvStoreType kvStoreType,std::string &deviceAccountId) +{ + if (appId.appId.empty() || storeId.storeId.empty()) { + ZLOGW("appid or storeid empty"); + return Status::INVALID_ARGUMENT; + } + + KvStoreType kvStoreTypeInOptions = options.kvStoreType; + if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { + ZLOGE("invalid kvStore type."); + return Status::INVALID_ARGUMENT; + } + KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + std::string bundleName = Constant::TrimCopy(appId.appId); + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + if (!CheckBundleName(bundleName)) { + ZLOGE("invalid bundleName."); + return Status::INVALID_ARGUMENT; + } + if (!CheckStoreId(storeIdTmp)) { + ZLOGE("invalid storeIdTmp."); + return Status::INVALID_ARGUMENT; + } + + std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + if (trueAppId.empty()) { + ZLOGW("appId empty(permission issues?)"); + return Status::PERMISSION_DENIED; + } + + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string devAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (devAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; + } + deviceAccountId = devAccountId; + return Status::SUCCESS; +} + bool KvStoreDataService::CheckOptions(const Options &options, const std::vector &metaKey) const { ZLOGI("begin."); @@ -535,7 +493,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), - "/", BackupHandler::GetHashedBackupName(backupFileName) }); + "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::FileExists(backFilePath)) { ZLOGE("BackupHandler file is not exist."); return false; @@ -544,7 +502,6 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId } Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, const StoreId &storeId, const std::vector &secretKey, @@ -556,6 +513,8 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -584,7 +543,6 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, } Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, const StoreId &storeId, const std::vector &secretKey, @@ -596,6 +554,8 @@ Status KvStoreDataService::RecoverMultiKvStore(const Options &options, Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -625,8 +585,7 @@ Status KvStoreDataService::RecoverMultiKvStore(const Options &options, return Status::RECOVER_SUCCESS; } -void KvStoreDataService::GetAllKvStoreId( - const AppId &appId, std::function &)> callback) +void KvStoreDataService::GetAllKvStoreId(const AppId &appId, std::function &)> callback) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGI("GetAllKvStoreId begin."); @@ -660,11 +619,8 @@ void KvStoreDataService::GetAllKvStoreId( } std::vector dbEntries; DistributedDB::DBStatus dbStatus; - DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor( - DeviceKvStoreImpl::GetLocalDeviceId() + Constant::KEY_SEPARATOR + - deviceAccountId + Constant::KEY_SEPARATOR + - "default" + Constant::KEY_SEPARATOR + - bundleName + Constant::KEY_SEPARATOR); + DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor(DeviceKvStoreImpl::GetLocalDeviceId() + Constant::KEY_SEPARATOR + + deviceAccountId + Constant::KEY_SEPARATOR +"default" + Constant::KEY_SEPARATOR + bundleName + Constant::KEY_SEPARATOR); { DdsTrace trace(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); dbStatus = metaKvStoreDelegate->GetEntries(dbKey, dbEntries); @@ -790,17 +746,13 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::NOT_SUPPORT; } - auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + auto backFilePath = Constant::Concatenate({ 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) - }); + backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), + "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } @@ -962,7 +914,11 @@ void KvStoreDataService::OnStart() return; } } + StartService(); +} +void KvStoreDataService::StartService() +{ // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { @@ -974,14 +930,19 @@ 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)) { + ZLOGE("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 +967,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 +1058,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 +1215,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; @@ -1251,15 +1235,15 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) Status KvStoreDataService::GetLocalDevice(DeviceInfo &device) { auto tmpDevice = KvStoreUtils::GetProviderInstance().GetLocalBasicInfo(); - device = {tmpDevice.deviceId, tmpDevice.deviceName, tmpDevice.deviceType}; + device = { tmpDevice.deviceId, tmpDevice.deviceName, tmpDevice.deviceType }; return Status::SUCCESS; } Status KvStoreDataService::GetDeviceList(std::vector &deviceInfoList, DeviceFilterStrategy strategy) { auto devices = KvStoreUtils::GetProviderInstance().GetRemoteNodesBasicInfo(); - for(auto const &device : devices) { - deviceInfoList.push_back({device.deviceId, device.deviceName, device.deviceType}); + for (auto const &device : devices) { + deviceInfoList.push_back({ device.deviceId, device.deviceName, device.deviceType }); } ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; @@ -1278,7 +1262,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..3d63dcf42 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -87,14 +87,12 @@ public: bool CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, int securityLevel); - Status RecoverSingleKvStore(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const StoreId &storeId, - const std::vector &secretKey, + Status RecoverSingleKvStore(const Options &options, const std::string &bundleName, + const StoreId &storeId, const std::vector &secretKey, std::function)> callback); - Status RecoverMultiKvStore(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const StoreId &storeId, - const std::vector &secretKey, + Status RecoverMultiKvStore(const Options &options, const std::string &bundleName, + const StoreId &storeId, const std::vector &secretKey, std::function)> callback); private: class KvStoreClientDeathObserverImpl { @@ -124,6 +122,14 @@ private: void Initialize(); + void StartService(); + + Status GetSecretKey(Status alreadyCreated, bool &outdated, const std::vector &metaSecretKey, + std::vector &secretKey, const std::string &secretKeyFile); + + Status CheckParameters(const Options &options, const AppId &appId, const StoreId &storeId, + const KvStoreType kvStoreType, std::string &deviceAccountId); + 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..eea3cb800 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,223 @@ 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..53344d96a 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -147,48 +147,17 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION && - kvStoreType != KvStoreType::MULTI_VERSION) { - ZLOGE("invalid kvStore type."); + std::string deviceAccountId; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, deviceAccountId); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); std::string bundleName = Constant::TrimCopy(appId.appId); std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); - callback(nullptr); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { @@ -202,27 +171,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)) { @@ -270,10 +227,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()); @@ -318,7 +275,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId return Status::DB_ERROR; } // recover database - return RecoverMultiKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverMultiKvStore(options, bundleName, storeId, secretKey, callback); } return statusTmp; @@ -334,46 +291,17 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION) { - ZLOGE("invalid kvStore type."); + std::string deviceAccountId; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::SINGLE_VERSION, deviceAccountId); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + std::string bundleName = Constant::TrimCopy(appId.appId); std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - callback(nullptr); - ZLOGW("appId empty(permission issues?)"); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { @@ -388,27 +316,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)) { @@ -450,10 +366,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()); @@ -491,11 +407,52 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId return Status::DB_ERROR; } // recover database - return RecoverSingleKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverSingleKvStore(options, bundleName, storeId, secretKey, callback); } return statusTmp; } +Status KvStoreDataService::CheckParameters(const Options &options, const AppId &appId, + const StoreId &storeId, const KvStoreType kvStoreType, std::string &deviceAccountId) +{ + if (appId.appId.empty() || storeId.storeId.empty()) { + ZLOGW("appid or storeid empty"); + return Status::INVALID_ARGUMENT; + } + + KvStoreType kvStoreTypeInOptions = options.kvStoreType; + if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { + ZLOGE("invalid kvStore type."); + return Status::INVALID_ARGUMENT; + } + KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + std::string bundleName = Constant::TrimCopy(appId.appId); + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + if (!CheckBundleName(bundleName)) { + ZLOGE("invalid bundleName."); + return Status::INVALID_ARGUMENT; + } + if (!CheckStoreId(storeIdTmp)) { + ZLOGE("invalid storeIdTmp."); + return Status::INVALID_ARGUMENT; + } + + std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + if (trueAppId.empty()) { + ZLOGW("appId empty(permission issues?)"); + return Status::PERMISSION_DENIED; + } + + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string devAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (devAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; + } + deviceAccountId = devAccountId; + return Status::SUCCESS; +} + bool KvStoreDataService::CheckOptions(const Options &options, const std::vector &metaKey) const { ZLOGI("begin."); @@ -541,7 +498,6 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId } Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, const StoreId &storeId, const std::vector &secretKey, @@ -553,6 +509,8 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -581,7 +539,6 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, } Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, const StoreId &storeId, const std::vector &secretKey, @@ -593,6 +550,8 @@ Status KvStoreDataService::RecoverMultiKvStore(const Options &options, Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -791,17 +750,13 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::NOT_SUPPORT; } - auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + auto backFilePath = Constant::Concatenate({ 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) - }); + backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), + "/", BackupHandler::GetHashedBackupName(backupFileName) }); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } @@ -940,24 +895,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)) { + ZLOGE("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 +940,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 +949,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(); @@ -1080,6 +1041,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)), -- Gitee