1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "app_account_control_manager.h"
17
18 #include "accesstoken_kit.h"
19 #include "account_log_wrapper.h"
20 #include "account_permission_manager.h"
21 #include "app_account_check_labels_session.h"
22 #include "app_account_data_storage.h"
23 #include "app_account_info.h"
24 #include "app_account_subscribe_manager.h"
25 #ifdef HAS_ASSET_PART
26 #include "asset_system_api.h"
27 #endif
28 #include "bundle_manager_adapter.h"
29 #ifdef SQLITE_DLCLOSE_ENABLE
30 #include "database_adapter_loader.h"
31 #endif // SQLITE_DLCLOSE_ENABLE
32 #include "ipc_skeleton.h"
33 #include "iservice_registry.h"
34 #include "ohos_account_kits.h"
35 #include "singleton.h"
36 #include "system_ability_definition.h"
37
38 namespace OHOS {
39 namespace AccountSA {
40 namespace {
41 const char GET_ALL_APP_ACCOUNTS[] = "ohos.permission.GET_ALL_APP_ACCOUNTS";
42 const char DATA_STORAGE_SUFFIX[] = "_sync";
43 #ifndef SQLITE_DLCLOSE_ENABLE
44 const char DATA_STORAGE_PREFIX[] = "encrypt_";
45 #endif // SQLITE_DLCLOSE_ENABLE
46 const char EL2_DATA_STORE_PREFIX[] = "account_";
47 const char EL2_DATA_STORAGE_PATH_PREFIX[] = "/data/service/el2/";
48 const char EL2_DATA_STORAGE_PATH_SUFFIX[] = "/account/app_account/database/";
49 const char AUTHORIZED_ACCOUNTS[] = "authorizedAccounts";
50 const std::string HYPHEN = "#";
51 #ifdef HAS_ASSET_PART
52 const std::string ALIAS_SUFFIX_CREDENTIAL = "credential";
53 const std::string ALIAS_SUFFIX_TOKEN = "token";
54 #endif
55 }
56
57 #ifdef HAS_ASSET_PART
SaveDataToAsset(int32_t localId,const std::string & hapLabel,const std::string & accountLabel,const std::string & alias,const std::string & value)58 static ErrCode SaveDataToAsset(int32_t localId, const std::string &hapLabel, const std::string &accountLabel,
59 const std::string &alias, const std::string &value)
60 {
61 if (value.empty()) {
62 return ERR_OK;
63 }
64 AssetValue hapLabelValue = { .blob = { static_cast<uint32_t>(hapLabel.size()),
65 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(hapLabel.c_str())) } };
66 AssetValue accountLabelValue = { .blob = { static_cast<uint32_t>(accountLabel.size()),
67 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(accountLabel.c_str())) } };
68 AssetValue aliasValue = { .blob = { static_cast<uint32_t>(alias.size()),
69 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(alias.c_str())) } };
70 AssetValue secretValue = { .blob = { static_cast<uint32_t>(value.size()),
71 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(value.c_str())) } };
72 AssetValue accessibilityValue;
73 if (localId == 0) {
74 accessibilityValue.u32 = SEC_ASSET_ACCESSIBILITY_DEVICE_POWERED_ON;
75 } else {
76 accessibilityValue.u32 = SEC_ASSET_ACCESSIBILITY_DEVICE_UNLOCKED;
77 }
78 std::vector<AssetAttr> attrs = {
79 { .tag = SEC_ASSET_TAG_SECRET, .value = secretValue },
80 { .tag = SEC_ASSET_TAG_DATA_LABEL_NORMAL_1, .value = hapLabelValue },
81 { .tag = SEC_ASSET_TAG_DATA_LABEL_NORMAL_2, .value = accountLabelValue },
82 { .tag = SEC_ASSET_TAG_ACCESSIBILITY, .value = accessibilityValue },
83 { .tag = SEC_ASSET_TAG_ALIAS, .value = aliasValue }
84 };
85 uint32_t queryCnt = 1;
86 if (localId != 0) {
87 AssetValue localIdValue = { .u32 = localId };
88 attrs.push_back({ .tag = SEC_ASSET_TAG_USER_ID, .value = localIdValue });
89 queryCnt++;
90 }
91 const AssetAttr *attrArr = attrs.data();
92 ErrCode ret = AssetAdd(attrArr, attrs.size());
93 if (ret == SEC_ASSET_DUPLICATED) {
94 ret = AssetUpdate(&attrArr[4], queryCnt, attrArr, 1); // 4 indicates the index four
95 }
96 if (ret != ERR_OK) {
97 ACCOUNT_LOGE("fail to save data to asset, error code: %{public}d", ret);
98 }
99 return ret;
100 }
101
GetDataFromAsset(int32_t localId,const std::string & alias,std::string & value)102 static ErrCode GetDataFromAsset(int32_t localId, const std::string &alias, std::string &value)
103 {
104 AssetValue aliasValue = { .blob = { static_cast<uint32_t>(alias.size()),
105 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(alias.c_str())) } };
106 AssetValue u32Value = { .u32 = SEC_ASSET_RETURN_ALL };
107 std::vector<AssetAttr> attrs = {
108 { .tag = SEC_ASSET_TAG_ALIAS, .value = aliasValue },
109 { .tag = SEC_ASSET_TAG_RETURN_TYPE, .value = u32Value }
110 };
111 if (localId != 0) {
112 AssetValue localIdValue = { .u32 = localId };
113 attrs.push_back({ .tag = SEC_ASSET_TAG_USER_ID, .value = localIdValue });
114 }
115
116 AssetResultSet resultSet = {0};
117 ErrCode ret = AssetQuery(attrs.data(), attrs.size(), &resultSet);
118 if (ret != SEC_ASSET_SUCCESS) {
119 ACCOUNT_LOGE("fail to get data from asset, error code: %{public}d", ret);
120 } else {
121 AssetAttr *secret = AssetParseAttr(resultSet.results, SEC_ASSET_TAG_SECRET);
122 if (secret == nullptr) {
123 ACCOUNT_LOGE("secret is nullptr");
124 ret = ERR_ACCOUNT_COMMON_NULL_PTR_ERROR;
125 } else {
126 AssetBlob valueBlob = secret->value.blob;
127 value = std::string(reinterpret_cast<const char *>(valueBlob.data), valueBlob.size);
128 }
129 }
130 AssetFreeResultSet(&resultSet);
131 return ret;
132 }
133
RemoveDataFromAsset(int32_t localId,const std::string & alias)134 static ErrCode RemoveDataFromAsset(int32_t localId, const std::string &alias)
135 {
136 AssetValue aliasValue = { .blob = { static_cast<uint32_t>(alias.size()),
137 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(alias.c_str())) } };
138 std::vector<AssetAttr> attrs = {
139 { .tag = SEC_ASSET_TAG_ALIAS, .value = aliasValue }
140 };
141 if (localId != 0) {
142 AssetValue localIdValue = { .u32 = localId };
143 attrs.push_back({ .tag = SEC_ASSET_TAG_USER_ID, .value = localIdValue });
144 }
145
146 ErrCode ret = AssetRemove(attrs.data(), attrs.size());
147 if (ret != SEC_ASSET_SUCCESS) {
148 ACCOUNT_LOGE("fail to remove data from asset");
149 }
150 return ret;
151 }
152
RemoveDataFromAssetByLabel(int32_t localId,int32_t tag,const std::string & label)153 static ErrCode RemoveDataFromAssetByLabel(int32_t localId, int32_t tag, const std::string &label)
154 {
155 AssetValue labelValue = { .blob = { static_cast<uint32_t>(label.size()),
156 const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(label.c_str())) } };
157 std::vector<AssetAttr> attrs = { { .tag = tag, .value = labelValue } };
158 if (localId != 0) {
159 AssetValue localIdValue = { .u32 = localId };
160 attrs.push_back({ .tag = SEC_ASSET_TAG_USER_ID, .value = localIdValue });
161 }
162
163 ErrCode ret = AssetRemove(attrs.data(), attrs.size());
164 if (ret != SEC_ASSET_SUCCESS) {
165 ACCOUNT_LOGE("fail to remove data from asset");
166 }
167 return ret;
168 }
169 #endif
170
171 #ifndef SQLITE_DLCLOSE_ENABLE
MoveData()172 void AppAccountControlManager::MoveData()
173 {
174 DistributedKv::DistributedKvDataManager dataManager;
175 DistributedKv::AppId appId = { .appId = Constants::APP_ACCOUNT_APP_ID };
176 std::vector<DistributedKv::StoreId> storeIdList;
177 std::lock_guard<std::mutex> storeIdLock(storePtrMutex_);
178 OHOS::DistributedKv::Status status = dataManager.GetAllKvStoreId(appId, storeIdList);
179 if (status != OHOS::DistributedKv::Status::SUCCESS) {
180 ACCOUNT_LOGE("GetAllKvStoreId failed, status=%{public}u", status);
181 return;
182 }
183 std::lock_guard<std::mutex> accountIdLock(migratedAccountMutex_);
184 while (!migratedAccounts_.empty()) {
185 std::string userId = std::to_string(*(migratedAccounts_.begin()));
186 for (std::string &storeId : storeIdList) {
187 if (storeId.find(EL2_DATA_STORE_PREFIX) != std::string::npos
188 || storeId.find(userId) == std::string::npos) {
189 continue;
190 }
191 AccountDataStorageOptions options;
192 if (storeId.find(DATA_STORAGE_PREFIX) != std::string::npos) {
193 options.encrypt = true;
194 }
195 ACCOUNT_LOGI("MoveData start, storeId=%{public}s", storeId.c_str());
196 auto oldPtr = std::make_shared<AppAccountDataStorage>(storeId, options);
197 options.encrypt = false;
198 options.area = DistributedKv::EL2;
199 options.baseDir = EL2_DATA_STORAGE_PATH_PREFIX + userId + EL2_DATA_STORAGE_PATH_SUFFIX;
200 auto newPtr = std::make_shared<AppAccountDataStorage>(EL2_DATA_STORE_PREFIX + userId, options);
201 ErrCode result = newPtr->MoveData(oldPtr);
202 if (result != ERR_OK) {
203 ACCOUNT_LOGE("MoveData failed, storeId=%{public}s, result=%{public}u",
204 storeId.c_str(), result);
205 continue;
206 }
207 result = oldPtr->DeleteKvStore();
208 if (result != ERR_OK) {
209 ACCOUNT_LOGE("DeleteKvStore failed, storeId=%{public}s, result=%{public}u", storeId.c_str(), result);
210 }
211 }
212 migratedAccounts_.erase(migratedAccounts_.begin());
213 }
214 ACCOUNT_LOGI("MoveData complete");
215 }
216 #else
MoveData()217 void AppAccountControlManager::MoveData()
218 {
219 ACCOUNT_LOGI("MoveData not enabled.");
220 }
221 #endif // SQLITE_DLCLOSE_ENABLE
222
AddMigratedAccount(int32_t localId)223 void AppAccountControlManager::AddMigratedAccount(int32_t localId)
224 {
225 {
226 std::lock_guard<std::mutex> lock(migratedAccountMutex_);
227 migratedAccounts_.insert(localId);
228 }
229 MoveData();
230 }
231
GetInstance()232 AppAccountControlManager &AppAccountControlManager::GetInstance()
233 {
234 static AppAccountControlManager *instance = new (std::nothrow) AppAccountControlManager();
235 return *instance;
236 }
237
AddAccount(const std::string & name,const std::string & extraInfo,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)238 ErrCode AppAccountControlManager::AddAccount(const std::string &name, const std::string &extraInfo, const uid_t &uid,
239 const std::string &bundleName, AppAccountInfo &appAccountInfo)
240 {
241 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
242 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
243 if (result != ERR_OK) {
244 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
245
246 appAccountInfo.SetExtraInfo(extraInfo);
247
248 result = AddAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
249 if (result != ERR_OK) {
250 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
251 return result;
252 }
253 } else {
254 ACCOUNT_LOGE("add existing account");
255 return ERR_APPACCOUNT_SERVICE_ADD_EXISTING_ACCOUNT;
256 }
257
258 return ERR_OK;
259 }
260
CreateAccount(const std::string & name,const CreateAccountOptions & options,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)261 ErrCode AppAccountControlManager::CreateAccount(const std::string &name, const CreateAccountOptions &options,
262 const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
263 {
264 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
265 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
266 if (result != ERR_OK) {
267 result = appAccountInfo.InitCustomData(options.customData);
268 if (result != ERR_OK) {
269 ACCOUNT_LOGE("failed to set custom data, result %{public}d.", result);
270 return ERR_APPACCOUNT_SERVICE_SET_ASSOCIATED_DATA;
271 }
272 result = AddAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
273 if (result != ERR_OK) {
274 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
275 return result;
276 }
277 } else {
278 ACCOUNT_LOGE("add existing account");
279 return ERR_APPACCOUNT_SERVICE_ADD_EXISTING_ACCOUNT;
280 }
281
282 return ERR_OK;
283 }
284
DeleteAccount(const std::string & name,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)285 ErrCode AppAccountControlManager::DeleteAccount(
286 const std::string &name, const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
287 {
288 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
289 ErrCode result = DeleteAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr, uid);
290 if (result != ERR_OK) {
291 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
292 return result;
293 }
294 RemoveAssociatedDataCacheByAccount(uid, name);
295 #ifdef HAS_ASSET_PART
296 RemoveDataFromAssetByLabel(uid / UID_TRANSFORM_DIVISOR, SEC_ASSET_TAG_DATA_LABEL_NORMAL_2,
297 appAccountInfo.GetPrimeKey());
298 #endif
299
300 std::set<std::string> authorizedApps;
301 appAccountInfo.GetAuthorizedApps(authorizedApps);
302 for (auto authorizedApp : authorizedApps) {
303 // remove authorized account from data storage
304 result = RemoveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, uid);
305 if (result != ERR_OK) {
306 ACCOUNT_LOGE("failed to save authorized account into data storage, result %{public}d.", result);
307 return result;
308 }
309 }
310
311 return ERR_OK;
312 }
313
GetAccountExtraInfo(const std::string & name,std::string & extraInfo,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)314 ErrCode AppAccountControlManager::GetAccountExtraInfo(const std::string &name, std::string &extraInfo,
315 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
316 {
317 AppAccountInfo appAccountInfo(name, bundleName);
318 appAccountInfo.SetAppIndex(appIndex);
319 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
320 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
321 if (result != ERR_OK) {
322 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
323 return result;
324 }
325
326 appAccountInfo.GetExtraInfo(extraInfo);
327
328 return ERR_OK;
329 }
330
SetAccountExtraInfo(const std::string & name,const std::string & extraInfo,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)331 ErrCode AppAccountControlManager::SetAccountExtraInfo(const std::string &name, const std::string &extraInfo,
332 const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
333 {
334 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
335 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
336 if (result != ERR_OK) {
337 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
338 return result;
339 }
340
341 appAccountInfo.SetExtraInfo(extraInfo);
342
343 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
344 if (result != ERR_OK) {
345 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
346 return result;
347 }
348
349 ACCOUNT_LOGD("end, result = %{public}d", result);
350
351 return result;
352 }
353
EnableAppAccess(const std::string & name,const std::string & authorizedApp,AppAccountCallingInfo & appAccountCallingInfo,AppAccountInfo & appAccountInfo,const uint32_t apiVersion)354 ErrCode AppAccountControlManager::EnableAppAccess(const std::string &name, const std::string &authorizedApp,
355 AppAccountCallingInfo &appAccountCallingInfo, AppAccountInfo &appAccountInfo, const uint32_t apiVersion)
356 {
357 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
358 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
359 if (result != ERR_OK) {
360 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
361 return result;
362 }
363
364 result = appAccountInfo.EnableAppAccess(authorizedApp, apiVersion);
365 if (result != ERR_OK) {
366 ACCOUNT_LOGE("Failed to enable app access, result=%{public}d.", result);
367 return result;
368 }
369 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
370 if (result != ERR_OK) {
371 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
372 return result;
373 }
374
375 // save authorized account into data storage
376 result = SaveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
377 if (result != ERR_OK) {
378 ACCOUNT_LOGE("Failed to save authorized account into data storage, result=%{public}d.", result);
379 return result;
380 }
381
382 return ERR_OK;
383 }
384
DisableAppAccess(const std::string & name,const std::string & authorizedApp,AppAccountCallingInfo & appAccountCallingInfo,AppAccountInfo & appAccountInfo,const uint32_t apiVersion)385 ErrCode AppAccountControlManager::DisableAppAccess(const std::string &name, const std::string &authorizedApp,
386 AppAccountCallingInfo &appAccountCallingInfo, AppAccountInfo &appAccountInfo, const uint32_t apiVersion)
387 {
388 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
389 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
390 if (result != ERR_OK) {
391 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
392 return result;
393 }
394
395 result = appAccountInfo.DisableAppAccess(authorizedApp, apiVersion);
396 if (result != ERR_OK) {
397 ACCOUNT_LOGE("failed to disable app access, result %{public}d.", result);
398 return ERR_APPACCOUNT_SERVICE_DISABLE_APP_ACCESS_NOT_EXISTED;
399 }
400
401 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
402 if (result != ERR_OK) {
403 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
404 return result;
405 }
406
407 // remove authorized account from data storage
408 result = RemoveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
409 if (result != ERR_OK) {
410 ACCOUNT_LOGE("failed to save authorized account into data storage, result %{public}d.", result);
411 return result;
412 }
413
414 return ERR_OK;
415 }
416
CheckAppAccess(const std::string & name,const std::string & authorizedApp,bool & isAccessible,const AppAccountCallingInfo & appAccountCallingInfo)417 ErrCode AppAccountControlManager::CheckAppAccess(const std::string &name, const std::string &authorizedApp,
418 bool &isAccessible, const AppAccountCallingInfo &appAccountCallingInfo)
419 {
420 isAccessible = false;
421 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
422 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
423 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
424 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
425 if (result != ERR_OK) {
426 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
427 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
428 }
429 return appAccountInfo.CheckAppAccess(authorizedApp, isAccessible);
430 }
431
CheckAppAccountSyncEnable(const std::string & name,bool & syncEnable,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)432 ErrCode AppAccountControlManager::CheckAppAccountSyncEnable(const std::string &name,
433 bool &syncEnable, const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
434 {
435 AppAccountInfo appAccountInfo(name, bundleName);
436 appAccountInfo.SetAppIndex(appIndex);
437 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
438 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
439 if (result != ERR_OK) {
440 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
441 return result;
442 }
443
444 appAccountInfo.GetSyncEnable(syncEnable);
445
446 return ERR_OK;
447 }
448
SetAppAccountSyncEnable(const std::string & name,const bool & syncEnable,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)449 ErrCode AppAccountControlManager::SetAppAccountSyncEnable(const std::string &name, const bool &syncEnable,
450 const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
451 {
452 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
453 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
454 if (result != ERR_OK) {
455 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
456 return result;
457 }
458
459 appAccountInfo.SetSyncEnable(syncEnable);
460
461 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
462 if (result != ERR_OK) {
463 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
464 return result;
465 }
466
467 return ERR_OK;
468 }
469
PopDataFromAssociatedDataCache()470 void AppAccountControlManager::PopDataFromAssociatedDataCache()
471 {
472 auto it = associatedDataCache_.begin();
473 auto toPopedIt = it++;
474 for (; it != associatedDataCache_.end(); ++it) {
475 if (toPopedIt->second.freq > it->second.freq) {
476 toPopedIt = it;
477 }
478 it->second.freq = 0;
479 }
480 associatedDataCache_.erase(toPopedIt);
481 }
482
GetAssociatedDataFromStorage(const std::string & name,const std::string & key,std::string & value,const uid_t & uid,const uint32_t & appIndex)483 ErrCode AppAccountControlManager::GetAssociatedDataFromStorage(const std::string &name, const std::string &key,
484 std::string &value, const uid_t &uid, const uint32_t &appIndex)
485 {
486 std::string bundleName;
487 if (BundleManagerAdapter::GetInstance()->GetNameForUid(uid, bundleName) != ERR_OK) {
488 ACCOUNT_LOGE("failed to get bundle name");
489 return ERR_APPACCOUNT_SERVICE_GET_BUNDLE_NAME;
490 }
491 AppAccountInfo appAccountInfo(name, bundleName);
492 appAccountInfo.SetAppIndex(appIndex);
493 std::shared_ptr<AppAccountDataStorage> storePtr = GetDataStorage(uid);
494 if (storePtr == nullptr) {
495 ACCOUNT_LOGE("failed to get data storage");
496 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
497 }
498 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, storePtr);
499 if (result != ERR_OK) {
500 ACCOUNT_LOGE("failed to get account info from data storage");
501 return result;
502 }
503 AssociatedDataCacheItem item;
504 item.name = name;
505 item.freq = 0;
506 appAccountInfo.GetAllAssociatedData(item.data);
507 auto it = item.data.find(key);
508 if (it != item.data.end()) {
509 value = it->second;
510 } else {
511 result = ERR_APPACCOUNT_SERVICE_ASSOCIATED_DATA_KEY_NOT_EXIST;
512 }
513 if (associatedDataCache_.size() >= ASSOCIATED_DATA_CACHE_MAX_SIZE) {
514 PopDataFromAssociatedDataCache();
515 }
516 associatedDataCache_.emplace(uid, item);
517 return result;
518 }
519
GetAssociatedData(const std::string & name,const std::string & key,std::string & value,const uid_t & uid)520 ErrCode AppAccountControlManager::GetAssociatedData(const std::string &name, const std::string &key,
521 std::string &value, const uid_t &uid)
522 {
523 std::lock_guard<std::mutex> lock(associatedDataMutex_);
524 auto it = associatedDataCache_.find(uid);
525 if ((it == associatedDataCache_.end()) || (it->second.name != name)) {
526 uint32_t callingTokenId = IPCSkeleton::GetCallingTokenID();
527 Security::AccessToken::HapTokenInfo hapTokenInfo;
528 int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callingTokenId, hapTokenInfo);
529 if ((result != 0) || (hapTokenInfo.instIndex < 0)) {
530 ACCOUNT_LOGE("failed to get app index");
531 return ERR_APPACCOUNT_SERVICE_GET_APP_INDEX;
532 }
533 associatedDataCache_.erase(uid);
534 return GetAssociatedDataFromStorage(name, key, value, uid, hapTokenInfo.instIndex);
535 }
536 it->second.freq++;
537 auto dataIt = it->second.data.find(key);
538 if (dataIt == it->second.data.end()) {
539 return ERR_APPACCOUNT_SERVICE_ASSOCIATED_DATA_KEY_NOT_EXIST;
540 }
541 value = dataIt->second;
542 return ERR_OK;
543 }
544
SetAssociatedData(const std::string & name,const std::string & key,const std::string & value,const AppAccountCallingInfo & appAccountCallingInfo)545 ErrCode AppAccountControlManager::SetAssociatedData(const std::string &name, const std::string &key,
546 const std::string &value, const AppAccountCallingInfo &appAccountCallingInfo)
547 {
548 std::shared_ptr<AppAccountDataStorage> storePtr = GetDataStorage(appAccountCallingInfo.callingUid);
549 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
550 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
551 std::lock_guard<std::mutex> lock(associatedDataMutex_);
552 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, storePtr);
553 if (result != ERR_OK) {
554 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
555 return result;
556 }
557 result = appAccountInfo.SetAssociatedData(key, value);
558 if (result != ERR_OK) {
559 ACCOUNT_LOGE("failed to set associated data, result %{public}d.", result);
560 return result;
561 }
562 result = SaveAccountInfoIntoDataStorage(appAccountInfo, storePtr, appAccountCallingInfo.callingUid);
563 if (result != ERR_OK) {
564 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
565 return result;
566 }
567 auto it = associatedDataCache_.find(appAccountCallingInfo.callingUid);
568 if ((it != associatedDataCache_.end()) && (it->second.name == name)) {
569 it->second.data[key] = value;
570 }
571 return ERR_OK;
572 }
573
GetAccountCredential(const std::string & name,const std::string & credentialType,std::string & credential,const AppAccountCallingInfo & appAccountCallingInfo)574 ErrCode AppAccountControlManager::GetAccountCredential(const std::string &name, const std::string &credentialType,
575 std::string &credential, const AppAccountCallingInfo &appAccountCallingInfo)
576 {
577 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
578 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
579 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid, false);
580 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
581 if (result != ERR_OK) {
582 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
583 return result;
584 }
585
586 result = appAccountInfo.GetAccountCredential(credentialType, credential);
587 if (result != ERR_OK) {
588 return result;
589 }
590 #ifdef HAS_ASSET_PART
591 std::string alias = credential;
592 credential = "";
593 GetDataFromAsset(appAccountCallingInfo.callingUid / UID_TRANSFORM_DIVISOR, alias, credential);
594 #endif
595 return result;
596 }
597
SetAccountCredential(const std::string & name,const std::string & credentialType,const std::string & credential,const AppAccountCallingInfo & appAccountCallingInfo)598 ErrCode AppAccountControlManager::SetAccountCredential(const std::string &name, const std::string &credentialType,
599 const std::string &credential, const AppAccountCallingInfo &appAccountCallingInfo)
600 {
601 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid, false);
602 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
603 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
604 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
605 if (result != ERR_OK) {
606 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
607 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
608 }
609 result = appAccountInfo.SetAccountCredential(credentialType, credential);
610 if (result != ERR_OK) {
611 ACCOUNT_LOGE("failed to set account credential, result %{public}d.", result);
612 return result;
613 }
614
615 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
616 if (result != ERR_OK) {
617 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
618 return result;
619 }
620 #ifdef HAS_ASSET_PART
621 std::string hapLabel = appAccountCallingInfo.bundleName + Constants::HYPHEN +
622 std::to_string(appAccountCallingInfo.appIndex);
623 std::string credentialAlias;
624 appAccountInfo.GetAccountCredential(credentialType, credentialAlias);
625 int32_t localId = appAccountCallingInfo.callingUid / UID_TRANSFORM_DIVISOR;
626 result = SaveDataToAsset(localId, hapLabel, appAccountInfo.GetAlias(), credentialAlias, credential);
627 #endif
628 return result;
629 }
630
DeleteAccountCredential(const std::string & name,const std::string & credentialType,const AppAccountCallingInfo & callingInfo)631 ErrCode AppAccountControlManager::DeleteAccountCredential(const std::string &name, const std::string &credentialType,
632 const AppAccountCallingInfo &callingInfo)
633 {
634 AppAccountInfo appAccountInfo(name, callingInfo.bundleName);
635 appAccountInfo.SetAppIndex(callingInfo.appIndex);
636 auto dataStoragePtr = GetDataStorage(callingInfo.callingUid, false);
637 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
638 if (result != ERR_OK) {
639 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
640 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
641 }
642 #ifdef HAS_ASSET_PART
643 std::string alias;
644 appAccountInfo.GetAccountCredential(credentialType, alias);
645 RemoveDataFromAsset(callingInfo.callingUid / UID_TRANSFORM_DIVISOR, alias);
646 #endif
647 result = appAccountInfo.DeleteAccountCredential(credentialType);
648 if (result != ERR_OK) {
649 ACCOUNT_LOGE("failed to delete account credential, result %{public}d.", result);
650 return result;
651 }
652
653 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, callingInfo.callingUid);
654 if (result != ERR_OK) {
655 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
656 }
657 return result;
658 }
659
GetOAuthToken(const AuthenticatorSessionRequest & request,std::string & token,const uint32_t apiVersion)660 ErrCode AppAccountControlManager::GetOAuthToken(
661 const AuthenticatorSessionRequest &request, std::string &token, const uint32_t apiVersion)
662 {
663 AppAccountInfo appAccountInfo(request.name, request.owner);
664 appAccountInfo.SetAppIndex(0);
665 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid, false);
666 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
667 if (result != ERR_OK) {
668 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
669 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
670 }
671 bool isVisible = false;
672 result = appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.callerBundleName +
673 GetBundleKeySuffix(request.appIndex), isVisible, apiVersion);
674 if ((result != ERR_OK) || (!isVisible)) {
675 ACCOUNT_LOGE("failed to get oauth token for permission denied, result %{public}d.", result);
676 return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
677 }
678 result = appAccountInfo.GetOAuthToken(request.authType, token, apiVersion);
679 if (result != ERR_OK) {
680 return result;
681 }
682 #ifdef HAS_ASSET_PART
683 std::string alias = token;
684 token = "";
685 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, token);
686 if (token.empty() && (apiVersion < Constants::API_VERSION9)) {
687 return ERR_APPACCOUNT_SERVICE_OAUTH_TOKEN_NOT_EXIST;
688 }
689 #endif
690 return ERR_OK;
691 }
692
SetOAuthToken(const AuthenticatorSessionRequest & request)693 ErrCode AppAccountControlManager::SetOAuthToken(const AuthenticatorSessionRequest &request)
694 {
695 std::lock_guard<std::mutex> lock(mutex_);
696 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
697 appAccountInfo.SetAppIndex(request.appIndex);
698 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid, false);
699 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
700 if (result != ERR_OK) {
701 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
702 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
703 }
704 result = appAccountInfo.SetOAuthToken(request.authType, request.token);
705 if (result != ERR_OK) {
706 ACCOUNT_LOGE("failed to set oauth token, result %{public}d.", result);
707 return result;
708 }
709 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
710 if (result != ERR_OK) {
711 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
712 return result;
713 }
714 #ifdef HAS_ASSET_PART
715 std::string hapLabel = request.callerBundleName + Constants::HYPHEN + std::to_string(request.appIndex);
716 std::string authTypeAlias;
717 appAccountInfo.GetOAuthToken(request.authType, authTypeAlias);
718 int32_t localId = request.callerUid / UID_TRANSFORM_DIVISOR;
719 result = SaveDataToAsset(localId, hapLabel, appAccountInfo.GetAlias(), authTypeAlias, request.token);
720 #endif
721 return result;
722 }
723
DeleteOAuthToken(const AuthenticatorSessionRequest & request,const uint32_t apiVersion)724 ErrCode AppAccountControlManager::DeleteOAuthToken(
725 const AuthenticatorSessionRequest &request, const uint32_t apiVersion)
726 {
727 std::lock_guard<std::mutex> lock(mutex_);
728 AppAccountInfo appAccountInfo(request.name, request.owner);
729 appAccountInfo.SetAppIndex(0);
730 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
731 ErrCode ret = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
732 if (ret != ERR_OK) {
733 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", ret);
734 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
735 }
736 bool isVisible = false;
737 ret = appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.callerBundleName +
738 GetBundleKeySuffix(request.appIndex), isVisible, apiVersion);
739 if ((!isVisible) || (ret != ERR_OK)) {
740 ACCOUNT_LOGE("failed to delete oauth token for permission denied, result %{public}d.", ret);
741 return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
742 }
743 std::string token = request.token;
744 #ifdef HAS_ASSET_PART
745 std::string alias;
746 ret = appAccountInfo.GetOAuthToken(request.authType, alias, apiVersion);
747 if (ret != ERR_OK) {
748 return apiVersion >= Constants::API_VERSION9 ? ret : ERR_OK;
749 }
750 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, token);
751 if (token != request.token) {
752 return ERR_OK;
753 }
754 RemoveDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias);
755 token = alias;
756 #endif
757 if (apiVersion >= Constants::API_VERSION9) {
758 bool isOwnerSelf = request.owner == request.callerBundleName;
759 ret = appAccountInfo.DeleteAuthToken(request.authType, token, isOwnerSelf);
760 if (ret != ERR_OK) {
761 return ret;
762 }
763 } else {
764 ret = appAccountInfo.DeleteOAuthToken(request.authType, token);
765 if (ret == ERR_APPACCOUNT_SERVICE_OAUTH_TOKEN_NOT_EXIST) {
766 return ERR_OK;
767 }
768 }
769 ret = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
770 if (ret != ERR_OK) {
771 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", ret);
772 return ret;
773 }
774 return ret;
775 }
776
SetOAuthTokenVisibility(const AuthenticatorSessionRequest & request,const uint32_t apiVersion)777 ErrCode AppAccountControlManager::SetOAuthTokenVisibility(
778 const AuthenticatorSessionRequest &request, const uint32_t apiVersion)
779 {
780 std::lock_guard<std::mutex> lock(mutex_);
781 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
782 appAccountInfo.SetAppIndex(request.appIndex);
783 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
784 ErrCode ret = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
785 if (ret != ERR_OK) {
786 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", ret);
787 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
788 }
789 ret = appAccountInfo.SetOAuthTokenVisibility(
790 request.authType, request.bundleName, request.isTokenVisible, apiVersion);
791 if (ret != ERR_OK) {
792 ACCOUNT_LOGE("failed to set oauth token visibility, result %{public}d.", ret);
793 return ret;
794 }
795 ret = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
796 if (ret != ERR_OK) {
797 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", ret);
798 return ret;
799 }
800 return ERR_OK;
801 }
802
CheckOAuthTokenVisibility(const AuthenticatorSessionRequest & request,bool & isVisible,const uint32_t apiVersion)803 ErrCode AppAccountControlManager::CheckOAuthTokenVisibility(
804 const AuthenticatorSessionRequest &request, bool &isVisible, const uint32_t apiVersion)
805 {
806 isVisible = false;
807 AppAccountInfo appAccountInfo(request.name, request.owner);
808 appAccountInfo.SetAppIndex(request.appIndex);
809 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
810 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
811 if (result != ERR_OK) {
812 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
813 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
814 }
815 return appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.bundleName, isVisible, apiVersion);
816 }
817
GetAllOAuthTokens(const AuthenticatorSessionRequest & request,std::vector<OAuthTokenInfo> & tokenInfos)818 ErrCode AppAccountControlManager::GetAllOAuthTokens(
819 const AuthenticatorSessionRequest &request, std::vector<OAuthTokenInfo> &tokenInfos)
820 {
821 tokenInfos.clear();
822 AppAccountInfo appAccountInfo(request.name, request.owner);
823 appAccountInfo.SetAppIndex(0);
824 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
825 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
826 if (result != ERR_OK) {
827 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
828 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
829 }
830 std::string bundleKey = request.callerBundleName + GetBundleKeySuffix(request.appIndex);
831 std::vector<OAuthTokenInfo> allTokenInfos;
832 result = appAccountInfo.GetAllOAuthTokens(allTokenInfos);
833 if (result != ERR_OK) {
834 ACCOUNT_LOGE("failed to get all oauth token from data storage, result %{public}d.", result);
835 return result;
836 }
837 for (auto tokenInfo : allTokenInfos) {
838 if ((bundleKey != request.owner) &&
839 (tokenInfo.authList.find(bundleKey) == tokenInfo.authList.end())) {
840 continue;
841 }
842 #ifdef HAS_ASSET_PART
843 std::string alias = tokenInfo.token;
844 tokenInfo.token = "";
845 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, tokenInfo.token);
846 #endif
847 if (tokenInfo.token.empty() && tokenInfo.authList.empty()) { // for api 8 logic
848 continue;
849 }
850 tokenInfo.authList.clear();
851 tokenInfos.push_back(tokenInfo);
852 }
853 return ERR_OK;
854 }
855
GetOAuthList(const AuthenticatorSessionRequest & request,std::set<std::string> & oauthList,const uint32_t apiVersion)856 ErrCode AppAccountControlManager::GetOAuthList(
857 const AuthenticatorSessionRequest &request, std::set<std::string> &oauthList, const uint32_t apiVersion)
858 {
859 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
860 appAccountInfo.SetAppIndex(request.appIndex);
861 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
862 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
863 if (result != ERR_OK) {
864 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
865 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
866 }
867 return appAccountInfo.GetOAuthList(request.authType, oauthList, apiVersion);
868 }
869
GetBundleKeySuffix(const uint32_t & appIndex)870 std::string AppAccountControlManager::GetBundleKeySuffix(const uint32_t &appIndex)
871 {
872 return (appIndex == 0 ? "" : HYPHEN + std::to_string(appIndex));
873 }
874
GetAllAccounts(const std::string & owner,std::vector<AppAccountInfo> & appAccounts,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)875 ErrCode AppAccountControlManager::GetAllAccounts(const std::string &owner, std::vector<AppAccountInfo> &appAccounts,
876 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
877 {
878 appAccounts.clear();
879
880 auto dataStoragePtr = GetDataStorage(uid);
881 if (dataStoragePtr == nullptr) {
882 ACCOUNT_LOGE("dataStoragePtr is nullptr");
883 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
884 }
885 ErrCode result = AccountPermissionManager::VerifyPermission(GET_ALL_APP_ACCOUNTS);
886 std::string bundleKey = bundleName + GetBundleKeySuffix(appIndex);
887 if ((bundleKey == owner) || (result == ERR_OK)) {
888 std::string key = owner + Constants::HYPHEN + std::to_string(0);
889 result = GetAllAccountsFromDataStorage(key, appAccounts, owner, dataStoragePtr);
890 if (result != ERR_OK) {
891 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
892 return result;
893 }
894 return ERR_OK;
895 }
896
897 std::vector<std::string> accessibleAccounts;
898 result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleKey, accessibleAccounts);
899 if (result != ERR_OK) {
900 ACCOUNT_LOGE("failed to get accessible account from data storage, result %{public}d.", result);
901 return result;
902 }
903 for (auto account : accessibleAccounts) {
904 AppAccountInfo appAccountInfo;
905 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
906 if (result != ERR_OK) {
907 ACCOUNT_LOGE("failed to get account info by id, result %{public}d.", result);
908 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
909 }
910 if (appAccountInfo.GetOwner() == owner && AppAccountSubscribeManager::CheckAppIsMaster(account)) {
911 appAccounts.emplace_back(appAccountInfo);
912 }
913 }
914 return ERR_OK;
915 }
916
LoadAllAppAccounts(const std::shared_ptr<OHOS::AccountSA::AppAccountDataStorage> & dataStoragePtr,std::vector<AppAccountInfo> & appAccounts)917 static ErrCode LoadAllAppAccounts(const std::shared_ptr<OHOS::AccountSA::AppAccountDataStorage> &dataStoragePtr,
918 std::vector<AppAccountInfo> &appAccounts)
919 {
920 std::map<std::string, std::shared_ptr<IAccountInfo>> infos;
921 ErrCode result = dataStoragePtr->LoadAllData(infos);
922 if (result != ERR_OK) {
923 ACCOUNT_LOGE("LoadAllData failed!");
924 return result;
925 }
926 for (auto it = infos.begin(); it != infos.end(); ++it) {
927 if (it->first == AUTHORIZED_ACCOUNTS) {
928 continue;
929 }
930 AppAccountInfo curAppInfo = *(std::static_pointer_cast<AppAccountInfo>(it->second));
931 appAccounts.emplace_back(curAppInfo);
932 }
933 return ERR_OK;
934 }
935
GetAllAccessibleAccounts(std::vector<AppAccountInfo> & appAccounts,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)936 ErrCode AppAccountControlManager::GetAllAccessibleAccounts(std::vector<AppAccountInfo> &appAccounts,
937 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
938 {
939 appAccounts.clear();
940
941 auto dataStoragePtr = GetDataStorage(uid);
942 if (dataStoragePtr == nullptr) {
943 ACCOUNT_LOGE("dataStoragePtr is nullptr");
944 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
945 }
946 ErrCode result = AccountPermissionManager::VerifyPermission(GET_ALL_APP_ACCOUNTS);
947 if (result == ERR_OK) {
948 return LoadAllAppAccounts(dataStoragePtr, appAccounts);
949 }
950 std::vector<std::string> accessibleAccounts;
951 result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleName, accessibleAccounts);
952 if (result != ERR_OK) {
953 ACCOUNT_LOGE("failed to get accessible account from data storage, result %{public}d.", result);
954 return result;
955 }
956
957 for (auto account : accessibleAccounts) {
958 AppAccountInfo appAccountInfo;
959
960 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
961 if (result != ERR_OK) {
962 ACCOUNT_LOGE("failed to get account info by id, result %{public}d.", result);
963 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
964 }
965
966 appAccounts.emplace_back(appAccountInfo);
967 }
968
969 std::vector<AppAccountInfo> currentAppAccounts;
970 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
971 result = GetAllAccountsFromDataStorage(key, currentAppAccounts, bundleName, dataStoragePtr);
972 if (result != ERR_OK) {
973 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
974 return result;
975 }
976
977 std::transform(currentAppAccounts.begin(), currentAppAccounts.end(), std::back_inserter(appAccounts),
978 [](auto account) { return account; });
979
980 return ERR_OK;
981 }
982
SelectAccountsByOptions(const SelectAccountsOptions & options,const sptr<IAppAccountAuthenticatorCallback> & callback,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)983 ErrCode AppAccountControlManager::SelectAccountsByOptions(
984 const SelectAccountsOptions &options, const sptr<IAppAccountAuthenticatorCallback> &callback,
985 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
986 {
987 AAFwk::Want result;
988 if ((!options.hasAccounts) && (!options.hasOwners) && (!options.hasLabels)) {
989 callback->OnResult(ERR_JS_SUCCESS, result);
990 return ERR_OK;
991 }
992 std::set<std::string> allowedAccounts;
993 for (auto account : options.allowedAccounts) {
994 allowedAccounts.emplace(account.first + "_" + account.second);
995 }
996 std::set<std::string> allowedOwners(options.allowedOwners.begin(), options.allowedOwners.end());
997 std::vector<AppAccountInfo> accessibleAccounts;
998 ErrCode errCode = GetAllAccessibleAccounts(accessibleAccounts, uid, bundleName, appIndex);
999 if (errCode != ERR_OK) {
1000 ACCOUNT_LOGE("failed to get all accessible accounts");
1001 return errCode;
1002 }
1003 std::vector<AppAccountInfo> candidateAccounts;
1004 for (auto account : accessibleAccounts) {
1005 std::string owner = account.GetOwner();
1006 if (options.hasOwners && allowedOwners.count(owner) == 0) {
1007 continue;
1008 }
1009 if (options.hasAccounts && allowedAccounts.count(owner + "_" + account.GetName()) == 0) {
1010 continue;
1011 }
1012 candidateAccounts.push_back(account);
1013 }
1014 if (options.requiredLabels.size() == 0) {
1015 std::vector<std::string> names;
1016 std::vector<std::string> owners;
1017 for (auto account : candidateAccounts) {
1018 names.push_back(account.GetName());
1019 owners.push_back(account.GetOwner());
1020 }
1021 result.SetParam(Constants::KEY_ACCOUNT_NAMES, names);
1022 result.SetParam(Constants::KEY_ACCOUNT_OWNERS, owners);
1023 callback->OnResult(ERR_JS_SUCCESS, result);
1024 return ERR_OK;
1025 }
1026 AuthenticatorSessionRequest request;
1027 request.callback = callback;
1028 request.callerUid = uid;
1029 request.labels = options.requiredLabels;
1030 return AppAccountAuthenticatorSessionManager::GetInstance().SelectAccountsByOptions(candidateAccounts, request);
1031 }
1032
RemoveAssociatedDataCacheByUid(const uid_t & uid)1033 void AppAccountControlManager::RemoveAssociatedDataCacheByUid(const uid_t &uid)
1034 {
1035 std::lock_guard<std::mutex> lock(associatedDataMutex_);
1036 associatedDataCache_.erase(uid);
1037 }
1038
RemoveAssociatedDataCacheByAccount(const uid_t & uid,const std::string & name)1039 void AppAccountControlManager::RemoveAssociatedDataCacheByAccount(const uid_t &uid, const std::string &name)
1040 {
1041 std::lock_guard<std::mutex> lock(associatedDataMutex_);
1042 auto it = associatedDataCache_.find(uid);
1043 if ((it == associatedDataCache_.end()) || (it->second.name != name)) {
1044 return;
1045 }
1046 associatedDataCache_.erase(it);
1047 }
1048
SetOsAccountRemoved(int32_t localId,bool isRemoved)1049 void AppAccountControlManager::SetOsAccountRemoved(int32_t localId, bool isRemoved)
1050 {
1051 if (isRemoved) {
1052 removedOsAccounts_.EnsureInsert(localId, true);
1053 } else {
1054 removedOsAccounts_.Erase(localId);
1055 }
1056 }
1057
IsOsAccountRemoved(int32_t localId)1058 bool AppAccountControlManager::IsOsAccountRemoved(int32_t localId)
1059 {
1060 bool isRemoved = false;
1061 return removedOsAccounts_.Find(localId, isRemoved);
1062 }
1063
OnPackageRemoved(const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)1064 ErrCode AppAccountControlManager::OnPackageRemoved(
1065 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
1066 {
1067 RemoveAssociatedDataCacheByUid(uid);
1068 int32_t localId = uid / UID_TRANSFORM_DIVISOR;
1069 if (IsOsAccountRemoved(localId)) {
1070 ACCOUNT_LOGI("Account %{public}d is removed", localId);
1071 return ERR_OK;
1072 }
1073 ErrCode errCode = RemoveAppAccountData(uid, bundleName, appIndex);
1074 CloseDataStorage();
1075 return errCode;
1076 }
1077
RemoveAppAccountData(const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)1078 ErrCode AppAccountControlManager::RemoveAppAccountData(
1079 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
1080 {
1081 auto dataStoragePtr = GetDataStorage(uid);
1082 if (dataStoragePtr == nullptr) {
1083 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1084 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1085 }
1086 #ifdef DISTRIBUTED_FEATURE_ENABLED
1087 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1088 if (dataStorageSyncPtr == nullptr) {
1089 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1090 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1091 }
1092 #endif // DISTRIBUTED_FEATURE_ENABLED
1093 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1094 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
1095 ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(key, accounts);
1096 if (result != ERR_OK) {
1097 ACCOUNT_LOGE("failed to get accounts by owner, result %{public}d, bundleName = %{public}s",
1098 result, bundleName.c_str());
1099 return result;
1100 }
1101 AppAccountInfo appAccountInfo;
1102 for (auto account : accounts) {
1103 appAccountInfo = *(std::static_pointer_cast<AppAccountInfo>(account.second));
1104 std::set<std::string> authorizedApps;
1105 appAccountInfo.GetAuthorizedApps(authorizedApps);
1106 appAccountInfo.SetAppIndex(appIndex);
1107 for (auto authorizedApp : authorizedApps) {
1108 RemoveAuthorizedAccountFromDataStorage(authorizedApp, appAccountInfo, dataStoragePtr);
1109 #ifdef DISTRIBUTED_FEATURE_ENABLED
1110 if (NeedSyncDataStorage(appAccountInfo) == true) {
1111 RemoveAuthorizedAccountFromDataStorage(authorizedApp, appAccountInfo, dataStorageSyncPtr);
1112 }
1113 #endif // DISTRIBUTED_FEATURE_ENABLED
1114 }
1115 dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1116 #ifdef DISTRIBUTED_FEATURE_ENABLED
1117 if (NeedSyncDataStorage(appAccountInfo) == true) {
1118 dataStorageSyncPtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1119 }
1120 #else // DISTRIBUTED_FEATURE_ENABLED
1121 ACCOUNT_LOGI("No distributed feature!");
1122 #endif // DISTRIBUTED_FEATURE_ENABLED
1123 }
1124 #ifdef HAS_ASSET_PART
1125 RemoveDataFromAssetByLabel(uid / UID_TRANSFORM_DIVISOR, SEC_ASSET_TAG_DATA_LABEL_NORMAL_1, key);
1126 #endif
1127 return ERR_OK;
1128 }
1129
OnUserStopping(int32_t userId)1130 ErrCode AppAccountControlManager::OnUserStopping(int32_t userId)
1131 {
1132 std::string storeId = std::to_string(userId);
1133 std::string syncStoreId = storeId + DATA_STORAGE_SUFFIX;
1134 std::lock_guard<std::mutex> lock(storePtrMutex_);
1135 storePtrMap_.erase(storeId);
1136 storePtrMap_.erase(syncStoreId);
1137 return ERR_OK;
1138 }
1139
OnUserRemoved(int32_t userId)1140 ErrCode AppAccountControlManager::OnUserRemoved(int32_t userId)
1141 {
1142 return OnUserStopping(userId);
1143 }
1144
GetAllAccountsFromDataStorage(const std::string & owner,std::vector<AppAccountInfo> & appAccounts,const std::string & bundleName,const std::shared_ptr<AppAccountDataStorage> & dataStoragePtr)1145 ErrCode AppAccountControlManager::GetAllAccountsFromDataStorage(const std::string &owner,
1146 std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName,
1147 const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1148 {
1149 appAccounts.clear();
1150
1151 if (dataStoragePtr == nullptr) {
1152 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1153 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1154 }
1155
1156 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1157 ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(owner, accounts);
1158 if (result != ERR_OK) {
1159 ACCOUNT_LOGE("failed to get accounts by owner, result = %{public}d, owner = %{public}s",
1160 result, owner.c_str());
1161 return result;
1162 }
1163
1164 std::transform(accounts.begin(), accounts.end(), std::back_inserter(appAccounts),
1165 [](auto account) { return *(std::static_pointer_cast<AppAccountInfo>(account.second)); });
1166
1167 return ERR_OK;
1168 }
1169
GetAllAccessibleAccountsFromDataStorage(std::vector<AppAccountInfo> & appAccounts,const std::string & bundleName,const std::shared_ptr<AppAccountDataStorage> & dataStoragePtr,const uint32_t & appIndex)1170 ErrCode AppAccountControlManager::GetAllAccessibleAccountsFromDataStorage(
1171 std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName,
1172 const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uint32_t &appIndex)
1173 {
1174 appAccounts.clear();
1175
1176 if (dataStoragePtr == nullptr) {
1177 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1178 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1179 }
1180
1181 std::vector<std::string> accessibleAccounts;
1182 ErrCode result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleName, accessibleAccounts);
1183 if (result != ERR_OK) {
1184 ACCOUNT_LOGE("failed to get accessible account from data storage, result = %{public}d.", result);
1185 return result;
1186 }
1187
1188 for (auto account : accessibleAccounts) {
1189 if (!AppAccountSubscribeManager::CheckAppIsMaster(account)) {
1190 continue;
1191 }
1192 AppAccountInfo appAccountInfo;
1193
1194 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
1195 if (result != ERR_OK) {
1196 ACCOUNT_LOGE("failed to get account info by id. result %{public}d.", result);
1197 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
1198 }
1199
1200 appAccounts.emplace_back(appAccountInfo);
1201 }
1202
1203 std::vector<AppAccountInfo> currentAppAccounts;
1204 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
1205 result = GetAllAccountsFromDataStorage(key, currentAppAccounts, bundleName, dataStoragePtr);
1206 if (result != ERR_OK) {
1207 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
1208 return result;
1209 }
1210
1211 std::transform(currentAppAccounts.begin(), currentAppAccounts.end(), std::back_inserter(appAccounts),
1212 [](auto account) { return account; });
1213
1214 return ERR_OK;
1215 }
1216
1217 #ifndef SQLITE_DLCLOSE_ENABLE
GetDataStorageByUserId(int32_t userId,const bool & autoSync,DistributedKv::SecurityLevel securityLevel)1218 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorageByUserId(
1219 int32_t userId, const bool &autoSync, DistributedKv::SecurityLevel securityLevel)
1220 {
1221 std::string storeId = std::to_string(userId);
1222 if (autoSync == true) {
1223 storeId = storeId + DATA_STORAGE_SUFFIX;
1224 }
1225 std::lock_guard<std::mutex> lock(storePtrMutex_);
1226 auto it = storePtrMap_.find(storeId);
1227 if ((it != storePtrMap_.end()) && (it->second != nullptr)) {
1228 return it->second;
1229 }
1230 AccountDataStorageOptions options;
1231 options.area = DistributedKv::EL2;
1232 #else
1233 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorageByUserId(
1234 int32_t userId, const bool &autoSync, DbAdapterSecurityLevel securityLevel)
1235 {
1236 std::string storeId = std::to_string(userId);
1237 if (autoSync == true) {
1238 storeId = storeId + DATA_STORAGE_SUFFIX;
1239 }
1240 std::lock_guard<std::mutex> lock(storePtrMutex_);
1241 auto it = storePtrMap_.find(storeId);
1242 if ((it != storePtrMap_.end()) && (it->second != nullptr)) {
1243 return it->second;
1244 }
1245 DbAdapterOptions options;
1246 options.area = DbAdapterArea::EL2;
1247 #endif // SQLITE_DLCLOSE_ENABLE
1248 options.autoSync = autoSync;
1249 options.securityLevel = securityLevel;
1250 options.baseDir = EL2_DATA_STORAGE_PATH_PREFIX + std::to_string(userId) + EL2_DATA_STORAGE_PATH_SUFFIX;
1251 auto storePtr = std::make_shared<AppAccountDataStorage>(EL2_DATA_STORE_PREFIX + storeId, options);
1252 storePtrMap_[storeId] = storePtr;
1253 return storePtr;
1254 }
1255
1256 #ifndef SQLITE_DLCLOSE_ENABLE
1257 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorage(
1258 const uid_t &uid, const bool &autoSync, DistributedKv::SecurityLevel securityLevel)
1259 #else
1260 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorage(
1261 const uid_t &uid, const bool &autoSync, DbAdapterSecurityLevel securityLevel)
1262 #endif // SQLITE_DLCLOSE_ENABLE
1263 {
1264 return GetDataStorageByUserId(uid / UID_TRANSFORM_DIVISOR, autoSync, securityLevel);
1265 }
1266
1267 void AppAccountControlManager::CloseDataStorage()
1268 {
1269 if (!storePtrMutex_.try_lock()) {
1270 return;
1271 }
1272 for (auto &item : storePtrMap_) {
1273 if (item.second == nullptr || item.second.use_count() > 1) {
1274 continue;
1275 }
1276 ErrCode result = item.second->Close();
1277 if (result == ERR_OK) {
1278 item.second = nullptr;
1279 }
1280 ACCOUNT_LOGI("Close storage, storeId: %{public}s, result: %{public}d", item.first.c_str(), result);
1281 }
1282 #ifdef SQLITE_DLCLOSE_ENABLE
1283 bool dlCloseRet = DatabaseAdapterLoader::GetInstance().CheckAndUnload();
1284 ACCOUNT_LOGI("Close so end, ret: %{public}d", dlCloseRet);
1285 #endif // SQLITE_DLCLOSE_ENABLE
1286 storePtrMutex_.unlock();
1287 }
1288
1289 bool AppAccountControlManager::NeedSyncDataStorage(const AppAccountInfo &appAccountInfo)
1290 {
1291 bool syncEnable = false;
1292 appAccountInfo.GetSyncEnable(syncEnable);
1293
1294 if (syncEnable == false) {
1295 return false;
1296 }
1297 return true;
1298 }
1299
1300 ErrCode AppAccountControlManager::GetAccountInfoFromDataStorage(
1301 AppAccountInfo &appAccountInfo, std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1302 {
1303 if (dataStoragePtr == nullptr) {
1304 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1305 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1306 }
1307
1308 return dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);
1309 }
1310
1311 ErrCode AppAccountControlManager::AddAccountInfoIntoDataStorage(
1312 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1313 {
1314 if (dataStoragePtr == nullptr) {
1315 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1316 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1317 }
1318
1319 std::string owner;
1320 appAccountInfo.GetOwner(owner);
1321
1322 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1323 std::string key = owner + Constants::HYPHEN + std::to_string(appAccountInfo.GetAppIndex());
1324 ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(key, accounts);
1325 if (result != ERR_OK) {
1326 ACCOUNT_LOGE("failed to get accounts by owner, result %{public}d, owner = %{public}s",
1327 result, owner.c_str());
1328 return result;
1329 }
1330
1331 if (accounts.size() >= ACCOUNT_MAX_SIZE) {
1332 ACCOUNT_LOGE("account exceeds max size");
1333 return ERR_APPACCOUNT_SERVICE_ACCOUNT_MAX_SIZE;
1334 }
1335
1336 result = dataStoragePtr->AddAccountInfoIntoDataStorage(appAccountInfo);
1337 if (result != ERR_OK) {
1338 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
1339 return result;
1340 }
1341
1342 // for sync data storage
1343 #ifdef DISTRIBUTED_FEATURE_ENABLED
1344 if (NeedSyncDataStorage(appAccountInfo) == true) {
1345 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1346 if (dataStorageSyncPtr == nullptr) {
1347 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1348 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1349 }
1350
1351 result = dataStorageSyncPtr->AddAccountInfoIntoDataStorage(appAccountInfo);
1352 if (result != ERR_OK) {
1353 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
1354 return result;
1355 }
1356 }
1357 #else // DISTRIBUTED_FEATURE_ENABLED
1358 ACCOUNT_LOGI("No distributed feature!");
1359 #endif // DISTRIBUTED_FEATURE_ENABLED
1360
1361 return ERR_OK;
1362 }
1363
1364 ErrCode AppAccountControlManager::SaveAccountInfoIntoDataStorage(
1365 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1366 {
1367 if (dataStoragePtr == nullptr) {
1368 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1369 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1370 }
1371
1372 ErrCode result = dataStoragePtr->SaveAccountInfoIntoDataStorage(appAccountInfo);
1373 if (result != ERR_OK) {
1374 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
1375 return result;
1376 }
1377
1378 // for sync data storage
1379 #ifdef DISTRIBUTED_FEATURE_ENABLED
1380 if (NeedSyncDataStorage(appAccountInfo) == true) {
1381 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1382 if (dataStorageSyncPtr == nullptr) {
1383 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1384 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1385 }
1386
1387 std::string appAccountInfoFromDataStorage;
1388 result = dataStorageSyncPtr->GetValueFromKvStore(appAccountInfo.GetPrimeKey(), appAccountInfoFromDataStorage);
1389 if (result != ERR_OK) {
1390 ACCOUNT_LOGE("failed to get config by id from data storage, result %{public}d.", result);
1391
1392 result = dataStorageSyncPtr->AddAccountInfo(appAccountInfo);
1393 if (result != ERR_OK) {
1394 ACCOUNT_LOGE("failed to add account info, result = %{public}d", result);
1395 return result;
1396 }
1397 } else {
1398 result = dataStorageSyncPtr->SaveAccountInfo(appAccountInfo);
1399 if (result != ERR_OK) {
1400 ACCOUNT_LOGE("failed to save account info, result = %{public}d", result);
1401 return result;
1402 }
1403 }
1404 }
1405 #else // DISTRIBUTED_FEATURE_ENABLED
1406 ACCOUNT_LOGI("No distributed feature!");
1407 #endif // DISTRIBUTED_FEATURE_ENABLED
1408
1409 return ERR_OK;
1410 }
1411
1412 ErrCode AppAccountControlManager::DeleteAccountInfoFromDataStorage(
1413 AppAccountInfo &appAccountInfo, std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1414 {
1415 if (dataStoragePtr == nullptr) {
1416 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1417 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1418 }
1419
1420 ErrCode result = dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);
1421 if (result != ERR_OK) {
1422 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
1423 return result;
1424 }
1425
1426 result = dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1427 if (result != ERR_OK) {
1428 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
1429 return result;
1430 }
1431
1432 // for sync data storage
1433 #ifdef DISTRIBUTED_FEATURE_ENABLED
1434 if (NeedSyncDataStorage(appAccountInfo) == true) {
1435 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1436 if (dataStorageSyncPtr == nullptr) {
1437 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1438 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1439 }
1440
1441 result = dataStorageSyncPtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1442 if (result != ERR_OK) {
1443 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
1444 }
1445 }
1446 #else // DISTRIBUTED_FEATURE_ENABLED
1447 ACCOUNT_LOGI("No distributed feature!");
1448 #endif // DISTRIBUTED_FEATURE_ENABLED
1449 return ERR_OK;
1450 }
1451
1452 ErrCode AppAccountControlManager::SaveAuthorizedAccount(const std::string &bundleName,
1453 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1454 {
1455 if (dataStoragePtr == nullptr) {
1456 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1457 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1458 }
1459
1460 ErrCode result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo, dataStoragePtr);
1461 if (result != ERR_OK) {
1462 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1463 return result;
1464 }
1465
1466 // for sync data storage
1467 #ifdef DISTRIBUTED_FEATURE_ENABLED
1468 if (NeedSyncDataStorage(appAccountInfo) == true) {
1469 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1470 if (dataStorageSyncPtr == nullptr) {
1471 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1472 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1473 }
1474
1475 result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo, dataStorageSyncPtr);
1476 if (result != ERR_OK) {
1477 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1478 return result;
1479 }
1480 }
1481 #else // DISTRIBUTED_FEATURE_ENABLED
1482 ACCOUNT_LOGI("No distributed feature!");
1483 #endif // DISTRIBUTED_FEATURE_ENABLED
1484
1485 return ERR_OK;
1486 }
1487
1488 ErrCode AppAccountControlManager::RemoveAuthorizedAccount(const std::string &bundleName,
1489 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1490 {
1491 if (dataStoragePtr == nullptr) {
1492 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1493 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1494 }
1495
1496 ErrCode result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo, dataStoragePtr);
1497 if (result != ERR_OK) {
1498 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1499 return result;
1500 }
1501
1502 // for sync data storage
1503 #ifdef DISTRIBUTED_FEATURE_ENABLED
1504 if (NeedSyncDataStorage(appAccountInfo) == true) {
1505 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1506 if (dataStorageSyncPtr == nullptr) {
1507 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1508 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1509 }
1510
1511 result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo, dataStorageSyncPtr);
1512 if (result != ERR_OK) {
1513 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1514 return result;
1515 }
1516 }
1517 #else // DISTRIBUTED_FEATURE_ENABLED
1518 ACCOUNT_LOGI("No distributed feature!");
1519 #endif // DISTRIBUTED_FEATURE_ENABLED
1520
1521 return ERR_OK;
1522 }
1523
1524 ErrCode AppAccountControlManager::SaveAuthorizedAccountIntoDataStorage(const std::string &authorizedApp,
1525 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1526 {
1527 if (dataStoragePtr == nullptr) {
1528 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1529 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1530 }
1531
1532 std::string authorizedAccounts;
1533 ErrCode result = dataStoragePtr->GetValueFromKvStore(AUTHORIZED_ACCOUNTS,
1534 authorizedAccounts);
1535 if (result != ERR_OK) {
1536 ACCOUNT_LOGE("failed to get config by id from data storage, result %{public}d.", result);
1537 }
1538
1539 std::vector<std::string> accessibleAccounts;
1540 auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(
1541 authorizedAccounts, authorizedApp, accessibleAccounts);
1542
1543 auto accountId = appAccountInfo.GetPrimeKey();
1544
1545 auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);
1546 if (it == accessibleAccounts.end()) {
1547 accessibleAccounts.emplace_back(accountId);
1548 }
1549
1550 auto accessibleAccountArray = Json::array();
1551 std::transform(accessibleAccounts.begin(), accessibleAccounts.end(), std::back_inserter(accessibleAccountArray),
1552 [](auto account) { return account; });
1553
1554 jsonObject[authorizedApp] = accessibleAccountArray;
1555 try {
1556 authorizedAccounts = jsonObject.dump();
1557 } catch (Json::type_error& err) {
1558 ACCOUNT_LOGE("failed to dump json object, reason: %{public}s", err.what());
1559 return ERR_ACCOUNT_COMMON_DUMP_JSON_ERROR;
1560 }
1561
1562 result = dataStoragePtr->PutValueToKvStore(AUTHORIZED_ACCOUNTS, authorizedAccounts);
1563 if (result != ERR_OK) {
1564 ACCOUNT_LOGE("PutValueToKvStore failed! result %{public}d.", result);
1565 }
1566 return result;
1567 }
1568
1569 ErrCode AppAccountControlManager::RemoveAuthorizedAccountFromDataStorage(const std::string &authorizedApp,
1570 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1571 {
1572 if (dataStoragePtr == nullptr) {
1573 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1574 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1575 }
1576
1577 std::string authorizedAccounts;
1578 ErrCode result = dataStoragePtr->GetValueFromKvStore(AUTHORIZED_ACCOUNTS,
1579 authorizedAccounts);
1580 if (result != ERR_OK) {
1581 ACCOUNT_LOGE("failed to get authorized accounts from data storage, result %{public}d.", result);
1582 }
1583
1584 std::vector<std::string> accessibleAccounts;
1585 auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(
1586 authorizedAccounts, authorizedApp, accessibleAccounts);
1587
1588 auto accountId = appAccountInfo.GetPrimeKey();
1589
1590 auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);
1591 if (it != accessibleAccounts.end()) {
1592 accessibleAccounts.erase(it);
1593 }
1594
1595 auto accessibleAccountArray = Json::array();
1596 std::transform(accessibleAccounts.begin(), accessibleAccounts.end(), std::back_inserter(accessibleAccountArray),
1597 [](auto account) { return account; });
1598
1599 jsonObject[authorizedApp] = accessibleAccountArray;
1600 try {
1601 authorizedAccounts = jsonObject.dump();
1602 } catch (Json::type_error& err) {
1603 ACCOUNT_LOGE("failed to dump json object, reason: %{public}s", err.what());
1604 return ERR_ACCOUNT_COMMON_DUMP_JSON_ERROR;
1605 }
1606
1607 result = dataStoragePtr->PutValueToKvStore(AUTHORIZED_ACCOUNTS, authorizedAccounts);
1608 if (result != ERR_OK) {
1609 ACCOUNT_LOGE("failed to save config info, result %{public}d.", result);
1610 return result;
1611 }
1612
1613 return ERR_OK;
1614 }
1615 } // namespace AccountSA
1616 } // namespace OHOS
1617