diff --git a/services/distributeddataservice/adapter/permission/src/media_lib_checker.cpp b/services/distributeddataservice/adapter/permission/src/media_lib_checker.cpp index 96107ebf5c26021858081fb709ad38f0657ec38c..85cbfd3b964cd340205697975bb157a6f0ebb00d 100644 --- a/services/distributeddataservice/adapter/permission/src/media_lib_checker.cpp +++ b/services/distributeddataservice/adapter/permission/src/media_lib_checker.cpp @@ -12,20 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "media_lib_checker.h" - #define LOG_TAG "MediaLibChecker" +#include "media_lib_checker.h" #include -#include "bundlemgr/bundle_mgr_client.h" +#include "accesstoken_kit.h" +#include "hap_token_info.h" #include "log/log_print.h" #include "utils/crypto.h" namespace OHOS { namespace DistributedData { -using namespace AppExecFwk; +using namespace Security::AccessToken; MediaLibChecker MediaLibChecker::instance_; -constexpr pid_t MediaLibChecker::SYSTEM_UID; MediaLibChecker::MediaLibChecker() noexcept { CheckerManager::GetInstance().RegisterPlugin( @@ -44,35 +42,28 @@ bool MediaLibChecker::SetTrustInfo(const CheckerManager::Trust &trust) return true; } -std::string MediaLibChecker::GetAppId(pid_t uid, const std::string &bundleName) +std::string MediaLibChecker::GetAppId(const CheckerManager::StoreInfo &info) { - if (!IsValid(uid, bundleName)) { + if (!IsValid(info)) { return ""; } - BundleMgrClient bmsClient; - std::string orionBundle; - (void)bmsClient.GetBundleNameForUid(uid, orionBundle); - auto bundleInfo = std::make_unique(); - auto success = bmsClient.GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, - *bundleInfo, Constants::ANY_USERID); - if (!success) { + + HapTokenInfo hapTokenInfo; + auto success = AccessTokenKit::GetHapTokenInfo(info.tokenId, hapTokenInfo); + if (success != RET_SUCCESS || info.bundleName != hapTokenInfo.bundleName) { return ""; } - ZLOGD("orion: %{public}s, uid: %{public}d, bundle: %{public}s appId: %{public}s", orionBundle.c_str(), uid, - bundleName.c_str(), bundleInfo->appId.c_str()); - return Crypto::Sha256(bundleInfo->appId); + ZLOGD("bundleName:%{public}s, uid:%{public}d, token:%{public}u, appId:%{public}s", + info.bundleName.c_str(), info.uid, info.tokenId, hapTokenInfo.appID.c_str()); + return Crypto::Sha256(hapTokenInfo.appID); } -bool MediaLibChecker::IsValid(pid_t uid, const std::string &bundleName) +bool MediaLibChecker::IsValid(const CheckerManager::StoreInfo &info) { - if (trusts_.find(bundleName) == trusts_.end()) { + if (trusts_.find(info.bundleName) == trusts_.end()) { return false; } - if (uid < SYSTEM_UID && uid != CheckerManager::INVALID_UID) { - return false; - } - - return true; + return (AccessTokenKit::GetTokenTypeFlag(info.tokenId) == TOKEN_HAP); } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/adapter/permission/src/media_lib_checker.h b/services/distributeddataservice/adapter/permission/src/media_lib_checker.h index 82d8c1cfb8711703dc3c18a19570f484102370df..b8f92b4238902e6f04b0b7b5f63d06f6994eb4db 100644 --- a/services/distributeddataservice/adapter/permission/src/media_lib_checker.h +++ b/services/distributeddataservice/adapter/permission/src/media_lib_checker.h @@ -25,11 +25,10 @@ public: ~MediaLibChecker(); void Initialize() override; bool SetTrustInfo(const DistributedData::CheckerManager::Trust &trust) override; - std::string GetAppId(pid_t uid, const std::string &bundleName) override; - bool IsValid(pid_t uid, const std::string &bundleName) override; + std::string GetAppId(const CheckerManager::StoreInfo &info) override; + bool IsValid(const CheckerManager::StoreInfo &info) override; private: static MediaLibChecker instance_; - static constexpr pid_t SYSTEM_UID = 10000; std::map trusts_; }; } // namespace DistributedData diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index b7480feb6e876a54a0aba984910faf2a70fc6c0d..4647f78bc76a0fd95b562dfcb84bc4330b33431a 100644 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -26,18 +26,21 @@ #include "battery_srv_client.h" #include "power_mgr_client.h" #endif +#include "communication_provider.h" #include "constant.h" #include "kv_store_delegate_manager.h" #include "kv_scheduler.h" #include "kvstore_data_service.h" #include "log_print.h" -#include "kvstore_meta_manager.h" +#include "metadata/meta_data_manager.h" +#include "metadata/secret_key_meta_data.h" +#include "metadata/store_meta_data.h" #include "time_utils.h" #include "utils/crypto.h" namespace OHOS::DistributedKv { -using json = nlohmann::json; - +using namespace DistributedData; +using namespace AppDistributedKv; BackupHandler::BackupHandler(IKvStoreDataService *kvStoreDataService) { } @@ -50,7 +53,7 @@ BackupHandler::~BackupHandler() } void BackupHandler::BackSchedule() { - std::chrono::duration delay(1800); // delay 30 minutes + std::chrono::duration delay(1800); // delay 30 minutes std::chrono::duration internal(1800); // duration is 30 minutes ZLOGI("BackupHandler Schedule start."); scheduler_.Every(delay, internal, [&]() { @@ -58,30 +61,34 @@ void BackupHandler::BackSchedule() ZLOGE("it is not meet the condition of backup."); return; } - std::map results; + auto device = CommunicationProvider::GetInstance().GetLocalDevice(); + if (device.uuid.empty()) { + ZLOGE("local uuid is empty!"); + return; + } + + std::vector results; ZLOGI("BackupHandler Schedule Every start."); - if (!KvStoreMetaManager::GetInstance().GetFullMetaData(results)) { + if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ device.uuid }), results)) { ZLOGE("GetFullMetaData failed."); return; } - for (auto const &entry : results) { - if (!entry.second.kvStoreMetaData.isBackup || entry.second.kvStoreMetaData.isDirty) { + for (auto &entry : results) { + if (!entry.isBackup || entry.isDirty) { continue; } - KvStoreType type = entry.second.kvStoreMetaData.kvStoreType; - if (type == KvStoreType::MULTI_VERSION) { - MultiKvStoreBackup(entry.second); - } else if (type == KvStoreType::SINGLE_VERSION) { - SingleKvStoreBackup(entry.second); + auto type = entry.storeType; + if (type == KvStoreType::SINGLE_VERSION) { + SingleKvStoreBackup(entry); } } backupSuccessTime_ = TimeUtils::CurrentTimeMicros(); }); } -void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) +void BackupHandler::SingleKvStoreBackup(const StoreMetaData &metaData) { ZLOGI("SingleKvStoreBackup start."); BackupPara backupPara; @@ -91,23 +98,17 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) } DistributedDB::KvStoreNbDelegate::Option dbOption; SetDBOptions(dbOption, backupPara, metaData); - auto *delegateMgr = new(std::nothrow) DistributedDB::KvStoreDelegateManager(metaData.kvStoreMetaData.appId, - AccountDelegate::GetInstance()->GetCurrentAccountId()); - if (delegateMgr == nullptr) { - return; - } - std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, - metaData.kvStoreMetaData.bundleName, backupPara.pathType); - DistributedDB::KvStoreConfig kvStoreConfig = {appDataStoragePath}; - delegateMgr->SetKvStoreConfig(kvStoreConfig); + DistributedDB::KvStoreDelegateManager delegateMgr(metaData.appId, metaData.user); + std::string path = KvStoreAppManager::GetDataStoragePath(metaData.account, metaData.bundleName, backupPara.pathType); + DistributedDB::KvStoreConfig kvStoreConfig = { path }; + delegateMgr.SetKvStoreConfig(kvStoreConfig); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreNbDelegate *delegate) { - auto del = std::shared_ptr(delegateMgr); if (delegate == nullptr) { ZLOGE("SingleKvStoreBackup delegate is null"); return; } - if (metaData.kvStoreMetaData.isAutoSync) { + if (metaData.isAutoSync) { bool autoSync = true; DistributedDB::PragmaData data = static_cast(&autoSync); auto pragmaStatus = delegate->Pragma(DistributedDB::PragmaCmd::AUTO_SYNC, data); @@ -129,134 +130,81 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) RenameFile(backupBackFullName, backupFullName); } } - del->CloseKvStore(delegate); + delegateMgr.CloseKvStore(delegate); }; - delegateMgr->GetKvStore(metaData.kvStoreMetaData.storeId, dbOption, fun); + delegateMgr.GetKvStore(metaData.storeId, dbOption, fun); } void BackupHandler::SetDBOptions(DistributedDB::KvStoreNbDelegate::Option &dbOption, - const BackupHandler::BackupPara &backupPara, const MetaData &metaData) + const BackupHandler::BackupPara &backupPara, const StoreMetaData &metaData) { dbOption.createIfNecessary = false; dbOption.isEncryptedDb = backupPara.password.GetSize() > 0; dbOption.passwd = backupPara.password; dbOption.createDirByStoreIdOnly = true; - dbOption.secOption = KvStoreAppManager::ConvertSecurity(metaData.kvStoreMetaData.securityLevel); + dbOption.secOption = KvStoreAppManager::ConvertSecurity(metaData.securityLevel); } -void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) +bool BackupHandler::InitBackupPara(const StoreMetaData &metaData, BackupPara &backupPara) { - ZLOGI("MultiKvStoreBackup start."); - BackupPara backupPara; - auto initPara = InitBackupPara(metaData, backupPara); - if (!initPara) { - return; - } - - DistributedDB::KvStoreDelegate::Option option; - option.createIfNecessary = false; - option.isEncryptedDb = backupPara.password.GetSize() > 0; - option.passwd = backupPara.password; - option.createDirByStoreIdOnly = true; - - auto *delegateMgr = new DistributedDB::KvStoreDelegateManager(metaData.kvStoreMetaData.appId, - AccountDelegate::GetInstance()->GetCurrentAccountId()); - std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, - metaData.kvStoreMetaData.bundleName, backupPara.pathType); - DistributedDB::KvStoreConfig kvStoreConfig; - kvStoreConfig.dataDir = appDataStoragePath; - delegateMgr->SetKvStoreConfig(kvStoreConfig); - std::function fun = - [&](DistributedDB::DBStatus status, DistributedDB::KvStoreDelegate *delegate) { - auto del = std::shared_ptr(delegateMgr); - if (delegate == nullptr) { - ZLOGE("MultiKvStoreBackup delegate is null"); - return; - } - ZLOGW("MultiKvStoreBackup export"); - if (status == DistributedDB::DBStatus::OK) { - auto backupFullName = backupPara.backupFullName; - auto backupBackFullName = backupPara.backupBackFullName; - - RenameFile(backupFullName, backupBackFullName); - status = delegate->Export(backupFullName, option.passwd); - if (status == DistributedDB::DBStatus::OK) { - ZLOGD("MultiKvStoreBackup export success."); - RemoveFile(backupBackFullName); - ZLOGD("MultiKvStoreBackup export success."); - } else { - ZLOGE("MultiKvStoreBackup export failed."); - RenameFile(backupBackFullName, backupFullName); - } - } - del->CloseKvStore(delegate); - }; - delegateMgr->GetKvStore(metaData.kvStoreMetaData.storeId, option, fun); -} - -bool BackupHandler::InitBackupPara(const MetaData &metaData, BackupPara &backupPara) -{ - BackupPara backupParameter; - auto pathType = KvStoreAppManager::ConvertPathType( - metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); - if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { + auto pathType = KvStoreAppManager::ConvertPathType(metaData); + if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.user, pathType))) { ZLOGE("MultiKvStoreBackup backup create directory failed."); return false; } - DistributedDB::CipherPassword password; - const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Set secret key value failed. len is (%d)", int32_t(secretKey.size())); - return false; - } - - std::initializer_list backList = {metaData.kvStoreMetaData.userId, "_", - metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId}; + std::initializer_list backList = { metaData.account, "_", metaData.appId, "_", metaData.storeId }; std::string backupName = Constant::Concatenate(backList); - std::initializer_list backFullList = { - BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName)}; + std::initializer_list backFullList = { BackupHandler::GetBackupPath(metaData.user, pathType), "/", + GetHashedBackupName(backupName) }; auto backupFullName = Constant::Concatenate(backFullList); - std::initializer_list backNameList = {backupFullName, ".", "backup"}; + std::initializer_list backNameList = { backupFullName, ".", "backup" }; auto backupBackFullName = Constant::Concatenate(backNameList); - backupParameter.pathType = pathType; - backupParameter.password = password; - backupParameter.backupFullName = backupFullName; - backupParameter.backupBackFullName = backupBackFullName; - backupPara = backupParameter; + backupPara.pathType = pathType; + backupPara.backupFullName = backupFullName; + backupPara.backupBackFullName = backupBackFullName; + backupPara.password = {}; + if (metaData.isEncrypt) { + GetPassword(metaData, backupPara.password); + } + return true; +} +bool BackupHandler::GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password) +{ + std::string key = SecretKeyMetaData::GetKey({}); + SecretKeyMetaData secretKey; + MetaDataManager::GetInstance().LoadMeta(key, secretKey, true); + if (password.SetValue(secretKey.sKey.data(), secretKey.sKey.size()) != DistributedDB::CipherPassword::OK) { + ZLOGE("Set secret key value failed. len is (%d)", int32_t(secretKey.sKey.size())); + return false; + } return true; } -bool BackupHandler::SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvStoreNbDelegate *delegate) +bool BackupHandler::SingleKvStoreRecover(StoreMetaData &metaData, DistributedDB::KvStoreNbDelegate *delegate) { ZLOGI("start."); if (delegate == nullptr) { ZLOGE("SingleKvStoreRecover failed, delegate is null."); return false; } - auto pathType = KvStoreAppManager::ConvertPathType( - metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); - if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { + auto pathType = KvStoreAppManager::ConvertPathType(metaData); + if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.user, pathType))) { ZLOGE("SingleKvStoreRecover failed, backupDir_ file is not exist."); return false; } DistributedDB::CipherPassword password; - const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { + if (GetPassword(metaData, password)) { ZLOGE("Set secret key failed."); return false; } - std::string backupName = Constant::Concatenate( - {metaData.kvStoreMetaData.userId, "_", metaData.kvStoreMetaData.appId, "_", - metaData.kvStoreMetaData.storeId}); + std::string backupName = Constant::Concatenate({ metaData.account, "_", metaData.appId, "_", metaData.storeId }); auto backupFullName = Constant::Concatenate( - {BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName)}); + { BackupHandler::GetBackupPath(metaData.user, pathType), "/", GetHashedBackupName(backupName) }); DistributedDB::DBStatus dbStatus = delegate->Import(backupFullName, password); if (dbStatus == DistributedDB::DBStatus::OK) { ZLOGI("SingleKvStoreRecover success."); @@ -266,36 +214,29 @@ bool BackupHandler::SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvSt return false; } -bool BackupHandler::MultiKvStoreRecover(MetaData &metaData, - DistributedDB::KvStoreDelegate *delegate) +bool BackupHandler::MultiKvStoreRecover(StoreMetaData &metaData, DistributedDB::KvStoreDelegate *delegate) { ZLOGI("start."); if (delegate == nullptr) { ZLOGE("MultiKvStoreRecover failed, delegate is null."); return false; } - auto pathType = KvStoreAppManager::ConvertPathType( - metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); - if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { + auto pathType = KvStoreAppManager::ConvertPathType(metaData); + if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.user, pathType))) { ZLOGE("MultiKvStoreRecover failed, backupDir_ file is not exist."); return false; } ZLOGI("MultiKvStoreRecover start."); DistributedDB::CipherPassword password; - const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { + if (GetPassword(metaData, password)) { ZLOGE("Set secret key failed."); return false; } - 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.account, "_", metaData.appId, "_", metaData.storeId }); + auto backupFullName = Constant::Concatenate( + { BackupHandler::GetBackupPath(metaData.user, pathType), "/", GetHashedBackupName(backupName) }); DistributedDB::DBStatus dbStatus = delegate->Import(backupFullName, password); if (dbStatus == DistributedDB::DBStatus::OK) { ZLOGI("MultiKvStoreRecover success."); diff --git a/services/distributeddataservice/app/src/backup_handler.h b/services/distributeddataservice/app/src/backup_handler.h index 0fcda21d5d39523f3a7338daf4ac4d313b5e5f57..35f0e38f5e9369cb656a28385e55b1e505c95aab 100644 --- a/services/distributeddataservice/app/src/backup_handler.h +++ b/services/distributeddataservice/app/src/backup_handler.h @@ -16,25 +16,28 @@ #ifndef DISTRIBUTEDDATAMGR_BACKUP_HANDLER_H #define DISTRIBUTEDDATAMGR_BACKUP_HANDLER_H +#include "ikvstore_data_service.h" #include "kv_store_nb_delegate.h" #include "kv_store_delegate.h" -#include "types.h" +#include "kvstore_app_manager.h" #include "kv_scheduler.h" #include "kvstore_meta_manager.h" -#include "ikvstore_data_service.h" -#include "kvstore_app_manager.h" +#include "metadata/store_meta_data.h" +#include "metadata/secret_key_meta_data.h" +#include "types.h" namespace OHOS::DistributedKv { class BackupHandler { public: + using StoreMetaData = DistributedData::StoreMetaData; + using SecretKeyMetaData = DistributedData::SecretKeyMetaData; explicit BackupHandler(IKvStoreDataService *kvStoreDataService); BackupHandler(); ~BackupHandler(); void BackSchedule(); - void SingleKvStoreBackup(const MetaData &metaData); - void MultiKvStoreBackup(const MetaData &metaData); - bool SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvStoreNbDelegate *delegate); - bool MultiKvStoreRecover(MetaData &metaData, DistributedDB::KvStoreDelegate *delegate); + void SingleKvStoreBackup(const StoreMetaData &metaData); + bool SingleKvStoreRecover(StoreMetaData &metaData, DistributedDB::KvStoreNbDelegate *delegate); + bool MultiKvStoreRecover(StoreMetaData &metaData, DistributedDB::KvStoreDelegate *delegate); static const std::string &GetBackupPath(const std::string &deviceAccountId, int pathType); static bool RenameFile(const std::string &oldPath, const std::string &newPath); @@ -51,13 +54,13 @@ public: private: bool CheckNeedBackup(); - bool InitBackupPara(const MetaData &metaData, BackupPara &backupPara); - + bool InitBackupPara(const StoreMetaData &metaData, BackupPara &backupPara); + bool GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); static std::string backupDirCe_; static std::string backupDirDe_; void SetDBOptions(DistributedDB::KvStoreNbDelegate::Option &dbOption, - const BackupPara &backupPara, const MetaData &metaData); + const BackupPara &backupPara, const StoreMetaData &metaData); KvScheduler scheduler_ {}; static constexpr uint64_t BACKUP_INTERVAL = 3600 * 1000 * 10; // 10 hours int64_t backupSuccessTime_ = 0; diff --git a/services/distributeddataservice/app/src/kvstore_app_accessor.cpp b/services/distributeddataservice/app/src/kvstore_app_accessor.cpp index 74884cde5fddcb3515819b8838b38eeab64d37a6..7ee4346dab45d5c1c95ef90dabfb99d73d97fca4 100644 --- a/services/distributeddataservice/app/src/kvstore_app_accessor.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_accessor.cpp @@ -16,16 +16,22 @@ #define LOG_TAG "KvStoreAppAccessor" #include "kvstore_app_accessor.h" -#include #include +#include #include "broadcast_sender.h" #include "kv_store_delegate_manager.h" #include "kvstore_app_manager.h" #include "kvstore_meta_manager.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" +#include "metadata//secret_key_meta_data.h" #include "log_print.h" #include "permission_validator.h" namespace OHOS::DistributedKv { +using MetaDataManager = DistributedData::MetaDataManager; +using StoreMetaData = DistributedData::StoreMetaData; +using SecKeyMetaData = DistributedData::SecretKeyMetaData; KvStoreAppAccessor::~KvStoreAppAccessor() { ZLOGD("destructor."); @@ -62,33 +68,30 @@ void KvStoreAppAccessor::EnableKvStoreAutoLaunch() { ZLOGI("start"); return; - std::map entries; - if (KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) { + std::vector entries; + if (MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({}), entries)) { for (auto &meta : entries) { - KvStoreMetaData &metaData = meta.second.kvStoreMetaData; - ZLOGI("meta appId:%s", metaData.appId.c_str()); - DistributedDB::CipherPassword password; - const std::vector &secretKey = meta.second.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Get secret key failed."); - return; - } - auto pathType = - KvStoreAppManager::ConvertPathType(metaData.uid, metaData.bundleName, metaData.securityLevel); - std::string appPath = KvStoreAppManager::GetDataStoragePath( - metaData.deviceAccountId, metaData.bundleName, pathType); + ZLOGI("meta appId:%s", meta.appId.c_str()); + auto pathType = KvStoreAppManager::ConvertPathType(meta); + std::string appPath = KvStoreAppManager::GetDataStoragePath(meta.user, meta.bundleName, pathType); DistributedDB::AutoLaunchOption dbLaunchOption; dbLaunchOption.createIfNecessary = true; dbLaunchOption.createDirByStoreIdOnly = true; - dbLaunchOption.dataDir = Constant::Concatenate({appPath, "/", metaData.bundleName}); + dbLaunchOption.dataDir = Constant::Concatenate({ appPath, "/", meta.bundleName }); dbLaunchOption.observer = nullptr; - if (password.GetSize() > 0) { + if (meta.isEncrypt) { dbLaunchOption.isEncryptedDb = true; dbLaunchOption.cipher = DistributedDB::CipherType::AES_256_GCM; - dbLaunchOption.passwd = password; + SecKeyMetaData keyMeta; + MetaDataManager::GetInstance().LoadMeta(SecKeyMetaData::GetKey({}), keyMeta); + if (dbLaunchOption.passwd.SetValue(keyMeta.sKey.data(), keyMeta.sKey.size()) + != DistributedDB::CipherPassword::OK) { + ZLOGE("Get secret key failed."); + return; + } } - dbLaunchOption.secOption = KvStoreAppManager::ConvertSecurity(metaData.securityLevel); - EnableKvStoreAutoLaunch({metaData.userId, metaData.appId, metaData.storeId, dbLaunchOption}); + dbLaunchOption.secOption = KvStoreAppManager::ConvertSecurity(meta.securityLevel); + EnableKvStoreAutoLaunch({ meta.user, meta.appId, meta.storeId, dbLaunchOption }); } } else { ZLOGW("Init Service start enable failed."); diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index e6f86af24b07646e2bff157b392a33ec8d838b88..c62858ec208e3ff6213717b290c43eb5ad71dd04 100644 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -42,8 +42,8 @@ namespace OHOS { namespace DistributedKv { using namespace OHOS::DistributedData; -KvStoreAppManager::KvStoreAppManager(const std::string &bundleName, pid_t uid) - : bundleName_(bundleName), uid_(uid), flowCtrl_(BURST_CAPACITY, SUSTAINED_CAPACITY) +KvStoreAppManager::KvStoreAppManager(const std::string &bundleName, pid_t uid, uint32_t token) + : bundleName_(bundleName), uid_(uid), token_(token), flowCtrl_(BURST_CAPACITY, SUSTAINED_CAPACITY) { ZLOGI("begin."); deviceAccountId_ = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); @@ -94,12 +94,12 @@ Status KvStoreAppManager::ConvertErrorStatus(DistributedDB::DBStatus dbStatus, b return Status::SUCCESS; } -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, +Status KvStoreAppManager::GetKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &cipherKey, sptr &kvStore) { ZLOGI("begin"); kvStore = nullptr; - PathType type = ConvertPathType(uid_, bundleName_, options.securityLevel); + PathType type = ConvertPathType(metaData); auto *delegateManager = GetDelegateManager(type); if (delegateManager == nullptr) { ZLOGE("delegateManagers[%d] is nullptr.", type); @@ -112,7 +112,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & } std::lock_guard lg(storeMutex_); - auto it = stores_[type].find(storeId); + auto it = stores_[type].find(metaData.storeId); if (it != stores_[type].end()) { kvStore = it->second; ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); @@ -134,7 +134,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & DistributedDB::KvStoreDelegate *storeDelegate = nullptr; DistributedDB::DBStatus dbStatusTmp; - delegateManager->GetKvStore(storeId, dbOption, + delegateManager->GetKvStore(metaData.storeId, dbOption, [&storeDelegate, &dbStatusTmp](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreDelegate *delegate) { storeDelegate = delegate; dbStatusTmp = dbStatus; @@ -146,14 +146,14 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & } ZLOGD("get delegate"); - kvStore = new (std::nothrow)KvStoreImpl(options, deviceAccountId_, bundleName_, - appId, storeId, GetDbDir(options), storeDelegate); + kvStore = new (std::nothrow)KvStoreImpl(options, metaData.user, metaData.bundleName, + metaData.appId, metaData.storeId, GetDbDir(metaData), storeDelegate); if (kvStore == nullptr) { delegateManager->CloseKvStore(storeDelegate); kvStore = nullptr; return Status::ERROR; } - auto result = stores_[type].emplace(storeId, kvStore); + auto result = stores_[type].emplace(metaData.storeId, kvStore); if (!result.second) { ZLOGE("emplace failed."); delegateManager->CloseKvStore(storeDelegate); @@ -165,12 +165,12 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & return Status::SUCCESS; } -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, +Status KvStoreAppManager::GetKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &cipherKey, sptr &kvStore) { ZLOGI("begin"); kvStore = nullptr; - PathType type = ConvertPathType(uid_, bundleName_, options.securityLevel); + PathType type = ConvertPathType(metaData); auto *delegateManager = GetDelegateManager(type); if (delegateManager == nullptr) { ZLOGE("delegateManagers[%d] is nullptr.", type); @@ -182,7 +182,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & return Status::EXCEED_MAX_ACCESS_RATE; } std::lock_guard lg(storeMutex_); - auto it = singleStores_[type].find(storeId); + auto it = singleStores_[type].find(metaData.storeId); if (it != singleStores_[type].end()) { kvStore = it->second; ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); @@ -204,7 +204,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & DistributedDB::KvStoreNbDelegate *storeDelegate = nullptr; DistributedDB::DBStatus dbStatusTmp; - delegateManager->GetKvStore(storeId, dbOption, + delegateManager->GetKvStore(metaData.storeId, dbOption, [&](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *kvStoreDelegate) { storeDelegate = kvStoreDelegate; dbStatusTmp = dbStatus; @@ -214,15 +214,15 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & ZLOGE("storeDelegate is nullptr."); return ConvertErrorStatus(dbStatusTmp, options.createIfMissing); } - std::string kvStorePath = GetDbDir(options); + std::string kvStorePath = GetDbDir(metaData); switch (options.kvStoreType) { case KvStoreType::DEVICE_COLLABORATION: - kvStore = new (std::nothrow) DeviceKvStoreImpl( - options, deviceAccountId_, bundleName_, storeId, trueAppId_, kvStorePath, storeDelegate); + kvStore = new (std::nothrow) DeviceKvStoreImpl(options, metaData.user, metaData.bundleName, + metaData.storeId, metaData.appId, kvStorePath, storeDelegate); break; default: - kvStore = new (std::nothrow) SingleKvStoreImpl( - options, deviceAccountId_, bundleName_, storeId, trueAppId_, kvStorePath, storeDelegate); + kvStore = new (std::nothrow) SingleKvStoreImpl(options, metaData.user, metaData.bundleName, + metaData.storeId, metaData.appId, kvStorePath, storeDelegate); break; } if (kvStore == nullptr) { @@ -232,7 +232,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & return Status::ERROR; } kvStore->SetCompatibleIdentify(); - auto result = singleStores_[type].emplace(storeId, kvStore); + auto result = singleStores_[type].emplace(metaData.storeId, kvStore); if (!result.second) { ZLOGE("emplace failed."); delegateManager->CloseKvStore(storeDelegate); @@ -255,7 +255,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & dbOption.createDirByStoreIdOnly, kvStorePath, nullptr }; launchOption.secOption = ConvertSecurity(options.securityLevel); - AppAccessorParam accessorParam = {Constant::DEFAULT_GROUP_ID, trueAppId_, storeId, launchOption}; + AppAccessorParam accessorParam = {Constant::DEFAULT_GROUP_ID, trueAppId_, metaData.storeId, launchOption}; KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(accessorParam); return Status::SUCCESS; } @@ -408,15 +408,14 @@ Status KvStoreAppManager::InitNbDbOption(const Options &options, const std::vect return Status::SUCCESS; } -std::string KvStoreAppManager::GetDbDir(const Options &options) const +std::string KvStoreAppManager::GetDbDir(const StoreMetaData &metaData) { - return GetDataStoragePath(deviceAccountId_, bundleName_, ConvertPathType(uid_, bundleName_, options.securityLevel)); + return GetDataStoragePath(metaData.user, metaData.bundleName, ConvertPathType(metaData)); } -KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(int32_t uid, const std::string &bundleName, - int securityLevel) +KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(const StoreMetaData &metaData) { - switch (securityLevel) { + switch (metaData.securityLevel) { case S0: // fallthrough case S1: return PATH_DE; @@ -428,7 +427,12 @@ KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(int32_t uid, cons default: break; } - if (CheckerManager::GetInstance().GetAppId(bundleName, uid) != bundleName) { + CheckerManager::StoreInfo storeInfo; + storeInfo.uid = metaData.uid; + storeInfo.tokenId = metaData.tokenId; + storeInfo.bundleName = metaData.bundleName; + storeInfo.storeId = metaData.storeId; + if (CheckerManager::GetInstance().GetAppId(storeInfo) != metaData.bundleName) { return PATH_CE; } return PATH_DE; @@ -451,10 +455,11 @@ DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(Pat DirectoryUtils::ChangeModeDirOnly(directory, Constant::DEFAULT_MODE_DIR); DirectoryUtils::ChangeModeFileOnly(directory, Constant::DEFAULT_MODE_FILE); - trueAppId_ = CheckerManager::GetInstance().GetAppId(bundleName_, uid_); + trueAppId_ = CheckerManager::GetInstance().GetAppId({uid_, token_, bundleName_, ""}); if (trueAppId_.empty()) { delegateManagers_[type] = nullptr; - ZLOGW("check bundleName:%{public}s uid:%{public}d failed.", bundleName_.c_str(), uid_); + ZLOGW("check bundleName:%{public}s uid:%{public}d token:%{public}u failed.", ++ bundleName_.c_str(), uid_, token_); return nullptr; } diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.h b/services/distributeddataservice/app/src/kvstore_app_manager.h index 22fe7330004edb4fb3614c6ce167c5a4c10a3a57..a25160c19af51bd0c0e47f644eff7592e5d0bb20 100644 --- a/services/distributeddataservice/app/src/kvstore_app_manager.h +++ b/services/distributeddataservice/app/src/kvstore_app_manager.h @@ -22,10 +22,13 @@ #include "flowctrl_manager/kvstore_flowctrl_manager.h" #include "kv_store_delegate_manager.h" #include "kvstore_impl.h" -#include "types.h" -#include "single_kvstore_impl.h" #include "kv_store_nb_delegate.h" +#include "kvstore_meta_manager.h" +#include "metadata/store_meta_data.h" #include "nocopyable.h" +#include "single_kvstore_impl.h" +#include "types.h" + namespace OHOS { namespace DistributedKv { @@ -36,16 +39,17 @@ public: PATH_CE, PATH_TYPE_MAX }; + using StoreMetaData = DistributedData::StoreMetaData; - KvStoreAppManager(const std::string &bundleName, pid_t uid); + KvStoreAppManager(const std::string &bundleName, pid_t uid, uint32_t token); virtual ~KvStoreAppManager(); - Status GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, - const std::vector &cipherKey, sptr &kvStore); + Status GetKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &cipherKey, + sptr &kvStore); - Status GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, - const std::vector &cipherKey, sptr &kvStore); + Status GetKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &cipherKey, + sptr &kvStore); Status CloseKvStore(const std::string &storeId); @@ -66,9 +70,9 @@ public: static std::string GetDataStoragePath(const std::string &userId, const std::string &bundleName, PathType type); - static PathType ConvertPathType(int32_t uid, const std::string &bundleName, int securityLevel); + static PathType ConvertPathType(const StoreMetaData &metaData); - std::string GetDbDir(const Options &options) const; + static std::string GetDbDir(const StoreMetaData &metaData); void Dump(int fd) const; @@ -98,6 +102,7 @@ private: std::string deviceAccountId_ {}; std::string trueAppId_ {}; pid_t uid_; + uint32_t token_; std::mutex delegateMutex_ {}; DistributedDB::KvStoreDelegateManager *delegateManagers_[PATH_TYPE_MAX] {nullptr, nullptr}; KvStoreFlowCtrlManager flowCtrl_; diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index eb5b274a4260b0412be0136996d1da6cfd479cda..99cc87b69e70c75f7fdc01b9d924db3a378f133a 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -55,6 +55,7 @@ #include "user_delegate.h" #include "utils/block_integer.h" #include "utils/crypto.h" +#include "utils/converter.h" namespace OHOS::DistributedKv { using json = nlohmann::json; @@ -145,55 +146,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGE("invalid argument type."); return Status::INVALID_ARGUMENT; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - KvStoreParam param; - param.bundleName = appId.appId; - param.storeId = storeId.storeId; - const int32_t uid = IPCSkeleton::GetCallingUid(); - param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); - if (param.trueAppId.empty()) { - ZLOGW("appId:%{public}s, uid:%{public}d, PERMISSION_DENIED", appId.appId.c_str(), uid); - return Status::PERMISSION_DENIED; - } - - param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - SecretKeyPara keyPara; - Status status = KvStoreDataService::GetSecretKey(options, param, keyPara); - if (status != Status::SUCCESS) { - callback(nullptr); - return status; - } - - auto it = deviceAccountMap_.find(param.userId); - if (it == deviceAccountMap_.end()) { - auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(param.userId), std::forward_as_tuple(param.userId)); - if (!result.second) { - ZLOGE("emplace failed."); - FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_GET_DB}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - callback(nullptr); - return Status::ERROR; - } - it = result.first; - } - - sptr store; - param.status = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); - if (keyPara.outdated) { - KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, - KvStoreAppManager::ConvertPathType(param.uid, param.bundleName, options.securityLevel), store); - } - - ZLOGD("get kvstore return status:%d, userId:[%s], bundleName:[%s].", - param.status, KvStoreUtils::ToBeAnonymous(param.userId).c_str(), appId.appId.c_str()); - if (param.status == Status::SUCCESS) { - callback(std::move(store)); - return UpdateMetaData(options, param, keyPara.metaKey, it->second); - } - param.status = GetKvStoreFailDo(options, param, keyPara, it->second, store); - callback(std::move(store)); - return param.status; + return Status::NOT_SUPPORT; } Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, @@ -202,24 +155,24 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGI("begin."); KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - KvStoreParam param; - Status status = FillStoreParam(options, appId, storeId, param); + StoreMetaData metaData; + Status status = FillStoreParam(options, appId, storeId, metaData); if (status != Status::SUCCESS) { callback(nullptr); return status; } SecretKeyPara keyPara; - status = KvStoreDataService::GetSecretKey(options, param, keyPara); + status = KvStoreDataService::GetSecretKey(options, metaData, keyPara); if (status != Status::SUCCESS) { callback(nullptr); return status; } - auto it = deviceAccountMap_.find(param.userId); + auto it = deviceAccountMap_.find(metaData.user); if (it == deviceAccountMap_.end()) { auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(param.userId), std::forward_as_tuple(param.userId)); + std::forward_as_tuple(metaData.user), std::forward_as_tuple(metaData.user)); if (!result.second) { ZLOGE("emplace failed."); callback(nullptr); @@ -228,14 +181,13 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId it = result.first; } sptr store; - param.status = - (it->second).GetKvStore(options, param.bundleName, param.storeId, param.uid, keyPara.secretKey, store); + status = (it->second).GetKvStore(options, metaData, keyPara.secretKey, store); if (keyPara.outdated) { - KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, - KvStoreAppManager::ConvertPathType(param.uid, param.bundleName, options.securityLevel), store); + KvStoreMetaManager::GetInstance().ReKey(metaData.account, metaData.bundleName, metaData.storeId, + KvStoreAppManager::ConvertPathType(metaData), store); } - if (param.status == Status::SUCCESS) { - status = UpdateMetaData(options, param, keyPara.metaKey, it->second); + if (status == Status::SUCCESS) { + status = UpdateMetaData(options, metaData); if (status != Status::SUCCESS) { ZLOGE("failed to write meta"); callback(nullptr); @@ -245,40 +197,41 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId return status; } - param.status = GetSingleKvStoreFailDo(options, param, keyPara, it->second, store); + status = GetSingleKvStoreFailDo(status, options, metaData, keyPara, it->second, store); callback(std::move(store)); - return param.status; + return status; } Status KvStoreDataService::FillStoreParam( - const Options &options, const AppId &appId, const StoreId &storeId, KvStoreParam ¶m) + const Options &options, const AppId &appId, const StoreId &storeId, StoreMetaData &metaData) { if (!appId.IsValid() || !storeId.IsValid() || !options.IsValidType() || options.kvStoreType == KvStoreType::MULTI_VERSION) { ZLOGE("invalid argument type."); return Status::INVALID_ARGUMENT; } - param.bundleName = appId.appId; - param.storeId = storeId.storeId; - param.uid = IPCSkeleton::GetCallingUid(); - param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, param.uid); - ZLOGI("%{public}s, %{public}s", param.trueAppId.c_str(), param.bundleName.c_str()); - if (param.trueAppId.empty()) { - ZLOGW("appId:%{public}s, uid:%{public}d, PERMISSION_DENIED", appId.appId.c_str(), param.uid); + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.uid = IPCSkeleton::GetCallingUid(); + metaData.tokenId = IPCSkeleton::GetCallingTokenID(); + metaData.appId = CheckerManager::GetInstance().GetAppId(Converter::ConvertToStoreInfo(metaData)); + ZLOGI("%{public}s, %{public}s", metaData.appId.c_str(), metaData.bundleName.c_str()); + if (metaData.appId.empty()) { + ZLOGW("appId:%{public}s, uid:%{public}d, PERMISSION_DENIED", appId.appId.c_str(), metaData.uid); return PERMISSION_DENIED; } - param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(param.uid); + metaData.user = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(metaData.uid); return SUCCESS; } -Status KvStoreDataService::GetSecretKey(const Options &options, const KvStoreParam &kvParas, +Status KvStoreDataService::GetSecretKey(const Options &options, const StoreMetaData &metaData, SecretKeyPara &secretKeyParas) { - std::string bundleName = kvParas.bundleName; - std::string storeIdTmp = kvParas.storeId; + std::string bundleName = metaData.bundleName; + std::string storeIdTmp = metaData.storeId; std::lock_guard lg(accountMutex_); - auto metaKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp); + auto metaKey = KvStoreMetaManager::GetMetaKey(metaData.user, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { ZLOGE("encrypt type or kvStore type is not the same"); return Status::INVALID_ARGUMENT; @@ -290,13 +243,13 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const KvStorePar std::vector metaSecretKey; std::string secretKeyFile; if (options.kvStoreType == KvStoreType::MULTI_VERSION) { - metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "KEY"); - secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(kvParas.userId, bundleName, storeIdTmp, - KvStoreAppManager::ConvertPathType(kvParas.uid, bundleName, options.securityLevel)); + metaSecretKey = KvStoreMetaManager::GetMetaKey(metaData.user, "default", bundleName, storeIdTmp, "KEY"); + secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( + metaData.user, bundleName, storeIdTmp, KvStoreAppManager::ConvertPathType(metaData)); } else { - metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); - secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(kvParas.userId, bundleName, storeIdTmp, - KvStoreAppManager::ConvertPathType(kvParas.uid, bundleName, options.securityLevel)); + metaSecretKey = KvStoreMetaManager::GetMetaKey(metaData.user, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile( + metaData.user, bundleName, storeIdTmp, KvStoreAppManager::ConvertPathType(metaData)); } bool outdated = false; @@ -322,7 +275,6 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const KvStorePar kvStoreSecretKey.alreadyCreated = alreadyCreated; kvStoreSecretKey.outdated = outdated; secretKeyParas = kvStoreSecretKey; - return Status::SUCCESS; } @@ -354,94 +306,39 @@ Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool & return Status::SUCCESS; } -Status KvStoreDataService::UpdateMetaData(const Options &options, const KvStoreParam &kvParas, - const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager) +Status KvStoreDataService::UpdateMetaData(const Options &options, const StoreMetaData &metaData) { auto localDeviceId = DeviceKvStoreImpl::GetLocalDeviceId(); if (localDeviceId.empty()) { ZLOGE("failed to get local device id"); return Status::ERROR; } - KvStoreMetaData metaData; - metaData.appId = kvParas.trueAppId; - metaData.appType = "harmony"; - metaData.bundleName = kvParas.bundleName; - metaData.deviceAccountId = kvParas.userId; - metaData.deviceId = localDeviceId; - metaData.isAutoSync = options.autoSync; - metaData.isBackup = options.backup; - metaData.isEncrypt = options.encrypt; - metaData.kvStoreType = options.kvStoreType; - metaData.schema = options.schema; - metaData.storeId = kvParas.storeId; - metaData.tokenId = IPCSkeleton::GetCallingTokenID(); - metaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - metaData.uid = IPCSkeleton::GetCallingUid(); - metaData.version = STORE_VERSION; - metaData.securityLevel = options.securityLevel; - metaData.dataDir = kvStoreUserManager.GetDbDir(kvParas.bundleName, options); - - std::string jsonStr = metaData.Marshal(); - std::vector jsonVec(jsonStr.begin(), jsonStr.end()); - return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); + StoreMetaData saveMeta = metaData; + saveMeta.appType = "harmony"; + saveMeta.deviceId = localDeviceId; + saveMeta.isAutoSync = options.autoSync; + saveMeta.isBackup = options.backup; + saveMeta.isEncrypt = options.encrypt; + saveMeta.storeType = options.kvStoreType; + saveMeta.schema = options.schema; + saveMeta.version = StoreMetaData::CURRENT_VERSION; + saveMeta.securityLevel = options.securityLevel; + saveMeta.dataDir = KvStoreAppManager::GetDbDir(metaData); + auto saved = MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta); + return !saved ? Status::DB_ERROR : Status::SUCCESS; } -Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, - SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &store) -{ - Status statusTmp = kvParas.status; - Status getKvStoreStatus = statusTmp; - int32_t path = KvStoreAppManager::ConvertPathType(kvParas.uid, kvParas.bundleName, options.securityLevel); - ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); - if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { - if (secKeyParas.alreadyCreated != Status::SUCCESS) { - // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.uid, kvParas.bundleName, kvParas.storeId); - return Status::ERROR; - } - // get existing encrypted store failed, retry with key stored in file - Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); - if (status != Status::SUCCESS) { - store = nullptr; - return Status::CRYPT_ERROR; - } - // here callback is called twice - statusTmp = kvUserManager.GetKvStore( - options, kvParas.bundleName, kvParas.storeId, kvParas.uid, secKeyParas.secretKey, store); - if (secKeyParas.outdated) { - KvStoreMetaManager::GetInstance().ReKey(kvParas.userId, kvParas.bundleName, kvParas.storeId, path, store); - } - } - - // if kvstore damaged and no backup file, then return DB_ERROR - if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { - // if backup file not exist, don't need recover - if (!CheckBackupFileExist(kvParas.userId, kvParas.bundleName, kvParas.storeId, path)) { - return Status::CRYPT_ERROR; - } - // remove damaged database - if (DeleteKvStoreOnly(kvParas.storeId, kvParas.uid, kvParas.bundleName) != Status::SUCCESS) { - ZLOGE("DeleteKvStoreOnly failed."); - return Status::DB_ERROR; - } - // recover database - return RecoverKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, store); - } - return statusTmp; -} - -Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, +Status KvStoreDataService::GetSingleKvStoreFailDo(Status status, const Options &options, const StoreMetaData &metaData, SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &kvStore) { - Status statusTmp = kvParas.status; + Status statusTmp = status; Status getKvStoreStatus = statusTmp; - int32_t path = KvStoreAppManager::ConvertPathType(kvParas.uid, kvParas.bundleName, options.securityLevel); + int32_t path = KvStoreAppManager::ConvertPathType(metaData); ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.uid, kvParas.bundleName, kvParas.storeId); + KvStoreMetaManager::GetInstance().RemoveSecretKey(metaData.uid, metaData.bundleName, metaData.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file @@ -452,26 +349,25 @@ Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const return Status::CRYPT_ERROR; } // here callback is called twice - statusTmp = kvUserManager.GetKvStore( - options, kvParas.bundleName, kvParas.storeId, kvParas.uid, secKeyParas.secretKey, kvStore); + statusTmp = kvUserManager.GetKvStore(options, metaData, secKeyParas.secretKey, kvStore); if (secKeyParas.outdated) { - KvStoreMetaManager::GetInstance().ReKey(kvParas.userId, kvParas.bundleName, kvParas.storeId, path, kvStore); + KvStoreMetaManager::GetInstance().ReKey(metaData.user, metaData.bundleName, metaData.storeId, path, kvStore); } } // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, don't need recover - if (!CheckBackupFileExist(kvParas.userId, kvParas.bundleName, kvParas.storeId, path)) { + if (!CheckBackupFileExist(metaData.user, metaData.bundleName, metaData.storeId, path)) { return Status::CRYPT_ERROR; } // remove damaged database - if (DeleteKvStoreOnly(kvParas.storeId, kvParas.uid, kvParas.bundleName) != Status::SUCCESS) { + if (DeleteKvStoreOnly(metaData) != Status::SUCCESS) { ZLOGE("DeleteKvStoreOnly failed."); return Status::DB_ERROR; } // recover database - return RecoverKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, kvStore); + return RecoverKvStore(options, metaData, secKeyParas.secretKey, kvStore); } return statusTmp; } @@ -522,29 +418,26 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &userId, const s return true; } template -Status KvStoreDataService::RecoverKvStore(const Options &options, const std::string &bundleName, - const std::string &storeId, const std::vector &secretKey, sptr &kvStore) +Status KvStoreDataService::RecoverKvStore( + const Options &options, const StoreMetaData &metaData, const std::vector &secretKey, sptr &kvStore) { // restore database - std::string storeIdTmp = storeId; 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); + auto it = deviceAccountMap_.find(metaData.user); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); return Status::INVALID_ARGUMENT; } - Status statusTmp = (it->second).GetKvStore(optionsTmp, bundleName, storeIdTmp, uid, secretKey, kvStore); + Status statusTmp = (it->second).GetKvStore(optionsTmp, metaData, secretKey, kvStore); // restore database failed if (statusTmp != Status::SUCCESS || kvStore == nullptr) { ZLOGE("RecoverSingleKvStore reget GetSingleKvStore failed."); return Status::DB_ERROR; } // recover database from backup file - bool importRet = kvStore->Import(bundleName); + bool importRet = kvStore->Import(metaData.bundleName); if (!importRet) { ZLOGE("RecoverSingleKvStore Import failed."); return Status::RECOVER_FAILED; @@ -597,13 +490,18 @@ Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &store return Status::INVALID_ARGUMENT; } - const int32_t uid = IPCSkeleton::GetCallingUid(); - std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); + CheckerManager::StoreInfo info; + info.uid = IPCSkeleton::GetCallingUid(); + info.tokenId = IPCSkeleton::GetCallingTokenID(); + info.bundleName = appId.appId; + info.storeId = storeId.storeId; + std::string trueAppId = CheckerManager::GetInstance().GetAppId(info); if (trueAppId.empty()) { - ZLOGW("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), uid); + ZLOGW("check appId:%{public}s uid:%{public}d token:%{public}u failed.", + appId.appId.c_str(), info.uid, info.tokenId); return Status::PERMISSION_DENIED; } - const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(info.uid); std::lock_guard lg(accountMutex_); auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { @@ -627,14 +525,19 @@ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - const int32_t uid = IPCSkeleton::GetCallingUid(); - std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); + CheckerManager::StoreInfo info; + info.uid = IPCSkeleton::GetCallingUid(); + info.tokenId = IPCSkeleton::GetCallingTokenID(); + info.bundleName = appId.appId; + info.storeId = ""; + std::string trueAppId = CheckerManager::GetInstance().GetAppId(info); if (trueAppId.empty()) { - ZLOGW("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), uid); + ZLOGW("check appId:%{public}s uid:%{public}d token:%{public}u failed.", + appId.appId.c_str(), info.uid, info.tokenId); return Status::PERMISSION_DENIED; } - const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(info.uid); std::lock_guard lg(accountMutex_); auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { @@ -651,9 +554,13 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - int32_t uid = IPCSkeleton::GetCallingUid(); - if (!CheckerManager::GetInstance().IsValid(appId.appId, uid)) { - ZLOGE("get appId failed."); + CheckerManager::StoreInfo info; + info.uid = IPCSkeleton::GetCallingUid(); + info.tokenId = IPCSkeleton::GetCallingTokenID(); + info.bundleName = appId.appId; + info.storeId = ""; + if (!CheckerManager::GetInstance().IsValid(info)) { + ZLOGW("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid); return Status::PERMISSION_DENIED; } @@ -661,7 +568,7 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor std::initializer_list backFileList = { AccountDelegate::GetInstance()->GetCurrentAccountId(), "_", appId.appId, "_", storeId.storeId}; auto backupFileName = Constant::Concatenate(backFileList); - const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(info.uid); std::initializer_list backPathListDE = {BackupHandler::GetBackupPath(userId, KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; auto backFilePath = Constant::Concatenate(backPathListDE); @@ -687,9 +594,13 @@ Status KvStoreDataService::DeleteAllKvStore(const AppId &appId) return Status::INVALID_ARGUMENT; } - int32_t uid = IPCSkeleton::GetCallingUid(); - if (!CheckerManager::GetInstance().IsValid(appId.appId, uid)) { - ZLOGE("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), uid); + CheckerManager::StoreInfo info; + info.uid = IPCSkeleton::GetCallingUid(); + info.tokenId = IPCSkeleton::GetCallingTokenID(); + info.bundleName = appId.appId; + info.storeId = ""; + if (!CheckerManager::GetInstance().IsValid(info)) { + ZLOGW("check appId:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid); return Status::PERMISSION_DENIED; } @@ -726,15 +637,11 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< return Status::INVALID_ARGUMENT; } - int32_t uid = IPCSkeleton::GetCallingUid(); - if (!CheckerManager::GetInstance().IsValid(appId.appId, uid)) { - ZLOGE("no permission bundleName:%{public}s, uid:%{public}d.", appId.appId.c_str(), uid); - return Status::PERMISSION_DENIED; - } - + pid_t uid = IPCSkeleton::GetCallingUid(); + uint32_t tokenId = IPCSkeleton::GetCallingTokenID(); std::lock_guard lg(clientDeathObserverMutex_); auto it = clientDeathObserverMap_.emplace(std::piecewise_construct, std::forward_as_tuple(appId.appId), - std::forward_as_tuple(appId, uid, *this, std::move(observer))); + std::forward_as_tuple(appId, uid, tokenId, *this, std::move(observer))); ZLOGI("map size: %{public}zu.", clientDeathObserverMap_.size()); if (!it.second) { ZLOGI("insert failed"); @@ -744,7 +651,7 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< return Status::SUCCESS; } -Status KvStoreDataService::AppExit(const AppId &appId, pid_t uid) +Status KvStoreDataService::AppExit(const AppId &appId, pid_t uid, uint32_t token) { ZLOGI("AppExit"); // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after @@ -756,9 +663,10 @@ Status KvStoreDataService::AppExit(const AppId &appId, pid_t uid) ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); } - std::string trueAppId = CheckerManager::GetInstance().GetAppId(appIdTmp.appId, uid); + std::string trueAppId = CheckerManager::GetInstance().GetAppId({ uid, token, appIdTmp.appId, "" }); if (trueAppId.empty()) { - ZLOGW("check appId:%{public}s uid:%{public}d failed.", appIdTmp.appId.c_str(), uid); + ZLOGW("check appId:%{public}s uid:%{public}d token:%{public}u failed.", + appIdTmp.appId.c_str(), uid, token); return Status::PERMISSION_DENIED; } @@ -1040,8 +948,8 @@ void KvStoreDataService::OnStop() } KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl( - const AppId &appId, pid_t uid, KvStoreDataService &service, sptr observer) - : appId_(appId), uid_(uid), dataService_(service), observerProxy_(std::move(observer)), + const AppId &appId, pid_t uid, uint32_t token, KvStoreDataService &service, sptr observer) + : appId_(appId), uid_(uid), token_(token), dataService_(service), observerProxy_(std::move(observer)), deathRecipient_(new KvStoreDeathRecipient(*this)) { ZLOGI("KvStoreClientDeathObserverImpl"); @@ -1065,8 +973,8 @@ KvStoreDataService::KvStoreClientDeathObserverImpl::~KvStoreClientDeathObserverI void KvStoreDataService::KvStoreClientDeathObserverImpl::NotifyClientDie() { - ZLOGI("appId: %{public}s uid:%{public}d", appId_.appId.c_str(), uid_); - dataService_.AppExit(appId_, uid_); + ZLOGI("appId: %{public}s uid:%{public}d tokenId:%{public}u", appId_.appId.c_str(), uid_, token_); + dataService_.AppExit(appId_, uid_, token_); } KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::KvStoreDeathRecipient( @@ -1097,16 +1005,17 @@ Status KvStoreDataService::DeleteKvStore(const std::string &bundleName, const St return Status::INVALID_ARGUMENT; } - const int32_t uid = IPCSkeleton::GetCallingUid(); + const pid_t uid = IPCSkeleton::GetCallingUid(); + uint32_t tokenId = IPCSkeleton::GetCallingTokenID(); const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); std::lock_guard lg(accountMutex_); Status status; auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { - status = (it->second).DeleteKvStore(bundleName, uid, storeId.storeId); + status = (it->second).DeleteKvStore(bundleName, uid, tokenId, storeId.storeId); } else { KvStoreUserManager kvStoreUserManager(userId); - status = kvStoreUserManager.DeleteKvStore(bundleName, uid, storeId.storeId); + status = kvStoreUserManager.DeleteKvStore(bundleName, uid, tokenId, storeId.storeId); } if (status == Status::SUCCESS) { @@ -1121,16 +1030,15 @@ Status KvStoreDataService::DeleteKvStore(const std::string &bundleName, const St return status; } -Status KvStoreDataService::DeleteKvStoreOnly(const std::string &bundleName, pid_t uid, const std::string &storeId) +Status KvStoreDataService::DeleteKvStoreOnly(const StoreMetaData &metaData) { ZLOGI("DeleteKvStoreOnly begin."); - auto userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - auto it = deviceAccountMap_.find(userId); + auto it = deviceAccountMap_.find(metaData.user); if (it != deviceAccountMap_.end()) { - return (it->second).DeleteKvStore(bundleName, uid, storeId); + return (it->second).DeleteKvStore(metaData.bundleName, metaData.uid, metaData.tokenId, metaData.storeId); } - KvStoreUserManager kvStoreUserManager(userId); - return kvStoreUserManager.DeleteKvStore(bundleName, uid, storeId); + KvStoreUserManager kvStoreUserManager(metaData.user); + return kvStoreUserManager.DeleteKvStore(metaData.bundleName, metaData.uid, metaData.tokenId, metaData.storeId); } void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index 8a7a0f047d043c0b0ac2d115c7ebf8595f4868c9..f3782f39272b268ca1e2bc9249569ba249bd44be 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -45,6 +45,7 @@ class KvStoreDataService : public SystemAbility, public KvStoreDataServiceStub { DECLARE_SYSTEM_ABILITY(KvStoreDataService); public: + using StoreMetaData = DistributedData::StoreMetaData; // record kvstore meta version for compatible, should update when modify kvstore meta structure. static constexpr uint32_t STORE_VERSION = 0x03000001; @@ -84,7 +85,7 @@ public: void OnStop() override; - Status DeleteKvStoreOnly(const std::string &bundleName, pid_t uid, const std::string &storeId); + Status DeleteKvStoreOnly(const StoreMetaData &metaData); void AccountEventChanged(const AccountEventInfo &eventInfo); @@ -93,14 +94,6 @@ public: bool CheckBackupFileExist(const std::string &userId, const std::string &bundleName, const std::string &storeId, int pathType); - struct KvStoreParam { - std::string bundleName; - std::string storeId; - std::string trueAppId; - std::string userId; - pid_t uid; - Status status = Status::SUCCESS; - }; struct SecretKeyPara { std::vector metaKey; std::vector secretKey; @@ -113,7 +106,7 @@ public: private: class KvStoreClientDeathObserverImpl { public: - KvStoreClientDeathObserverImpl(const AppId &appId, pid_t uid, + KvStoreClientDeathObserverImpl(const AppId &appId, pid_t uid, uint32_t token, KvStoreDataService &service, sptr observer); virtual ~KvStoreClientDeathObserverImpl(); @@ -131,6 +124,7 @@ private: void NotifyClientDie(); AppId appId_; pid_t uid_; + uint32_t token_; KvStoreDataService &dataService_; sptr observerProxy_; sptr deathRecipient_; @@ -145,25 +139,22 @@ private: Status DeleteKvStore(const std::string &bundleName, const StoreId &storeId); template - Status RecoverKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, + Status RecoverKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &secretKey, sptr &kvStore); - Status GetSecretKey(const Options &options, const KvStoreParam &KvParas, SecretKeyPara &secretKeyParas); + + Status GetSecretKey(const Options &options, const StoreMetaData &metaData, SecretKeyPara &secretKeyParas); Status RecoverSecretKey(const Status &alreadyCreated, bool &outdated, const std::vector &metaSecretKey, std::vector &secretKey, const std::string &secretKeyFile); - Status UpdateMetaData(const Options &options, const KvStoreParam &kvParas, - const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager); + Status UpdateMetaData(const Options &options, const StoreMetaData &metaData); void OnStoreMetaChanged(const std::vector &key, const std::vector &value, CHANGE_FLAG flag); - Status GetKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, sptr &kvStore); - - Status GetSingleKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, sptr &kvStore); + Status GetSingleKvStoreFailDo(Status status, const Options &options, const StoreMetaData &metaData, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &kvStore); - Status AppExit(const AppId &appId, pid_t uid); + Status AppExit(const AppId &appId, pid_t uid, uint32_t token); bool CheckPermissions(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) const; @@ -175,7 +166,7 @@ private: void CreateRdbService(); bool IsStoreOpened(const std::string &userId, const std::string &appId, const std::string &storeId); static Status FillStoreParam( - const Options &options, const AppId &appId, const StoreId &storeId, KvStoreParam ¶m); + const Options &options, const AppId &appId, const StoreId &storeId, StoreMetaData &metaData); static constexpr int TEN_SEC = 10; diff --git a/services/distributeddataservice/app/src/kvstore_impl.cpp b/services/distributeddataservice/app/src/kvstore_impl.cpp index 19a002fe4bf285add6a637b6d86c355af192b635..5e9589f26fb8a0095c7466154aa9fd5b76b8e87d 100644 --- a/services/distributeddataservice/app/src/kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/kvstore_impl.cpp @@ -776,22 +776,17 @@ KvStoreImpl::~KvStoreImpl() bool KvStoreImpl::Import(const std::string &bundleName) const { - ZLOGI("KvStoreImpl Import start"); - const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, - "KEY"); - std::vector secretKey; - bool outdated = false; - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - - MetaData metaData{0}; - metaData.kvStoreMetaData.deviceAccountId = deviceAccountId_; - metaData.kvStoreMetaData.userId = harmonyAccountId; - metaData.kvStoreMetaData.bundleName = bundleName; - metaData.kvStoreMetaData.appId = appId_; - metaData.kvStoreMetaData.storeId = storeId_; - metaData.kvStoreMetaData.securityLevel = options_.securityLevel; - metaData.secretKeyMetaData.secretKey = secretKey; + ZLOGI("KvStoreImpl Import start"); + const std::string account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + DistributedData::StoreMetaData metaData; + metaData.user = deviceAccountId_; + metaData.account = account; + metaData.bundleName = bundleName; + metaData.appId = appId_; + metaData.storeId = storeId_; + metaData.securityLevel = options_.securityLevel; + metaData.isEncrypt = options_.encrypt; + metaData.storeType = options_.kvStoreType; std::shared_lock lock(storeDelegateMutex_); return std::make_unique()->MultiKvStoreRecover(metaData, kvStoreDelegate_); } diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.cpp b/services/distributeddataservice/app/src/kvstore_user_manager.cpp index c4bc281c0d2cf11fde91590d4fd79165e17c4e8a..1bafba1237410588323718392f79361b49146bbc 100644 --- a/services/distributeddataservice/app/src/kvstore_user_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_user_manager.cpp @@ -75,7 +75,8 @@ void KvStoreUserManager::CloseAllKvStore() } } -Status KvStoreUserManager::DeleteKvStore(const std::string &bundleName, pid_t uid, const std::string &storeId) +Status KvStoreUserManager::DeleteKvStore( + const std::string &bundleName, pid_t uid, uint32_t token, const std::string &storeId) { ZLOGI("begin."); std::lock_guard lg(appMutex_); @@ -88,7 +89,7 @@ Status KvStoreUserManager::DeleteKvStore(const std::string &bundleName, pid_t ui } return status; } - KvStoreAppManager kvStoreAppManager(bundleName, uid); + KvStoreAppManager kvStoreAppManager(bundleName, uid, token); return kvStoreAppManager.DeleteKvStore(storeId); } @@ -119,16 +120,16 @@ Status KvStoreUserManager::MigrateAllKvStore(const std::string &harmonyAccountId return status; } -std::string KvStoreUserManager::GetDbDir(const std::string &bundleName, const Options &options) +std::string KvStoreUserManager::GetDbDir(const StoreMetaData &metaData) { ZLOGI("begin."); - if (options.kvStoreType == KvStoreType::MULTI_VERSION) { + if (metaData.storeType == KvStoreType::MULTI_VERSION) { return "default"; } std::lock_guard lg(appMutex_); - auto it = appMap_.find(bundleName); + auto it = appMap_.find(metaData.bundleName); if (it != appMap_.end()) { - return (it->second).GetDbDir(options); + return (it->second).GetDbDir(metaData); } return ""; } diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.h b/services/distributeddataservice/app/src/kvstore_user_manager.h index d83982c38573e950d8d3feb3044a6f3791246f51..32134bbee1eacd7b391b9cce77e6d67048f41271 100644 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -26,19 +26,19 @@ namespace OHOS { namespace DistributedKv { class KvStoreUserManager { public: +using StoreMetaData = DistributedData::StoreMetaData; explicit KvStoreUserManager(const std::string &userId); virtual ~KvStoreUserManager(); template - Status GetKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, pid_t uid, - const std::vector &cipherKey, sptr &kvStore) + Status GetKvStore(const Options &options, const StoreMetaData &metaData, const std::vector &cipherKey, sptr &kvStore) { std::lock_guard lg(appMutex_); - auto it = appMap_.find(bundleName); + auto it = appMap_.find(metaData.bundleName); if (it == appMap_.end()) { - auto result = appMap_.emplace( - std::piecewise_construct, std::forward_as_tuple(bundleName), std::forward_as_tuple(bundleName, uid)); + auto result = appMap_.emplace(std::piecewise_construct, std::forward_as_tuple(metaData.bundleName), + std::forward_as_tuple(metaData.bundleName, metaData.uid, metaData.tokenId)); if (result.second) { it = result.first; } @@ -47,7 +47,7 @@ public: kvStore = nullptr; return Status::ERROR; } - return (it->second).GetKvStore(options, bundleName, storeId, cipherKey, kvStore); + return (it->second).GetKvStore(options, metaData, cipherKey, kvStore); } Status CloseKvStore(const std::string &appId, const std::string &storeId); @@ -56,13 +56,13 @@ public: void CloseAllKvStore(); - Status DeleteKvStore(const std::string &bundleName, pid_t uid, const std::string &storeId); + Status DeleteKvStore(const std::string &bundleName, pid_t uid, uint32_t token, const std::string &storeId); void DeleteAllKvStore(); Status MigrateAllKvStore(const std::string &harmonyAccountId); - std::string GetDbDir(const std::string &bundleName, const Options &options); + std::string GetDbDir(const StoreMetaData &metaData); void Dump(int fd) const; diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 2947a236f2cfb8516b9656bc5bf7a805620d1021..0c7b6c72b61505f7a1a6eb5d047aed88d49ec56c 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -20,6 +20,8 @@ #include "device_kvstore_impl.h" #include "kvstore_meta_manager.h" #include "log_print.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" #include "securec.h" #include "upgrade_manager.h" #include "bootstrap.h" @@ -52,7 +54,8 @@ void RouteHeadHandlerImpl::Init() if (deviceId_.empty()) { return; } - SessionPoint localPoint { DeviceKvStoreImpl::GetLocalDeviceId(), std::stoi(userId_), appId_ }; + SessionPoint localPoint { + DeviceKvStoreImpl::GetLocalDeviceId(), static_cast(atoi(userId_.c_str())), appId_, storeId_ }; session_ = SessionManager::GetInstance().GetSession(localPoint, deviceId_); ZLOGD("valid session:%{public}s", Serializable::Marshall(session_).c_str()); } diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index da49c05dc8d0ce74c93b2eac728c766b300a37c1..b506c8f67323b7466e29536ee24dee709b4f510a 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -22,6 +22,8 @@ #include "auth_delegate.h" #include "checker/checker_manager.h" #include "log/log_print.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" #include "user_delegate.h" #include "utils/anonymous.h" @@ -36,17 +38,22 @@ SessionManager &SessionManager::GetInstance() Session SessionManager::GetSession(const SessionPoint &from, const std::string &targetDeviceId) const { ZLOGD("begin. peer device:%{public}s", Anonymous::Change(targetDeviceId).c_str()); - auto users = UserDelegate::GetInstance().GetRemoteUserStatus(targetDeviceId); Session session; session.appId = from.appId; session.sourceUserId = from.userId; session.sourceDeviceId = from.deviceId; session.targetDeviceId = targetDeviceId; - + auto users = UserDelegate::GetInstance().GetRemoteUserStatus(targetDeviceId); + StoreMetaData metaData; + auto key = StoreMetaData::GetKey({ from.deviceId, std::to_string(from.userId), + "default", from.appId, from.storeId }); + if (!MetaDataManager::GetInstance().LoadMeta(key, metaData)) { + return session; + } // system service if (from.userId == UserDelegate::SYSTEM_USER) { - auto *checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); - if (checker != nullptr && checker->IsValid(UserDelegate::SYSTEM_USER, from.appId)) { + if (CheckerManager::GetInstance().GetAppId({ metaData.uid, metaData.tokenId, metaData.bundleName, "" }) + == metaData.bundleName) { session.targetUserIds.push_back(UserDelegate::SYSTEM_USER); } } @@ -64,6 +71,7 @@ Session SessionManager::GetSession(const SessionPoint &from, const std::string & ZLOGD("end"); return session; } + bool SessionManager::CheckSession(const SessionPoint &from, const SessionPoint &to) const { return AuthDelegate::GetInstance()->CheckAccess(from.userId, to.userId, to.deviceId, from.appId); diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.h b/services/distributeddataservice/app/src/session_manager/session_manager.h index 17909f7de43c92a4cc5a8bd0ca7f56e80fb4bdf3..bad2b8e2f6cad8b3d461d4aa722de72ec415d532 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.h +++ b/services/distributeddataservice/app/src/session_manager/session_manager.h @@ -26,6 +26,7 @@ struct SessionPoint { std::string deviceId; uint32_t userId; std::string appId; + std::string storeId; }; class Session : public Serializable { diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index 4f58d0c7fde4a4e1993b9ebb77ec23a427f2ec1d..de7aa0193cbe1a6cbbeee25ee8f34e78e73967fe 100644 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -1489,19 +1489,16 @@ void SingleKvStoreImpl::IncreaseOpenCount() bool SingleKvStoreImpl::Import(const std::string &bundleName) const { ZLOGI("Single KvStoreImpl Import start"); - const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - auto sKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, "SINGLE_KEY"); - std::vector secretKey; - bool outdated = false; - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(sKey, secretKey, outdated); - MetaData metaData{0}; - metaData.kvStoreMetaData.deviceAccountId = deviceAccountId_; - metaData.kvStoreMetaData.userId = harmonyAccountId; - metaData.kvStoreMetaData.bundleName = bundleName; - metaData.kvStoreMetaData.appId = appId_; - metaData.kvStoreMetaData.storeId = storeId_; - metaData.kvStoreMetaData.securityLevel = options_.securityLevel; - metaData.secretKeyMetaData.secretKey = secretKey; + const std::string account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + DistributedData::StoreMetaData metaData; + metaData.user = deviceAccountId_; + metaData.account = account; + metaData.bundleName = bundleName; + metaData.appId = appId_; + metaData.storeId = storeId_; + metaData.securityLevel = options_.securityLevel; + metaData.isEncrypt = options_.encrypt; + metaData.storeType = options_.kvStoreType; std::shared_lock lock(storeNbDelegateMutex_); return std::make_unique()->SingleKvStoreRecover(metaData, kvStoreNbDelegate_); } @@ -1608,11 +1605,17 @@ void SingleKvStoreImpl::OnDump(int fd) const dprintf(fd, "%s createIfMissing : %d\n", prefix.c_str(), static_cast(options_.createIfMissing)); dprintf(fd, "%s schema : %s\n", prefix.c_str(), options_.schema.c_str()); } + std::string SingleKvStoreImpl::GetStoreId() { return storeId_; } +std::string SingleKvStoreImpl::GetStorePath() const +{ + return storePath_; +} + void SingleKvStoreImpl::SetCompatibleIdentify(const std::string &changedDevice) { bool flag = false; diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index 2320fdbe7227af9f2b2bcf23521e47ef35801202..279fc94486b17d7e9ae2314accb2fb1a5e38dac8 100644 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -79,6 +79,7 @@ public: void OnDump(int fd) const; void SetCompatibleIdentify(const std::string &changedDevice); void SetCompatibleIdentify(); + std::string GetStorePath() const; protected: virtual KvStoreObserverImpl *CreateObserver(const SubscribeType subscribeType, sptr observer); diff --git a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp index 64986e8de39fea4c420ae9f8667663d7a3a7cbe8..5496548907de4dd69955d24e95919899acf26599 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp @@ -17,10 +17,10 @@ #include #include #include +#include "backup_handler.h" #include "bootstrap.h" #include "checker/checker_manager.h" #include "kvstore_impl.h" -#include "backup_handler.h" #include "kv_scheduler.h" #include "kvstore_data_service.h" #include "kvstore_meta_manager.h" @@ -117,17 +117,15 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); - auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData; - metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - metaData.kvStoreMetaData.appId = trueAppId; - metaData.kvStoreMetaData.bundleName = appId.appId; - metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = true; - metaData.kvStoreType = KvStoreType::SINGLE_VERSION; - + metaData.user = "0"; + metaData.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + metaData.tokenId = 0; + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.isBackup = true; + metaData.storeType = KvStoreType::SINGLE_VERSION; + metaData.appId = CheckerManager::GetInstance().GetAppId({0, 0, appId.appId, storeId.storeId}); backupHandler->SingleKvStoreBackup(metaData); kvStorePtr->Delete(key2); @@ -171,16 +169,15 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); - auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData; - metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - metaData.kvStoreMetaData.appId = trueAppId; - metaData.kvStoreMetaData.bundleName = appId.appId; - metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = true; - metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + StoreMetaData metaData; + metaData.user = "0"; + metaData.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + metaData.appId = CheckerManager::GetInstance().GetAppId({0, 0, appId.appId, storeId.storeId}); + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.isBackup = true; + metaData.storeType = KvStoreType::SINGLE_VERSION; backupHandler->SingleKvStoreBackup(metaData); @@ -188,7 +185,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) std::initializer_list fileList = {currentAccountId, "_", trueAppId, "_", storeId.storeId}; auto backupFileName = Constant::Concatenate(fileList); auto backupFileNameHashed = BackupHandler::GetHashedBackupName(backupFileName); - auto pathType = KvStoreAppManager::ConvertPathType(1000, appId.appId, metaData.kvStoreMetaData.securityLevel); + auto pathType = KvStoreAppManager::ConvertPathType(metaData); std::initializer_list backFileList = {BackupHandler::GetBackupPath("0", pathType), "/", backupFileNameHashed}; auto backFilePath = Constant::Concatenate(backFileList); @@ -228,18 +225,16 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest005, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); - auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData; - metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - 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; - + StoreMetaData metaData; + metaData.user = "0"; + metaData.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.isBackup = true; + metaData.securityLevel = SecurityLevel::S0; + metaData.storeType = KvStoreType::SINGLE_VERSION; + metaData.appId = CheckerManager::GetInstance().GetAppId({0, 0, appId.appId, storeId.storeId}); backupHandler->SingleKvStoreBackup(metaData); kvStorePtr->Delete(key2); @@ -281,18 +276,16 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest006, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); - auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData; - metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - 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; - + StoreMetaData metaData; + metaData.user = "0"; + metaData.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.isBackup = true; + metaData.securityLevel = SecurityLevel::S2; + metaData.storeType = KvStoreType::SINGLE_VERSION; + metaData.appId = CheckerManager::GetInstance().GetAppId({0, 0, appId.appId, storeId.storeId}); backupHandler->SingleKvStoreBackup(metaData); kvStorePtr->Delete(key2); @@ -334,18 +327,16 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest007, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); - auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, 1000); auto backupHandler = std::make_unique(); - MetaData metaData; - metaData.kvStoreMetaData.deviceAccountId = "0"; - metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); - 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; - + StoreMetaData metaData; + metaData.user = "0"; + metaData.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); + metaData.bundleName = appId.appId; + metaData.storeId = storeId.storeId; + metaData.isBackup = true; + metaData.securityLevel = SecurityLevel::S4; + metaData.storeType = KvStoreType::SINGLE_VERSION; + metaData.appId = CheckerManager::GetInstance().GetAppId({0, 0, appId.appId, storeId.storeId}); backupHandler->SingleKvStoreBackup(metaData); kvStorePtr->Delete(key2); diff --git a/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp index 9ff2a31922298a75c2ec73459dbfffc671407b65..b71dcf16bc2de88f8d8a437bf8e8b41f8a93d248 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp @@ -38,7 +38,7 @@ AppId g_appId2; StoreId g_storeId2; } -class KvStoreImplLogicalIsolationTest : public testing::Test { +class SingleKvStoreImplLogicalIsolationTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -46,12 +46,12 @@ public: void TearDown(); }; -void KvStoreImplLogicalIsolationTest::SetUpTestCase(void) +void SingleKvStoreImplLogicalIsolationTest::SetUpTestCase(void) { g_defaultOptions.createIfMissing = true; g_defaultOptions.encrypt = false; g_defaultOptions.autoSync = true; - g_defaultOptions.kvStoreType = KvStoreType::MULTI_VERSION; + g_defaultOptions.kvStoreType = KvStoreType::SINGLE_VERSION; g_appId.appId = "lgc0"; g_storeId.storeId = "store0"; @@ -63,7 +63,7 @@ void KvStoreImplLogicalIsolationTest::SetUpTestCase(void) g_storeId2.storeId = "store2"; } -void KvStoreImplLogicalIsolationTest::TearDownTestCase(void) +void SingleKvStoreImplLogicalIsolationTest::TearDownTestCase(void) { g_kvStoreDataService->CloseAllKvStore(g_appId); g_kvStoreDataService->CloseAllKvStore(g_appId1); @@ -74,7 +74,7 @@ void KvStoreImplLogicalIsolationTest::TearDownTestCase(void) g_kvStoreDataService->DeleteAllKvStore(g_appId2); } -void KvStoreImplLogicalIsolationTest::SetUp(void) +void SingleKvStoreImplLogicalIsolationTest::SetUp(void) { g_kvStoreDataService = sptr(new KvStoreDataService()); KvStoreMetaManager::GetInstance().InitMetaParameter(); @@ -92,7 +92,7 @@ void KvStoreImplLogicalIsolationTest::SetUp(void) g_kvStoreDataService->DeleteAllKvStore(g_appId2); } -void KvStoreImplLogicalIsolationTest::TearDown(void) +void SingleKvStoreImplLogicalIsolationTest::TearDown(void) { g_kvStoreDataService->CloseAllKvStore(g_appId); g_kvStoreDataService->CloseAllKvStore(g_appId1); @@ -110,14 +110,14 @@ void KvStoreImplLogicalIsolationTest::TearDown(void) * @tc.require: AR000BVDF8 AR000CQS39 SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation001, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation001, TestSize.Level1) { - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); } @@ -129,22 +129,22 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation001, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation002, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation002, TestSize.Level1) { - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl EQ fail"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); } @@ -156,21 +156,21 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation002, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation003, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation003, TestSize.Level1) { - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl NE fail"; + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl NE fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); status = g_kvStoreDataService->CloseKvStore(g_appId1, g_storeId); @@ -183,21 +183,21 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation003, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation004, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation004, TestSize.Level1) { - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl NE fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl NE fail"; } /** @@ -207,23 +207,23 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation004, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation005, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation005, TestSize.Level1) { KvStoreDataService kvDataService; - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl NE fail"; + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl NE fail"; } /** @@ -233,35 +233,35 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation005, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation006, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation006, TestSize.Level1) { - sptr kvStorePtr; - sptr kvStorePtr1; - sptr kvStorePtr2; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; + sptr kvStorePtr; + sptr kvStorePtr1; + sptr kvStorePtr2; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; std::thread thread1([&]() { - Status status1 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status1, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status1 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status1, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); std::thread thread2([&]() { - Status status2 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); - EXPECT_EQ(status2, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status2 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); + EXPECT_EQ(status2, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); thread1.join(); thread2.join(); - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr2, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl EQ fail"; - EXPECT_EQ(kvStorePtr, kvStorePtr2) << "Two KvStoreImpl EQ fail"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr2, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl EQ fail"; + EXPECT_EQ(kvStorePtr, kvStorePtr2) << "Two SingleKvStoreImpl EQ fail"; } /** @@ -271,34 +271,34 @@ HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation006, TestSize.Level1) * @tc.require: AR000BVDF8 AR000CQS39 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplLogicalIsolationTest, LogicalIsolation007, TestSize.Level1) +HWTEST_F(SingleKvStoreImplLogicalIsolationTest, LogicalIsolation007, TestSize.Level1) { - sptr kvStorePtr; - sptr kvStorePtr1; - sptr kvStorePtr2; + sptr kvStorePtr; + sptr kvStorePtr1; + sptr kvStorePtr2; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; std::thread thread1([&]() { - Status status1 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status1, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status1 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status1, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); std::thread thread2([&]() { - Status status2 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId2, g_storeId2, - [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); - EXPECT_EQ(status2, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status2 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId2, g_storeId2, + [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); + EXPECT_EQ(status2, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); thread1.join(); thread2.join(); - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr2, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl NE fail"; - EXPECT_NE(kvStorePtr, kvStorePtr2) << "Two KvStoreImpl NE fail"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr2, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl NE fail"; + EXPECT_NE(kvStorePtr, kvStorePtr2) << "Two SingleKvStoreImpl NE fail"; } diff --git a/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp index 9596df63c2681302dff7ac2e50dd23abb8f6c126..ddb6440711883d19bc446308b181803bd8686765 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp @@ -39,19 +39,19 @@ AppId g_appId2; StoreId g_storeId2; } -class KvStoreImplPhysicalIsolationTest : public testing::Test { +class SingleKvStoreImplPhysicalIsolationTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); }; -void KvStoreImplPhysicalIsolationTest::SetUpTestCase(void) +void SingleKvStoreImplPhysicalIsolationTest::SetUpTestCase(void) { g_defaultOptions.createIfMissing = true; g_defaultOptions.encrypt = false; g_defaultOptions.autoSync = true; - g_defaultOptions.kvStoreType = KvStoreType::MULTI_VERSION; + g_defaultOptions.kvStoreType = KvStoreType::SINGLE_VERSION; g_appId.appId = "phy0"; g_storeId.storeId = "store0"; @@ -62,7 +62,7 @@ void KvStoreImplPhysicalIsolationTest::SetUpTestCase(void) g_appId2.appId = "phy2"; g_storeId2.storeId = "store2"; } -void KvStoreImplPhysicalIsolationTest::TearDownTestCase(void) +void SingleKvStoreImplPhysicalIsolationTest::TearDownTestCase(void) { g_kvStoreDataService->CloseAllKvStore(g_appId); g_kvStoreDataService->CloseAllKvStore(g_appId1); @@ -73,7 +73,7 @@ void KvStoreImplPhysicalIsolationTest::TearDownTestCase(void) g_kvStoreDataService->DeleteAllKvStore(g_appId2); } -void KvStoreImplPhysicalIsolationTest::SetUp(void) +void SingleKvStoreImplPhysicalIsolationTest::SetUp(void) { g_kvStoreDataService = sptr(new KvStoreDataService()); KvStoreMetaManager::GetInstance().InitMetaParameter(); @@ -90,7 +90,7 @@ void KvStoreImplPhysicalIsolationTest::SetUp(void) g_kvStoreDataService->DeleteAllKvStore(g_appId1); g_kvStoreDataService->DeleteAllKvStore(g_appId2); } -void KvStoreImplPhysicalIsolationTest::TearDown(void) +void SingleKvStoreImplPhysicalIsolationTest::TearDown(void) { g_kvStoreDataService->CloseAllKvStore(g_appId); g_kvStoreDataService->CloseAllKvStore(g_appId1); @@ -108,18 +108,18 @@ void KvStoreImplPhysicalIsolationTest::TearDown(void) * @tc.require: AR000BVDF8 AR000CQS3A SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation001, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation001, TestSize.Level1) { const std::string storePath = Constant::Concatenate( {Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), "/"}) + std::string("phy0/store0"); - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); } /** @@ -129,26 +129,26 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation001, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation002, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation002, TestSize.Level1) { const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; const std::string storePath1 = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store1"); - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId1); } @@ -159,26 +159,26 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation002, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation003, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation003, TestSize.Level1) { const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; const std::string storePath1 = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy1/store0"); - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); status = g_kvStoreDataService->CloseKvStore(g_appId1, g_storeId); } @@ -189,27 +189,27 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation003, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation004, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation004, TestSize.Level1) { const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; const std::string storePath1 = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy1/store1"); - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); status = g_kvStoreDataService->CloseKvStore(g_appId1, g_storeId1); } @@ -220,25 +220,25 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation004, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A SR000CQS38 * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation005, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation005, TestSize.Level1) { const std::string storePath = Constant::Concatenate( {Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), "/"}) + std::string("phy0/store0"); - sptr kvStorePtr; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; - sptr kvStorePtr1; - status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - EXPECT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + sptr kvStorePtr1; + status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + EXPECT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); } /** @@ -248,37 +248,37 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation005, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation006, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation006, TestSize.Level1) { const std::string storePath = Constant::Concatenate( {Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), "/"}) + std::string("phy0/store0"); - sptr kvStorePtr; - sptr kvStorePtr1; - sptr kvStorePtr2; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - ASSERT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; + sptr kvStorePtr; + sptr kvStorePtr1; + sptr kvStorePtr2; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + ASSERT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; std::thread thread1([&]() { - Status status1 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - ASSERT_EQ(status1, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status1 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + ASSERT_EQ(status1, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); std::thread thread2([&]() { - Status status2 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); - ASSERT_EQ(status2, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status2 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); + ASSERT_EQ(status2, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); thread1.join(); thread2.join(); - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr2, nullptr) << "GetKvStore execute fail!!"; - EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl EQ fail"; - EXPECT_EQ(kvStorePtr, kvStorePtr2) << "Two KvStoreImpl EQ fail"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; - EXPECT_EQ((static_cast(kvStorePtr2.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr2, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_EQ(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl EQ fail"; + EXPECT_EQ(kvStorePtr, kvStorePtr2) << "Two SingleKvStoreImpl EQ fail"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + EXPECT_EQ((static_cast(kvStorePtr2.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); } /** @@ -288,7 +288,7 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation006, TestSize.Level1 * @tc.require: AR000BVDF8 AR000CQS3A * @tc.author: liuyuhui */ -HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation007, TestSize.Level1) +HWTEST_F(SingleKvStoreImplPhysicalIsolationTest, PhysicalIsolation007, TestSize.Level1) { const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", @@ -298,32 +298,32 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation007, TestSize.Level1 const std::string storePath2 = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy2/store2"); - sptr kvStorePtr; - sptr kvStorePtr1; - sptr kvStorePtr2; - Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); - ASSERT_EQ(status, Status::SUCCESS) << "GetKvStore return wrong status"; + sptr kvStorePtr; + sptr kvStorePtr1; + sptr kvStorePtr2; + Status status = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId, g_storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + ASSERT_EQ(status, Status::SUCCESS) << "GetSingleKvStore return wrong status"; std::thread thread1([&]() { - Status status1 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId1, g_storeId1, - [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); - ASSERT_EQ(status1, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status1 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId1, g_storeId1, + [&](sptr kvStore) { kvStorePtr1 = std::move(kvStore); }); + ASSERT_EQ(status1, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); std::thread thread2([&]() { - Status status2 = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId2, g_storeId2, - [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); - ASSERT_EQ(status2, Status::SUCCESS) << "GetKvStore return wrong status"; + Status status2 = g_kvStoreDataService->GetSingleKvStore(g_defaultOptions, g_appId2, g_storeId2, + [&](sptr kvStore) { kvStorePtr2 = std::move(kvStore); }); + ASSERT_EQ(status2, Status::SUCCESS) << "GetSingleKvStore return wrong status"; }); thread1.join(); thread2.join(); - EXPECT_NE(kvStorePtr, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr1, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr2, nullptr) << "GetKvStore execute fail!!"; - EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two KvStoreImpl NE fail"; - EXPECT_NE(kvStorePtr, kvStorePtr2) << "Two KvStoreImpl NE fail"; - EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; - EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; - EXPECT_EQ((static_cast(kvStorePtr2.GetRefPtr()))->GetStorePath(), storePath2) << "StorePath EQ fail"; + EXPECT_NE(kvStorePtr, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr1, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr2, nullptr) << "GetSingleKvStore execute fail!!"; + EXPECT_NE(kvStorePtr, kvStorePtr1) << "Two SingleKvStoreImpl NE fail"; + EXPECT_NE(kvStorePtr, kvStorePtr2) << "Two SingleKvStoreImpl NE fail"; + EXPECT_EQ((static_cast(kvStorePtr.GetRefPtr()))->GetStorePath(), storePath) << "StorePath EQ fail"; + EXPECT_EQ((static_cast(kvStorePtr1.GetRefPtr()))->GetStorePath(), storePath1) << "StorePath EQ fail"; + EXPECT_EQ((static_cast(kvStorePtr2.GetRefPtr()))->GetStorePath(), storePath2) << "StorePath EQ fail"; status = g_kvStoreDataService->CloseKvStore(g_appId, g_storeId); status = g_kvStoreDataService->CloseKvStore(g_appId1, g_storeId1); status = g_kvStoreDataService->CloseKvStore(g_appId2, g_storeId2); diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 31c774ba338976207ae5c5dcf749884596a9c542..53f6b218cb9632c24c32f70f0e63312fb2fcbb51 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -48,6 +48,7 @@ ohos_shared_library("distributeddatasvcfwk") { "utils/anonymous.cpp", "utils/block_integer.cpp", "utils/constant.cpp", + "utils/converter.cpp", "utils/crypto.cpp", ] cflags = [ "-Wno-multichar" ] @@ -64,6 +65,7 @@ ohos_shared_library("distributeddatasvcfwk") { external_deps = [ "ability_base:base", "ability_base:want", + "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp index 33ef408815ccbc93f7322d857387bf4a80195fff..b7213f3c229c99b10612b7946d77dd47aa8ee94f 100644 --- a/services/distributeddataservice/framework/checker/checker_manager.cpp +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -49,13 +49,13 @@ void CheckerManager::RegisterPlugin(const std::string &checker, std::functionGetAppId(uid, bundleName); + auto appId = checker->GetAppId(info); if (appId.empty()) { continue; } @@ -64,13 +64,13 @@ std::string CheckerManager::GetAppId(const std::string &bundleName, pid_t uid) return ""; } -bool CheckerManager::IsValid(const std::string &bundleName, pid_t uid) +bool CheckerManager::IsValid(const StoreInfo &info) { for (auto &[name, checker] : checkers_) { if (checker == nullptr) { continue; } - if (!checker->IsValid(uid, bundleName)) { + if (!checker->IsValid(info)) { continue; } return true; diff --git a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp index 1c355e1e3a49f2fd390b16d8b19c9bd2efa783df..15167cc0a7c96aeecdcf421596120ce6eb2f8011 100644 --- a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp +++ b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp @@ -16,14 +16,14 @@ #include "checker/default/bundle_checker.h" #include -#include "bundlemgr/bundle_mgr_client.h" +#include "accesstoken_kit.h" +#include "hap_token_info.h" #include "log/log_print.h" #include "utils/crypto.h" namespace OHOS { namespace DistributedData { -using namespace AppExecFwk; +using namespace Security::AccessToken; BundleChecker BundleChecker::instance_; -constexpr pid_t BundleChecker::SYSTEM_UID; BundleChecker::BundleChecker() { CheckerManager::GetInstance().RegisterPlugin( @@ -44,50 +44,43 @@ bool BundleChecker::SetTrustInfo(const CheckerManager::Trust &trust) return true; } -std::string BundleChecker::GetAppId(pid_t uid, const std::string &bundleName) +std::string BundleChecker::GetAppId(const CheckerManager::StoreInfo &info) { - if (uid < SYSTEM_UID && uid != CheckerManager::INVALID_UID) { + if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { return ""; } - BundleMgrClient bmsClient; - std::string bundle = bundleName; - if (uid != CheckerManager::INVALID_UID) { - auto success = bmsClient.GetBundleNameForUid(uid, bundle); - if (!success || bundle != bundleName) { - return ""; - } + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) { + return ""; } - auto bundleInfo = std::make_unique(); - auto success = bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo, Constants::ANY_USERID); - if (!success) { + if (tokenInfo.bundleName != info.bundleName) { return ""; } - auto it = trusts_.find(bundleName); - if (it != trusts_.end() && (it->second == bundleInfo->appId)) { - return bundleName; + + auto it = trusts_.find(info.bundleName); + if (it != trusts_.end() && (it->second == tokenInfo.appID)) { + return info.bundleName; } - ZLOGD("bundleName:%{public}s, uid:%{public}d, appId:%{public}s", bundleName.c_str(), uid, - bundleInfo->appId.c_str()); - return Crypto::Sha256(bundleInfo->appId); + + ZLOGD("bundleName:%{public}s, token:%{public}u, appId:%{public}s", + info.bundleName.c_str(), info.tokenId, tokenInfo.appID.c_str()); + return Crypto::Sha256(tokenInfo.appID); } -bool BundleChecker::IsValid(pid_t uid, const std::string &bundleName) +bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) { - if (uid < SYSTEM_UID) { + if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { return false; } - BundleMgrClient bmsClient; - std::string bundle = bundleName; - auto success = bmsClient.GetBundleNameForUid(uid, bundle); - if (!success || bundle != bundleName) { + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) { return false; } - auto bundleInfo = std::make_unique(); - return bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo, Constants::ANY_USERID); + return tokenInfo.bundleName == info.bundleName; } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/checker/default/system_checker.cpp b/services/distributeddataservice/framework/checker/default/system_checker.cpp index f66f89e1340d141e8de9a796b0fc6c1af13f1530..e1b3977277e593a133e35d697d16d7b731fb55a1 100644 --- a/services/distributeddataservice/framework/checker/default/system_checker.cpp +++ b/services/distributeddataservice/framework/checker/default/system_checker.cpp @@ -14,11 +14,12 @@ */ #define LOG_TAG "SystemChecker" #include "checker/default/system_checker.h" +#include "accesstoken_kit.h" #include "log/log_print.h" namespace OHOS { namespace DistributedData { +using namespace Security::AccessToken; SystemChecker SystemChecker::instance_; -constexpr pid_t SystemChecker::SYSTEM_UID; SystemChecker::SystemChecker() { CheckerManager::GetInstance().RegisterPlugin( @@ -39,19 +40,20 @@ bool SystemChecker::SetTrustInfo(const CheckerManager::Trust &trust) return true; } -std::string SystemChecker::GetAppId(pid_t uid, const std::string &bundleName) +std::string SystemChecker::GetAppId(const CheckerManager::StoreInfo &info) { - if (uid >= SYSTEM_UID || uid == CheckerManager::INVALID_UID) { + if (!IsValid(info)) { return ""; } - std::string appId = (trusts_.find(bundleName) != trusts_.end()) ? trusts_[bundleName] : bundleName; - ZLOGD("bundleName:%{public}s, uid:%{public}d, appId:%{public}s", bundleName.c_str(), uid, appId.c_str()); + std::string appId = (trusts_.find(info.bundleName) != trusts_.end()) ? trusts_[info.bundleName] : info.bundleName; + ZLOGD("bundleName:%{public}s, token:%{public}u, appId:%{public}s", info.bundleName.c_str(), info.tokenId, + appId.c_str()); return appId; } -bool SystemChecker::IsValid(pid_t uid, const std::string &bundleName) +bool SystemChecker::IsValid(const CheckerManager::StoreInfo &info) { - return (uid < SYSTEM_UID && uid != CheckerManager::INVALID_UID); + return (AccessTokenKit::GetTokenTypeFlag(info.tokenId) == TOKEN_NATIVE || info.uid == CheckerManager::ROOT_UID); } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/checker/checker_manager.h b/services/distributeddataservice/framework/include/checker/checker_manager.h index 2a8363c5224fca6e5c784fd2fd86f16a60cdca6f..4f7074c07a1cbd73b0412d72f01052b07e88d5c3 100644 --- a/services/distributeddataservice/framework/include/checker/checker_manager.h +++ b/services/distributeddataservice/framework/include/checker/checker_manager.h @@ -22,7 +22,7 @@ namespace OHOS { namespace DistributedData { class CheckerManager { public: - static constexpr pid_t INVALID_UID = -1; + static constexpr pid_t ROOT_UID = 0; struct Trust { std::string bundleName; std::string appId; @@ -30,19 +30,25 @@ public: std::string base64Key; std::string checker; }; + struct StoreInfo { + pid_t uid; + uint32_t tokenId; + std::string bundleName; + std::string storeId; + }; class Checker { public: virtual void Initialize() = 0; virtual bool SetTrustInfo(const Trust &trust) = 0; - virtual std::string GetAppId(pid_t uid, const std::string &bundleName) = 0; - virtual bool IsValid(pid_t uid, const std::string &bundleName) = 0; + virtual std::string GetAppId(const StoreInfo &info) = 0; + virtual bool IsValid(const StoreInfo &info) = 0; protected: API_EXPORT ~Checker() = default; }; API_EXPORT static CheckerManager &GetInstance(); API_EXPORT void RegisterPlugin(const std::string &checker, std::function getter); - API_EXPORT std::string GetAppId(const std::string &bundleName, pid_t uid); - API_EXPORT bool IsValid(const std::string &bundleName, pid_t uid); + API_EXPORT std::string GetAppId(const StoreInfo &info); + API_EXPORT bool IsValid(const StoreInfo &info); API_EXPORT void LoadCheckers(std::vector &checkers); API_EXPORT Checker *GetChecker(const std::string &checker); private: diff --git a/services/distributeddataservice/framework/include/checker/default/bundle_checker.h b/services/distributeddataservice/framework/include/checker/default/bundle_checker.h index 3e4a1021006b13b81473bb344e374c6e42ad8cda..50b19af8d4e5625ee0d4380dd9a94085eaf372a6 100644 --- a/services/distributeddataservice/framework/include/checker/default/bundle_checker.h +++ b/services/distributeddataservice/framework/include/checker/default/bundle_checker.h @@ -24,11 +24,10 @@ public: ~BundleChecker(); void Initialize() override; bool SetTrustInfo(const CheckerManager::Trust &trust) override; - std::string GetAppId(pid_t uid, const std::string &bundleName) override; - bool IsValid(pid_t uid, const std::string &bundleName) override; + std::string GetAppId(const CheckerManager::StoreInfo &info) override; + bool IsValid(const CheckerManager::StoreInfo &info) override; private: static BundleChecker instance_; - static constexpr pid_t SYSTEM_UID = 10000; std::map trusts_; }; } // namespace DistributedData diff --git a/services/distributeddataservice/framework/include/checker/default/system_checker.h b/services/distributeddataservice/framework/include/checker/default/system_checker.h index 4ac610312007813352a0142b3c620e2dcfb3f851..566b0c9a87abda5e63dd67c0414c9e7ea8d8b907 100644 --- a/services/distributeddataservice/framework/include/checker/default/system_checker.h +++ b/services/distributeddataservice/framework/include/checker/default/system_checker.h @@ -25,10 +25,9 @@ public: ~SystemChecker(); void Initialize() override; bool SetTrustInfo(const CheckerManager::Trust &trust) override; - std::string GetAppId(pid_t uid, const std::string &bundleName) override; - bool IsValid(pid_t uid, const std::string &bundleName) override; + std::string GetAppId(const CheckerManager::StoreInfo &info) override; + bool IsValid(const CheckerManager::StoreInfo &info) override; private: - static constexpr pid_t SYSTEM_UID = 10000; std::map trusts_; static SystemChecker instance_; }; diff --git a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h index 6df56ca2956e8cb11a219a1c81fe20ed9d2f6585..0d62d7ab1666cd5e4163cbcaa44e460f0d6b8db1 100644 --- a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h @@ -26,6 +26,11 @@ struct API_EXPORT SecretKeyMetaData final : public Serializable { API_EXPORT ~SecretKeyMetaData(); API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; + + API_EXPORT static std::string GetKey(const std::initializer_list &fields); + API_EXPORT static std::string GetPrefix(const std::initializer_list &fields); +private: + static constexpr const char *KEY_PREFIX = "SecretKey"; }; } // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h index 87788aef3c85d4294fad4f6d545be0e3f2d37638..581e735ad1b5800fe0ec2508b3dfc371d807d617 100644 --- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -50,6 +50,7 @@ struct API_EXPORT StoreMetaData final : public Serializable { API_EXPORT bool operator==(const StoreMetaData &metaData) const; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; + API_EXPORT std::string GetKey(); API_EXPORT static std::string GetKey(const std::initializer_list &fields); API_EXPORT static std::string GetPrefix(const std::initializer_list &fields); diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index 4d29f7656482f4e0da2a99d418526adda768477c..7a8fa84acb0f5f93f3360ddde393a234629b59c1 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -26,21 +26,7 @@ #include "visibility.h" namespace OHOS { -namespace DistributedKv { -class KvStoreMetaRow { -public: - API_EXPORT static const std::string KEY_PREFIX; - - API_EXPORT static std::vector GetKeyFor(const std::string &key); -}; - -class SecretMetaRow { -public: - API_EXPORT static const std::string KEY_PREFIX; - - API_EXPORT static std::vector GetKeyFor(const std::string &key); -}; - +namespace DistributedData { class Constant { public: // concatenate strings and return a composition string. @@ -70,68 +56,7 @@ public: template static T TrimCopy(T s); - // get default device account id. - API_EXPORT static std::string GetDefaultDeviceAccountId(); - - // get default harmony account name. - API_EXPORT static std::string GetDefaultHarmonyAccountName(); - - // default group id for synchronization based on harmony account. - API_EXPORT static const std::string DEFAULT_GROUP_ID; - - // Indicates whether only storeid are used as hash materials for the DistributedDB path generated. - API_EXPORT static const bool STOREID_ONLY_FLAG; - - // version for distributed kv data service. - API_EXPORT static const std::string VERSION; - - // meta name for distributed kv data service. - API_EXPORT static const std::string META_DIR_NAME; - - // name for distributed kv data service. - API_EXPORT static const std::string SERVICE_NAME; - - // root path for distributed kv data service. - API_EXPORT static const std::string ROOT_PATH; - - // root path for distributeddata service and system services. - API_EXPORT static const std::string ROOT_PATH_DE; - - // root path for self-developed and non-self-developed app. - API_EXPORT static const std::string ROOT_PATH_CE; - - // the max length for key is 256. - API_EXPORT static const size_t MAX_KEY_LENGTH; - - // the max length for value is 1M. - API_EXPORT static const size_t MAX_VALUE_LENGTH; - - // the max length for StoreId is 64. - API_EXPORT static const size_t MAX_STORE_ID_LENGTH; - - // the max batch for putBatch is 128. - API_EXPORT static const size_t MAX_BATCH_SIZE; - - // the max capacity for ipc is 800KB. - API_EXPORT static const size_t MAX_IPC_CAPACITY; - - // service meta db name. - API_EXPORT static const std::string SERVICE_META_DB_NAME; - - API_EXPORT static const std::string KEY_SEPARATOR; - - API_EXPORT static const mode_t DEFAULT_MODE; - - API_EXPORT static const mode_t DEFAULT_MODE_DIR; - - API_EXPORT static const mode_t DEFAULT_MODE_FILE; - - API_EXPORT static const int SWITCH_RAW_DATA_SIZE; - - API_EXPORT static const int MAX_OPEN_KVSTORES; - - // name for process label (bus name for communication). compatible with HwDDMP - API_EXPORT static const std::string ROOT_KEY_GENERATED; + API_EXPORT static constexpr const char *KEY_SEPARATOR = "###"; }; // trim from start (in place) diff --git a/services/distributeddataservice/framework/include/utils/converter.h b/services/distributeddataservice/framework/include/utils/converter.h new file mode 100644 index 0000000000000000000000000000000000000000..3063e99c6238408ac21988199a0321b556b05c07 --- /dev/null +++ b/services/distributeddataservice/framework/include/utils/converter.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CONVERTER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CONVERTER_H +#include "checker/checker_manager.h" +#include "metadata/store_meta_data.h" +#include "visibility.h" +namespace OHOS::DistributedData { +class Converter { +public: + API_EXPORT static CheckerManager::StoreInfo ConvertToStoreInfo(const StoreMetaData &metaData); +}; +} // namespace OHOS::DistributedData +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CONVERTER_H diff --git a/services/distributeddataservice/framework/metadata/capability_meta_data.cpp b/services/distributeddataservice/framework/metadata/capability_meta_data.cpp index ae9f204a403cdac137dc396085102fee618514ae..4091a93495210d943ea4521efb512e3a30523ba1 100644 --- a/services/distributeddataservice/framework/metadata/capability_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/capability_meta_data.cpp @@ -17,8 +17,6 @@ #include "utils/constant.h" namespace OHOS::DistributedData { -using namespace OHOS::DistributedKv; - bool CapMetaData::Marshal(json &node) const { bool ret = true; diff --git a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp index 35e1737850b5c5cc4e823a91888a9b3248a07eb7..ff218fba3b430933fee0d1dc6ffa3848f9f9792e 100644 --- a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ #include "metadata/secret_key_meta_data.h" +#include "utils/constant.h" namespace OHOS { namespace DistributedData { SecretKeyMetaData::SecretKeyMetaData() @@ -36,5 +37,19 @@ bool SecretKeyMetaData::Unmarshal(const json &node) GetValue(node, GET_NAME(kvStoreType), kvStoreType); return true; } + +std::string SecretKeyMetaData::GetKey(const std::initializer_list &fields) +{ + std::string prefix = KEY_PREFIX; + for (const auto &field : fields) { + prefix.append(Constant::KEY_SEPARATOR).append(field); + } + return prefix; +} + +std::string SecretKeyMetaData::GetPrefix(const std::initializer_list &fields) +{ + return GetKey(fields).append(Constant::KEY_SEPARATOR); +} } // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/framework/metadata/store_meta_data.cpp b/services/distributeddataservice/framework/metadata/store_meta_data.cpp index af3a56ea73e655ae9c61690a2786eb029fb57cb4..e4eab4a8b324798a1e6ecac50e9245b79c455186 100644 --- a/services/distributeddataservice/framework/metadata/store_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp @@ -18,7 +18,6 @@ #include "utils/constant.h" namespace OHOS { namespace DistributedData { -using namespace OHOS::DistributedKv; constexpr uint32_t StoreMetaData::CURRENT_VERSION; constexpr uint32_t StoreMetaData::FIELD_CHANGED_TAG; constexpr const char *StoreMetaData::KEY_PREFIX; @@ -121,6 +120,11 @@ std::string StoreMetaData::GetKey(const std::initializer_list &fiel return prefix; } +std::string StoreMetaData::GetKey() +{ + return GetKey({ deviceId, user, "default", bundleName, storeId }); +} + std::string StoreMetaData::GetPrefix(const std::initializer_list &fields) { return GetKey(fields).append(Constant::KEY_SEPARATOR); diff --git a/services/distributeddataservice/framework/metadata/user_meta_data.cpp b/services/distributeddataservice/framework/metadata/user_meta_data.cpp index ab42cce6bd7103e69f50677526163eee80d5c365..d19b9c8b1f7e38b3c9d4f0752e391466a97db096 100644 --- a/services/distributeddataservice/framework/metadata/user_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/user_meta_data.cpp @@ -17,7 +17,6 @@ #include "utils/constant.h" namespace OHOS::DistributedData { -using namespace OHOS::DistributedKv; bool UserMetaData::Marshal(json &node) const { bool ret = true; diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..28395a16d81fa6514a367ad0263e1e198b96756f --- /dev/null +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -0,0 +1,103 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//build/ohos_var.gni") + +module_output_path = "distributeddatamgr/distributeddatafwk" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "../include/", + ] +} + +ohos_unittest("CheckerManagerTest") { + module_out_path = module_output_path + sources = [ + "../checker/checker_manager.cpp", + "../checker/default/bundle_checker.cpp", + "../checker/default/system_checker.cpp", + "checker_manager_test.cpp", + ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] +} + +ohos_unittest("EventCenterTest") { + module_out_path = module_output_path + sources = [ "event_center_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] +} + +ohos_unittest("SerializableTest") { + module_out_path = module_output_path + + sources = [ "serializable_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [] + + deps += [ + ":CheckerManagerTest", + ":EventCenterTest", + ":SerializableTest", + ] +} +############################################################################### diff --git a/services/distributeddataservice/framework/test/checker_manager_test.cpp b/services/distributeddataservice/framework/test/checker_manager_test.cpp index 8e9273b68b51d7cfdfe6d82301e10b87c0db6526..9e44c63f1446cf97d3da40aac618184b4eef4b84 100644 --- a/services/distributeddataservice/framework/test/checker_manager_test.cpp +++ b/services/distributeddataservice/framework/test/checker_manager_test.cpp @@ -15,9 +15,12 @@ #include "checker/checker_manager.h" #include "utils/crypto.h" +#include "nativetoken_kit.h" +#include "accesstoken_kit.h" #include using namespace testing::ext; using namespace OHOS::DistributedData; +using namespace OHOS::Security::AccessToken; class CheckerManagerTest : public testing::Test { public: static void SetUpTestCase(void) {} @@ -51,8 +54,12 @@ HWTEST_F(CheckerManagerTest, Checkers, TestSize.Level0) */ HWTEST_F(CheckerManagerTest, SystemCheckerBMS, TestSize.Level0) { - ASSERT_EQ("bundle_manager_service", CheckerManager::GetInstance().GetAppId("bundle_manager_service", 1000)); - ASSERT_TRUE(CheckerManager::GetInstance().IsValid("bundle_manager_service", 1000)); + CheckerManager::StoreInfo info; + info.uid = 1000; + info.tokenId = GetAccessTokenId("foundation", nullptr, 0, "system_core"); + info.bundleName = "bundle_manager_service"; + ASSERT_EQ("bundle_manager_service", CheckerManager::GetInstance().GetAppId(info)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid(info)); } /** @@ -64,8 +71,12 @@ HWTEST_F(CheckerManagerTest, SystemCheckerBMS, TestSize.Level0) */ HWTEST_F(CheckerManagerTest, SystemCheckerForm, TestSize.Level0) { - ASSERT_EQ("form_storage", CheckerManager::GetInstance().GetAppId("form_storage", 1000)); - ASSERT_TRUE(CheckerManager::GetInstance().IsValid("form_storage", 1000)); + CheckerManager::StoreInfo info; + info.uid = 1000; + info.tokenId = GetAccessTokenId("foundation", nullptr, 0, "system_core"); + info.bundleName = "form_storage"; + ASSERT_EQ("form_storage", CheckerManager::GetInstance().GetAppId(info)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid(info)); } /** @@ -77,8 +88,12 @@ HWTEST_F(CheckerManagerTest, SystemCheckerForm, TestSize.Level0) */ HWTEST_F(CheckerManagerTest, SystemCheckerIVI, TestSize.Level0) { - ASSERT_EQ("ivi_config_manager", CheckerManager::GetInstance().GetAppId("ivi_config_manager", 1000)); - ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ivi_config_manager", 1000)); + CheckerManager::StoreInfo info; + info.uid = 1000; + info.tokenId = GetAccessTokenId("foundation", nullptr, 0, "system_core"); + info.bundleName = "ivi_config_manager"; + ASSERT_EQ("ivi_config_manager", CheckerManager::GetInstance().GetAppId(info)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid(info)); } /** @@ -90,7 +105,10 @@ HWTEST_F(CheckerManagerTest, SystemCheckerIVI, TestSize.Level0) */ HWTEST_F(CheckerManagerTest, BundleChecker, TestSize.Level0) { - ASSERT_EQ(Crypto::Sha256("ohos.test.demo"), - CheckerManager::GetInstance().GetAppId("ohos.test.demo", 100000)); - ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ohos.test.demo", 100000)); -} + CheckerManager::StoreInfo info; + info.uid = 2000000; + info.tokenId = AccessTokenKit::GetHapTokenID(100, "ohos.test.demo", 0); + info.bundleName = "ohos.test.demo"; + ASSERT_EQ(Crypto::Sha256("ohos.test.demo"), CheckerManager::GetInstance().GetAppId(info)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid(info)); +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp index 99bbc3db19a7ac636a6153a3b0be9aa99611311c..674a9205a838d207e534229160e74284bbad17f1 100644 --- a/services/distributeddataservice/framework/utils/constant.cpp +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -19,81 +19,8 @@ #include namespace OHOS { -namespace DistributedKv { -// the Key Prefix for Meta data of KvStore. -const std::string KvStoreMetaRow::KEY_PREFIX = "KvStoreMetaData"; - -const std::string SecretMetaRow::KEY_PREFIX = "SecretKey"; - -/* version for distributed kv data service. */ -const std::string Constant::VERSION = "1"; - -/* meta name for distributed kv data service. */ -const std::string Constant::META_DIR_NAME = "Meta"; - -/* name for distributed kv data service. */ -const std::string Constant::SERVICE_NAME = "mdds"; - -/* root path for distributed kv data service. */ -const std::string Constant::ROOT_PATH = "/data/misc_de/0"; - -/* root path for distributeddata service and system services. */ -const std::string Constant::ROOT_PATH_DE = "/data/misc_de/0"; - -/* root path for self-developed and non-self-developed app. */ -const std::string Constant::ROOT_PATH_CE = "/data/misc_ce/0"; - -// the max length for key is 1024. -const size_t Constant::MAX_KEY_LENGTH = 1024; - -// the max length for StoreId is 128. -const size_t Constant::MAX_STORE_ID_LENGTH = 128; - -// the max length for value is 4M. -const size_t Constant::MAX_VALUE_LENGTH = 4 * 1024 * 1024; - -// the max batch for putBatch is 128. -const size_t Constant::MAX_BATCH_SIZE = 128; - -// the max capacity for ipc is 800K. -const size_t Constant::MAX_IPC_CAPACITY = 800 * 1024; - -// the default mode is 0755, stands for r/w/x for user, r/x for group, r/x for others. -const mode_t Constant::DEFAULT_MODE = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; - -// the mode for dir is 0755, r/w/x for user, r/-/x for group, r/-/x for others. -const mode_t Constant::DEFAULT_MODE_DIR = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; - -// the mode for file is 0600, r/w/- for user, -/-/- for group, -/-/- for others. -const mode_t Constant::DEFAULT_MODE_FILE = S_IRUSR | S_IWUSR; - -// Size threshold of switching to large data is a little smaller than MAX_IPC_CAPACITY. -const int Constant::SWITCH_RAW_DATA_SIZE = 700 * 1024; - -const int Constant::MAX_OPEN_KVSTORES = 16; - -// default group id for synchronization. -const std::string Constant::DEFAULT_GROUP_ID = "default"; - -// true indicates the ownership of distributed data is DEVICE, otherwise, ACCOUNT -const bool Constant::STOREID_ONLY_FLAG = true; - -// service meta db name. -const std::string Constant::SERVICE_META_DB_NAME = "service_meta"; - -const std::string Constant::KEY_SEPARATOR = "###"; - -std::vector KvStoreMetaRow::GetKeyFor(const std::string &key) -{ - std::string str = Constant::Concatenate({KvStoreMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key}); - return std::vector(str.begin(), str.end()); -} - -std::vector SecretMetaRow::GetKeyFor(const std::string &key) -{ - std::string str = Constant::Concatenate({SecretMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key}); - return std::vector(str.begin(), str.end()); -} +namespace DistributedData { +constexpr const char * Constant::KEY_SEPARATOR; std::string Constant::Concatenate(std::initializer_list stringList) { @@ -108,15 +35,5 @@ std::string Constant::Concatenate(std::initializer_list stringList) } return result; } - -std::string Constant::GetDefaultDeviceAccountId() -{ - return "0"; -} - -std::string Constant::GetDefaultHarmonyAccountName() -{ - return "default"; -} -} // namespace DistributedKv +} // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/framework/utils/converter.cpp b/services/distributeddataservice/framework/utils/converter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a49f0c5293ea7017d22c5390ffced2122fac4374 --- /dev/null +++ b/services/distributeddataservice/framework/utils/converter.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "utils/converter.h" +namespace OHOS::DistributedData { +CheckerManager::StoreInfo Converter::ConvertToStoreInfo(const StoreMetaData &metaData) +{ + return { metaData.uid, metaData.tokenId, metaData.bundleName, metaData.storeId }; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp index 4e3bf29f52d2368aa63369e0783bbf5741900286..9796444d18df040a54d81a55732b30c1d2baa816 100644 --- a/services/distributeddataservice/service/directory/src/directory_manager.cpp +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -32,8 +32,8 @@ std::string ServerDirWorker::GetDir(ClientContext clientContext, PathType type) if (rootPathMap_.find(type) == rootPathMap_.end()) { return ""; } - return DirectoryManager::JoinPath({ rootPathMap_.at(type), clientContext.userId, - Constant::GetDefaultHarmonyAccountName(), clientContext.bundleName }); + return DirectoryManager::JoinPath( + { rootPathMap_.at(type), clientContext.userId, "default", clientContext.bundleName }); } bool ServerDirWorker::CreateDir(ClientContext clientContext, PathType type) { @@ -56,7 +56,7 @@ std::string ServerDirWorker::GetBackupDir(ClientContext clientContext, PathType return ""; } return DirectoryManager::JoinPath({ rootPathMap_.at(type), clientContext.userId, - Constant::GetDefaultHarmonyAccountName(), clientContext.bundleName, "backup" }); + "default", clientContext.bundleName, "backup" }); } std::string ServerDirWorker::GetMetaDir() { diff --git a/services/distributeddataservice/service/kvdb/auth_delegate.cpp b/services/distributeddataservice/service/kvdb/auth_delegate.cpp index cc82b2a2593daa313aff35a77690f8495a01c864..0f81ea27c6a3e45249ffe9e70ac1d06f399defe5 100644 --- a/services/distributeddataservice/service/kvdb/auth_delegate.cpp +++ b/services/distributeddataservice/service/kvdb/auth_delegate.cpp @@ -150,16 +150,10 @@ std::vector AuthHandler::GetTrustedDevicesByType( bool AuthHandlerStub::CheckAccess( int localUserId, int peerUserId, const std::string &peerDeviceId, const std::string &appId) { - auto checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); - if (checker == nullptr) { - ZLOGE("get system checker failed"); - return false; - } - bool isSystemApp = checker->IsValid(UID_CAPACITY * localUserId, appId); - if (isSystemApp) { - ZLOGE("system app:%{public}s", appId.c_str()); + if (localUserId == SYSTEM_USER) { return peerUserId == SYSTEM_USER; } + auto localUsers = UserDelegate::GetInstance().GetLocalUserStatus(); auto peerUsers = UserDelegate::GetInstance().GetRemoteUserStatus(peerDeviceId); return peerUserId != SYSTEM_USER && IsUserActive(localUsers, localUserId) && IsUserActive(peerUsers, peerUserId); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 0763fb7f625b9fdb37fff755e12b5b5d72c178ff..b0180a976b64c39ab6f9cb2f1b0d6c79531d3226 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -116,7 +116,12 @@ void RdbServiceImpl::OnClientDied(pid_t pid) bool RdbServiceImpl::CheckAccess(const RdbSyncerParam ¶m) { - return !CheckerManager::GetInstance().GetAppId(param.bundleName_, GetCallingUid()).empty(); + CheckerManager::StoreInfo storeInfo; + storeInfo.uid = GetCallingUid(); + storeInfo.tokenId = GetCallingTokenID(); + storeInfo.bundleName = param.bundleName_; + storeInfo.storeId = param.storeName_; + return !CheckerManager::GetInstance().GetAppId(storeInfo).empty(); } RdbSyncerParam RdbServiceImpl::ToServiceParam(const RdbSyncerParam ¶m) @@ -212,9 +217,10 @@ std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam &pa { pid_t pid = GetCallingPid(); pid_t uid = GetCallingUid(); + uint32_t tokenId = GetCallingTokenID(); std::shared_ptr syncer; - syncers_.Compute(pid, [this, ¶m, pid, uid, &syncer] (const auto& key, StoreSyncersType& syncers) { + syncers_.Compute(pid, [this, ¶m, pid, uid, tokenId, &syncer] (const auto& key, StoreSyncersType& syncers) { auto it = syncers.find(param.storeName_); if (it != syncers.end()) { syncer = it->second; @@ -233,7 +239,7 @@ std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam &pa } auto syncer_ = std::make_shared(ToServiceParam(param), new (std::nothrow) RdbStoreObserverImpl(this, pid)); - if (syncer_->Init(pid, uid) != 0) { + if (syncer_->Init(pid, uid, tokenId) != 0) { return !syncers.empty(); } syncers[param.storeName_] = syncer_; @@ -326,8 +332,10 @@ std::string RdbServiceImpl::TransferStringToHex(const std::string &origStr) std::string RdbServiceImpl::GenIdentifier(const RdbSyncerParam ¶m) { pid_t uid = GetCallingUid(); + uint32_t token = GetCallingTokenID(); + CheckerManager::StoreInfo storeInfo{ uid, token, param.bundleName_, param.storeName_ }; std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - std::string appId = CheckerManager::GetInstance().GetAppId(param.bundleName_, uid); + std::string appId = CheckerManager::GetInstance().GetAppId(storeInfo); std::string identifier = RelationalStoreManager::GetRelationalStoreIdentifier(userId, appId, param.storeName_); return TransferStringToHex(identifier); } diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.cpp b/services/distributeddataservice/service/rdb/rdb_syncer.cpp index f5302d18723353c68fa1cc030cf567828138c3a1..eb96e4fb5c4304666c4ba916453b26ee218c1cda 100644 --- a/services/distributeddataservice/service/rdb/rdb_syncer.cpp +++ b/services/distributeddataservice/service/rdb/rdb_syncer.cpp @@ -81,7 +81,7 @@ std::string RdbSyncer::GetBundleName() const std::string RdbSyncer::GetAppId() const { - return DistributedData::CheckerManager::GetInstance().GetAppId(param_.bundleName_, uid_); + return DistributedData::CheckerManager::GetInstance().GetAppId({ uid_, token_, param_.bundleName_ }); } std::string RdbSyncer::GetPath() const @@ -94,11 +94,12 @@ std::string RdbSyncer::GetStoreId() const return param_.storeName_; } -int32_t RdbSyncer::Init(pid_t pid, pid_t uid) +int32_t RdbSyncer::Init(pid_t pid, pid_t uid, uint32_t token) { ZLOGI("enter"); pid_ = pid; uid_ = uid; + token_ = token; if (CreateMetaData() != RDB_OK) { ZLOGE("create meta data failed"); return RDB_ERROR; @@ -117,6 +118,7 @@ int32_t RdbSyncer::CreateMetaData() newMeta.deviceId = CommunicationProvider::GetInstance().GetLocalDevice().uuid; newMeta.storeId = GetStoreId(); newMeta.uid = uid_; + newMeta.tokenId = token_; newMeta.user = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid_); newMeta.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); newMeta.dataDir = GetPath(); diff --git a/services/distributeddataservice/service/rdb/rdb_syncer.h b/services/distributeddataservice/service/rdb/rdb_syncer.h index 7fb0616c63fc969917fb6f9590350614d06fabc3..ad67cf409a45f2de55b2bb03595b80d34f7e393a 100644 --- a/services/distributeddataservice/service/rdb/rdb_syncer.h +++ b/services/distributeddataservice/service/rdb/rdb_syncer.h @@ -31,7 +31,7 @@ public: RdbSyncer(const RdbSyncerParam& param, RdbStoreObserverImpl* observer); ~RdbSyncer() noexcept; - int32_t Init(pid_t pid, pid_t uid); + int32_t Init(pid_t pid, pid_t uid, uint32_t token); pid_t GetPid() const; @@ -69,6 +69,7 @@ private: RdbStoreObserverImpl *observer_ {}; pid_t pid_ {}; pid_t uid_ {}; + uint32_t token_ {}; uint32_t timerId_ {}; static std::vector GetConnectDevices();