1 /*
2 * Copyright (c) 2021-2025 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 DatabaseTransaction dbTransaction = nullptr;
290 ErrCode result = StartDbTransaction(dataStoragePtr, dbTransaction);
291 if (result != ERR_OK) {
292 ACCOUNT_LOGE("StartDbTransaction failed, result = %{public}d", result);
293 return result;
294 }
295 result = DeleteAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr, uid);
296 if (result != ERR_OK) {
297 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
298 return result;
299 }
300 RemoveAssociatedDataCacheByAccount(uid, name);
301 #ifdef HAS_ASSET_PART
302 RemoveDataFromAssetByLabel(uid / UID_TRANSFORM_DIVISOR, SEC_ASSET_TAG_DATA_LABEL_NORMAL_2,
303 appAccountInfo.GetPrimeKey());
304 #endif
305
306 std::set<std::string> authorizedApps;
307 appAccountInfo.GetAuthorizedApps(authorizedApps);
308 for (auto authorizedApp : authorizedApps) {
309 // remove authorized account from data storage
310 result = RemoveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, uid);
311 if (result != ERR_OK) {
312 ACCOUNT_LOGE("failed to save authorized account into data storage, result %{public}d.", result);
313 return result;
314 }
315 }
316 result = CommitDbTransaction(dataStoragePtr, dbTransaction);
317 if (result != ERR_OK) {
318 ACCOUNT_LOGE("Failed to commit db transaction, result %{public}d.", result);
319 return result;
320 }
321 return ERR_OK;
322 }
323
GetAccountExtraInfo(const std::string & name,std::string & extraInfo,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)324 ErrCode AppAccountControlManager::GetAccountExtraInfo(const std::string &name, std::string &extraInfo,
325 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
326 {
327 AppAccountInfo appAccountInfo(name, bundleName);
328 appAccountInfo.SetAppIndex(appIndex);
329 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
330 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
331 if (result != ERR_OK) {
332 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
333 return result;
334 }
335
336 appAccountInfo.GetExtraInfo(extraInfo);
337
338 return ERR_OK;
339 }
340
SetAccountExtraInfo(const std::string & name,const std::string & extraInfo,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)341 ErrCode AppAccountControlManager::SetAccountExtraInfo(const std::string &name, const std::string &extraInfo,
342 const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
343 {
344 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
345 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
346 if (result != ERR_OK) {
347 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
348 return result;
349 }
350
351 appAccountInfo.SetExtraInfo(extraInfo);
352
353 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
354 if (result != ERR_OK) {
355 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
356 return result;
357 }
358
359 ACCOUNT_LOGD("end, result = %{public}d", result);
360
361 return result;
362 }
363
EnableAppAccess(const std::string & name,const std::string & authorizedApp,AppAccountCallingInfo & appAccountCallingInfo,AppAccountInfo & appAccountInfo,const uint32_t apiVersion)364 ErrCode AppAccountControlManager::EnableAppAccess(const std::string &name, const std::string &authorizedApp,
365 AppAccountCallingInfo &appAccountCallingInfo, AppAccountInfo &appAccountInfo, const uint32_t apiVersion)
366 {
367 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
368 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
369 if (result != ERR_OK) {
370 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
371 return result;
372 }
373
374 result = appAccountInfo.EnableAppAccess(authorizedApp, apiVersion);
375 if (result != ERR_OK) {
376 ACCOUNT_LOGE("Failed to enable app access, result=%{public}d.", result);
377 return result;
378 }
379 DatabaseTransaction dbTransaction = nullptr;
380 result = StartDbTransaction(dataStoragePtr, dbTransaction);
381 if (result != ERR_OK) {
382 ACCOUNT_LOGE("StartDbTransaction failed, result = %{public}d", result);
383 return result;
384 }
385 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
386 if (result != ERR_OK) {
387 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
388 return result;
389 }
390
391 // save authorized account into data storage
392 result = SaveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
393 if (result != ERR_OK) {
394 ACCOUNT_LOGE("Failed to save authorized account into data storage, result=%{public}d.", result);
395 return result;
396 }
397 result = CommitDbTransaction(dataStoragePtr, dbTransaction);
398 if (result != ERR_OK) {
399 ACCOUNT_LOGE("Failed to commit db transaction, result %{public}d.", result);
400 return result;
401 }
402 return ERR_OK;
403 }
404
DisableAppAccess(const std::string & name,const std::string & authorizedApp,AppAccountCallingInfo & appAccountCallingInfo,AppAccountInfo & appAccountInfo,const uint32_t apiVersion)405 ErrCode AppAccountControlManager::DisableAppAccess(const std::string &name, const std::string &authorizedApp,
406 AppAccountCallingInfo &appAccountCallingInfo, AppAccountInfo &appAccountInfo, const uint32_t apiVersion)
407 {
408 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
409 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
410 if (result != ERR_OK) {
411 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
412 return result;
413 }
414
415 result = appAccountInfo.DisableAppAccess(authorizedApp, apiVersion);
416 if (result != ERR_OK) {
417 ACCOUNT_LOGE("failed to disable app access, result %{public}d.", result);
418 return ERR_APPACCOUNT_SERVICE_DISABLE_APP_ACCESS_NOT_EXISTED;
419 }
420 DatabaseTransaction dbTransaction = nullptr;
421 result = StartDbTransaction(dataStoragePtr, dbTransaction);
422 if (result != ERR_OK) {
423 ACCOUNT_LOGE("StartDbTransaction failed, result = %{public}d", result);
424 return result;
425 }
426 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
427 if (result != ERR_OK) {
428 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
429 return result;
430 }
431
432 // remove authorized account from data storage
433 result = RemoveAuthorizedAccount(authorizedApp, appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
434 if (result != ERR_OK) {
435 ACCOUNT_LOGE("failed to save authorized account into data storage, result %{public}d.", result);
436 return result;
437 }
438 result = CommitDbTransaction(dataStoragePtr, dbTransaction);
439 if (result != ERR_OK) {
440 ACCOUNT_LOGE("Failed to commit db transaction, result %{public}d.", result);
441 return result;
442 }
443 return ERR_OK;
444 }
445
CheckAppAccess(const std::string & name,const std::string & authorizedApp,bool & isAccessible,const AppAccountCallingInfo & appAccountCallingInfo)446 ErrCode AppAccountControlManager::CheckAppAccess(const std::string &name, const std::string &authorizedApp,
447 bool &isAccessible, const AppAccountCallingInfo &appAccountCallingInfo)
448 {
449 isAccessible = false;
450 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid);
451 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
452 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
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 ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
457 }
458 return appAccountInfo.CheckAppAccess(authorizedApp, isAccessible);
459 }
460
CheckAppAccountSyncEnable(const std::string & name,bool & syncEnable,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)461 ErrCode AppAccountControlManager::CheckAppAccountSyncEnable(const std::string &name,
462 bool &syncEnable, const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
463 {
464 AppAccountInfo appAccountInfo(name, bundleName);
465 appAccountInfo.SetAppIndex(appIndex);
466 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
467 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
468 if (result != ERR_OK) {
469 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
470 return result;
471 }
472
473 appAccountInfo.GetSyncEnable(syncEnable);
474
475 return ERR_OK;
476 }
477
SetAppAccountSyncEnable(const std::string & name,const bool & syncEnable,const uid_t & uid,const std::string & bundleName,AppAccountInfo & appAccountInfo)478 ErrCode AppAccountControlManager::SetAppAccountSyncEnable(const std::string &name, const bool &syncEnable,
479 const uid_t &uid, const std::string &bundleName, AppAccountInfo &appAccountInfo)
480 {
481 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(uid);
482 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
483 if (result != ERR_OK) {
484 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
485 return result;
486 }
487
488 appAccountInfo.SetSyncEnable(syncEnable);
489
490 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, uid);
491 if (result != ERR_OK) {
492 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
493 return result;
494 }
495
496 return ERR_OK;
497 }
498
PopDataFromAssociatedDataCache()499 void AppAccountControlManager::PopDataFromAssociatedDataCache()
500 {
501 auto it = associatedDataCache_.begin();
502 auto toPopedIt = it++;
503 for (; it != associatedDataCache_.end(); ++it) {
504 if (toPopedIt->second.freq > it->second.freq) {
505 toPopedIt = it;
506 }
507 it->second.freq = 0;
508 }
509 associatedDataCache_.erase(toPopedIt);
510 }
511
GetAssociatedDataFromStorage(const std::string & name,const std::string & key,std::string & value,const uid_t & uid,const uint32_t & appIndex)512 ErrCode AppAccountControlManager::GetAssociatedDataFromStorage(const std::string &name, const std::string &key,
513 std::string &value, const uid_t &uid, const uint32_t &appIndex)
514 {
515 std::string bundleName;
516 if (BundleManagerAdapter::GetInstance()->GetNameForUid(uid, bundleName) != ERR_OK) {
517 ACCOUNT_LOGE("failed to get bundle name");
518 return ERR_APPACCOUNT_SERVICE_GET_BUNDLE_NAME;
519 }
520 AppAccountInfo appAccountInfo(name, bundleName);
521 appAccountInfo.SetAppIndex(appIndex);
522 std::shared_ptr<AppAccountDataStorage> storePtr = GetDataStorage(uid);
523 if (storePtr == nullptr) {
524 ACCOUNT_LOGE("failed to get data storage");
525 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
526 }
527 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, storePtr);
528 if (result != ERR_OK) {
529 ACCOUNT_LOGE("failed to get account info from data storage");
530 return result;
531 }
532 AssociatedDataCacheItem item;
533 item.name = name;
534 item.freq = 0;
535 appAccountInfo.GetAllAssociatedData(item.data);
536 auto it = item.data.find(key);
537 if (it != item.data.end()) {
538 value = it->second;
539 } else {
540 result = ERR_APPACCOUNT_SERVICE_ASSOCIATED_DATA_KEY_NOT_EXIST;
541 }
542 if (associatedDataCache_.size() >= ASSOCIATED_DATA_CACHE_MAX_SIZE) {
543 PopDataFromAssociatedDataCache();
544 }
545 associatedDataCache_.emplace(uid, item);
546 return result;
547 }
548
GetAssociatedData(const std::string & name,const std::string & key,std::string & value,const uid_t & uid)549 ErrCode AppAccountControlManager::GetAssociatedData(const std::string &name, const std::string &key,
550 std::string &value, const uid_t &uid)
551 {
552 std::lock_guard<std::mutex> lock(associatedDataMutex_);
553 auto it = associatedDataCache_.find(uid);
554 if ((it == associatedDataCache_.end()) || (it->second.name != name)) {
555 uint32_t callingTokenId = IPCSkeleton::GetCallingTokenID();
556 Security::AccessToken::HapTokenInfo hapTokenInfo;
557 int result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(callingTokenId, hapTokenInfo);
558 if ((result != 0) || (hapTokenInfo.instIndex < 0)) {
559 ACCOUNT_LOGE("failed to get app index");
560 return ERR_APPACCOUNT_SERVICE_GET_APP_INDEX;
561 }
562 associatedDataCache_.erase(uid);
563 return GetAssociatedDataFromStorage(name, key, value, uid, hapTokenInfo.instIndex);
564 }
565 it->second.freq++;
566 auto dataIt = it->second.data.find(key);
567 if (dataIt == it->second.data.end()) {
568 return ERR_APPACCOUNT_SERVICE_ASSOCIATED_DATA_KEY_NOT_EXIST;
569 }
570 value = dataIt->second;
571 return ERR_OK;
572 }
573
SetAssociatedData(const std::string & name,const std::string & key,const std::string & value,const AppAccountCallingInfo & appAccountCallingInfo)574 ErrCode AppAccountControlManager::SetAssociatedData(const std::string &name, const std::string &key,
575 const std::string &value, const AppAccountCallingInfo &appAccountCallingInfo)
576 {
577 std::shared_ptr<AppAccountDataStorage> storePtr = GetDataStorage(appAccountCallingInfo.callingUid);
578 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
579 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
580 std::lock_guard<std::mutex> lock(associatedDataMutex_);
581 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, storePtr);
582 if (result != ERR_OK) {
583 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
584 return result;
585 }
586 result = appAccountInfo.SetAssociatedData(key, value);
587 if (result != ERR_OK) {
588 ACCOUNT_LOGE("failed to set associated data, result %{public}d.", result);
589 return result;
590 }
591 result = SaveAccountInfoIntoDataStorage(appAccountInfo, storePtr, appAccountCallingInfo.callingUid);
592 if (result != ERR_OK) {
593 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
594 return result;
595 }
596 auto it = associatedDataCache_.find(appAccountCallingInfo.callingUid);
597 if ((it != associatedDataCache_.end()) && (it->second.name == name)) {
598 it->second.data[key] = value;
599 }
600 return ERR_OK;
601 }
602
GetAccountCredential(const std::string & name,const std::string & credentialType,std::string & credential,const AppAccountCallingInfo & appAccountCallingInfo)603 ErrCode AppAccountControlManager::GetAccountCredential(const std::string &name, const std::string &credentialType,
604 std::string &credential, const AppAccountCallingInfo &appAccountCallingInfo)
605 {
606 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
607 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
608 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid, false);
609 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
610 if (result != ERR_OK) {
611 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
612 return result;
613 }
614
615 result = appAccountInfo.GetAccountCredential(credentialType, credential);
616 if (result != ERR_OK) {
617 return result;
618 }
619 #ifdef HAS_ASSET_PART
620 std::string alias = credential;
621 credential = "";
622 GetDataFromAsset(appAccountCallingInfo.callingUid / UID_TRANSFORM_DIVISOR, alias, credential);
623 #endif
624 return result;
625 }
626
SetAccountCredential(const std::string & name,const std::string & credentialType,const std::string & credential,const AppAccountCallingInfo & appAccountCallingInfo)627 ErrCode AppAccountControlManager::SetAccountCredential(const std::string &name, const std::string &credentialType,
628 const std::string &credential, const AppAccountCallingInfo &appAccountCallingInfo)
629 {
630 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(appAccountCallingInfo.callingUid, false);
631 AppAccountInfo appAccountInfo(name, appAccountCallingInfo.bundleName);
632 appAccountInfo.SetAppIndex(appAccountCallingInfo.appIndex);
633 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
634 if (result != ERR_OK) {
635 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
636 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
637 }
638 result = appAccountInfo.SetAccountCredential(credentialType, credential);
639 if (result != ERR_OK) {
640 ACCOUNT_LOGE("failed to set account credential, result %{public}d.", result);
641 return result;
642 }
643
644 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, appAccountCallingInfo.callingUid);
645 if (result != ERR_OK) {
646 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
647 return result;
648 }
649 #ifdef HAS_ASSET_PART
650 std::string hapLabel = appAccountCallingInfo.bundleName + Constants::HYPHEN +
651 std::to_string(appAccountCallingInfo.appIndex);
652 std::string credentialAlias;
653 appAccountInfo.GetAccountCredential(credentialType, credentialAlias);
654 int32_t localId = appAccountCallingInfo.callingUid / UID_TRANSFORM_DIVISOR;
655 result = SaveDataToAsset(localId, hapLabel, appAccountInfo.GetAlias(), credentialAlias, credential);
656 #endif
657 return result;
658 }
659
DeleteAccountCredential(const std::string & name,const std::string & credentialType,const AppAccountCallingInfo & callingInfo)660 ErrCode AppAccountControlManager::DeleteAccountCredential(const std::string &name, const std::string &credentialType,
661 const AppAccountCallingInfo &callingInfo)
662 {
663 AppAccountInfo appAccountInfo(name, callingInfo.bundleName);
664 appAccountInfo.SetAppIndex(callingInfo.appIndex);
665 auto dataStoragePtr = GetDataStorage(callingInfo.callingUid, 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 #ifdef HAS_ASSET_PART
672 std::string alias;
673 appAccountInfo.GetAccountCredential(credentialType, alias);
674 RemoveDataFromAsset(callingInfo.callingUid / UID_TRANSFORM_DIVISOR, alias);
675 #endif
676 result = appAccountInfo.DeleteAccountCredential(credentialType);
677 if (result != ERR_OK) {
678 ACCOUNT_LOGE("failed to delete account credential, result %{public}d.", result);
679 return result;
680 }
681
682 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, callingInfo.callingUid);
683 if (result != ERR_OK) {
684 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
685 }
686 return result;
687 }
688
GetOAuthToken(const AuthenticatorSessionRequest & request,std::string & token,const uint32_t apiVersion)689 ErrCode AppAccountControlManager::GetOAuthToken(
690 const AuthenticatorSessionRequest &request, std::string &token, const uint32_t apiVersion)
691 {
692 AppAccountInfo appAccountInfo(request.name, request.owner);
693 appAccountInfo.SetAppIndex(0);
694 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid, false);
695 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
696 if (result != ERR_OK) {
697 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
698 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
699 }
700 bool isVisible = false;
701 result = appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.callerBundleName +
702 GetBundleKeySuffix(request.appIndex), isVisible, apiVersion);
703 if ((result != ERR_OK) || (!isVisible)) {
704 ACCOUNT_LOGE("failed to get oauth token for permission denied, result %{public}d.", result);
705 return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
706 }
707 result = appAccountInfo.GetOAuthToken(request.authType, token, apiVersion);
708 if (result != ERR_OK) {
709 return result;
710 }
711 #ifdef HAS_ASSET_PART
712 std::string alias = token;
713 token = "";
714 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, token);
715 if (token.empty() && (apiVersion < Constants::API_VERSION9)) {
716 return ERR_APPACCOUNT_SERVICE_OAUTH_TOKEN_NOT_EXIST;
717 }
718 #endif
719 return ERR_OK;
720 }
721
SetOAuthToken(const AuthenticatorSessionRequest & request)722 ErrCode AppAccountControlManager::SetOAuthToken(const AuthenticatorSessionRequest &request)
723 {
724 std::lock_guard<std::mutex> lock(mutex_);
725 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
726 appAccountInfo.SetAppIndex(request.appIndex);
727 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid, false);
728 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
729 if (result != ERR_OK) {
730 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
731 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
732 }
733 result = appAccountInfo.SetOAuthToken(request.authType, request.token);
734 if (result != ERR_OK) {
735 ACCOUNT_LOGE("failed to set oauth token, result %{public}d.", result);
736 return result;
737 }
738 result = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
739 if (result != ERR_OK) {
740 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
741 return result;
742 }
743 #ifdef HAS_ASSET_PART
744 std::string hapLabel = request.callerBundleName + Constants::HYPHEN + std::to_string(request.appIndex);
745 std::string authTypeAlias;
746 appAccountInfo.GetOAuthToken(request.authType, authTypeAlias);
747 int32_t localId = request.callerUid / UID_TRANSFORM_DIVISOR;
748 result = SaveDataToAsset(localId, hapLabel, appAccountInfo.GetAlias(), authTypeAlias, request.token);
749 #endif
750 return result;
751 }
752
DeleteOAuthToken(const AuthenticatorSessionRequest & request,const uint32_t apiVersion)753 ErrCode AppAccountControlManager::DeleteOAuthToken(
754 const AuthenticatorSessionRequest &request, const uint32_t apiVersion)
755 {
756 std::lock_guard<std::mutex> lock(mutex_);
757 AppAccountInfo appAccountInfo(request.name, request.owner);
758 appAccountInfo.SetAppIndex(0);
759 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
760 ErrCode ret = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
761 if (ret != ERR_OK) {
762 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", ret);
763 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
764 }
765 bool isVisible = false;
766 ret = appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.callerBundleName +
767 GetBundleKeySuffix(request.appIndex), isVisible, apiVersion);
768 if ((!isVisible) || (ret != ERR_OK)) {
769 ACCOUNT_LOGE("failed to delete oauth token for permission denied, result %{public}d.", ret);
770 return ERR_ACCOUNT_COMMON_PERMISSION_DENIED;
771 }
772 std::string token = request.token;
773 #ifdef HAS_ASSET_PART
774 std::string alias;
775 ret = appAccountInfo.GetOAuthToken(request.authType, alias, apiVersion);
776 if (ret != ERR_OK) {
777 return apiVersion >= Constants::API_VERSION9 ? ret : ERR_OK;
778 }
779 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, token);
780 if (token != request.token) {
781 return ERR_OK;
782 }
783 RemoveDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias);
784 token = alias;
785 #endif
786 if (apiVersion >= Constants::API_VERSION9) {
787 bool isOwnerSelf = request.owner == request.callerBundleName;
788 ret = appAccountInfo.DeleteAuthToken(request.authType, token, isOwnerSelf);
789 if (ret != ERR_OK) {
790 return ret;
791 }
792 } else {
793 ret = appAccountInfo.DeleteOAuthToken(request.authType, token);
794 if (ret == ERR_APPACCOUNT_SERVICE_OAUTH_TOKEN_NOT_EXIST) {
795 return ERR_OK;
796 }
797 }
798 ret = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
799 if (ret != ERR_OK) {
800 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", ret);
801 return ret;
802 }
803 return ret;
804 }
805
SetOAuthTokenVisibility(const AuthenticatorSessionRequest & request,const uint32_t apiVersion)806 ErrCode AppAccountControlManager::SetOAuthTokenVisibility(
807 const AuthenticatorSessionRequest &request, const uint32_t apiVersion)
808 {
809 std::lock_guard<std::mutex> lock(mutex_);
810 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
811 appAccountInfo.SetAppIndex(request.appIndex);
812 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
813 ErrCode ret = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
814 if (ret != ERR_OK) {
815 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", ret);
816 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
817 }
818 ret = appAccountInfo.SetOAuthTokenVisibility(
819 request.authType, request.bundleName, request.isTokenVisible, apiVersion);
820 if (ret != ERR_OK) {
821 ACCOUNT_LOGE("failed to set oauth token visibility, result %{public}d.", ret);
822 return ret;
823 }
824 ret = SaveAccountInfoIntoDataStorage(appAccountInfo, dataStoragePtr, request.callerUid);
825 if (ret != ERR_OK) {
826 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", ret);
827 return ret;
828 }
829 return ERR_OK;
830 }
831
CheckOAuthTokenVisibility(const AuthenticatorSessionRequest & request,bool & isVisible,const uint32_t apiVersion)832 ErrCode AppAccountControlManager::CheckOAuthTokenVisibility(
833 const AuthenticatorSessionRequest &request, bool &isVisible, const uint32_t apiVersion)
834 {
835 isVisible = false;
836 AppAccountInfo appAccountInfo(request.name, request.owner);
837 appAccountInfo.SetAppIndex(request.appIndex);
838 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
839 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
840 if (result != ERR_OK) {
841 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
842 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
843 }
844 return appAccountInfo.CheckOAuthTokenVisibility(request.authType, request.bundleName, isVisible, apiVersion);
845 }
846
GetAllOAuthTokens(const AuthenticatorSessionRequest & request,std::vector<OAuthTokenInfo> & tokenInfos)847 ErrCode AppAccountControlManager::GetAllOAuthTokens(
848 const AuthenticatorSessionRequest &request, std::vector<OAuthTokenInfo> &tokenInfos)
849 {
850 tokenInfos.clear();
851 AppAccountInfo appAccountInfo(request.name, request.owner);
852 appAccountInfo.SetAppIndex(0);
853 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
854 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
855 if (result != ERR_OK) {
856 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
857 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
858 }
859 std::string bundleKey = request.callerBundleName + GetBundleKeySuffix(request.appIndex);
860 std::vector<OAuthTokenInfo> allTokenInfos;
861 result = appAccountInfo.GetAllOAuthTokens(allTokenInfos);
862 if (result != ERR_OK) {
863 ACCOUNT_LOGE("failed to get all oauth token from data storage, result %{public}d.", result);
864 return result;
865 }
866 for (auto tokenInfo : allTokenInfos) {
867 if ((bundleKey != request.owner) &&
868 (tokenInfo.authList.find(bundleKey) == tokenInfo.authList.end())) {
869 continue;
870 }
871 #ifdef HAS_ASSET_PART
872 std::string alias = tokenInfo.token;
873 tokenInfo.token = "";
874 GetDataFromAsset(request.callerUid / UID_TRANSFORM_DIVISOR, alias, tokenInfo.token);
875 #endif
876 if (tokenInfo.token.empty() && tokenInfo.authList.empty()) { // for api 8 logic
877 continue;
878 }
879 tokenInfo.authList.clear();
880 tokenInfos.push_back(tokenInfo);
881 }
882 return ERR_OK;
883 }
884
GetOAuthList(const AuthenticatorSessionRequest & request,std::set<std::string> & oauthList,const uint32_t apiVersion)885 ErrCode AppAccountControlManager::GetOAuthList(
886 const AuthenticatorSessionRequest &request, std::set<std::string> &oauthList, const uint32_t apiVersion)
887 {
888 AppAccountInfo appAccountInfo(request.name, request.callerBundleName);
889 appAccountInfo.SetAppIndex(request.appIndex);
890 std::shared_ptr<AppAccountDataStorage> dataStoragePtr = GetDataStorage(request.callerUid);
891 ErrCode result = GetAccountInfoFromDataStorage(appAccountInfo, dataStoragePtr);
892 if (result != ERR_OK) {
893 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
894 return ERR_APPACCOUNT_SERVICE_ACCOUNT_NOT_EXIST;
895 }
896 return appAccountInfo.GetOAuthList(request.authType, oauthList, apiVersion);
897 }
898
GetBundleKeySuffix(const uint32_t & appIndex)899 std::string AppAccountControlManager::GetBundleKeySuffix(const uint32_t &appIndex)
900 {
901 return (appIndex == 0 ? "" : HYPHEN + std::to_string(appIndex));
902 }
903
GetAllAccounts(const std::string & owner,std::vector<AppAccountInfo> & appAccounts,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)904 ErrCode AppAccountControlManager::GetAllAccounts(const std::string &owner, std::vector<AppAccountInfo> &appAccounts,
905 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
906 {
907 appAccounts.clear();
908
909 auto dataStoragePtr = GetDataStorage(uid);
910 if (dataStoragePtr == nullptr) {
911 ACCOUNT_LOGE("dataStoragePtr is nullptr");
912 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
913 }
914 ErrCode result = AccountPermissionManager::VerifyPermission(GET_ALL_APP_ACCOUNTS);
915 std::string bundleKey = bundleName + GetBundleKeySuffix(appIndex);
916 if ((bundleKey == owner) || (result == ERR_OK)) {
917 std::string key = owner + Constants::HYPHEN + std::to_string(0);
918 result = GetAllAccountsFromDataStorage(key, appAccounts, owner, dataStoragePtr);
919 if (result != ERR_OK) {
920 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
921 return result;
922 }
923 return ERR_OK;
924 }
925
926 std::vector<std::string> accessibleAccounts;
927 result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleKey, accessibleAccounts);
928 if (result != ERR_OK) {
929 ACCOUNT_LOGE("failed to get accessible account from data storage, result %{public}d.", result);
930 return result;
931 }
932 for (auto account : accessibleAccounts) {
933 AppAccountInfo appAccountInfo;
934 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
935 if (result != ERR_OK) {
936 ACCOUNT_LOGE("failed to get account info by id, result %{public}d.", result);
937 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
938 }
939 if (appAccountInfo.GetOwner() == owner && AppAccountSubscribeManager::CheckAppIsMaster(account)) {
940 appAccounts.emplace_back(appAccountInfo);
941 }
942 }
943 return ERR_OK;
944 }
945
LoadAllAppAccounts(const std::shared_ptr<OHOS::AccountSA::AppAccountDataStorage> & dataStoragePtr,std::vector<AppAccountInfo> & appAccounts)946 static ErrCode LoadAllAppAccounts(const std::shared_ptr<OHOS::AccountSA::AppAccountDataStorage> &dataStoragePtr,
947 std::vector<AppAccountInfo> &appAccounts)
948 {
949 std::map<std::string, std::shared_ptr<IAccountInfo>> infos;
950 ErrCode result = dataStoragePtr->LoadAllData(infos);
951 if (result != ERR_OK) {
952 ACCOUNT_LOGE("LoadAllData failed!");
953 return result;
954 }
955 for (auto it = infos.begin(); it != infos.end(); ++it) {
956 if (it->first == AUTHORIZED_ACCOUNTS) {
957 continue;
958 }
959 AppAccountInfo curAppInfo = *(std::static_pointer_cast<AppAccountInfo>(it->second));
960 appAccounts.emplace_back(curAppInfo);
961 }
962 return ERR_OK;
963 }
964
GetAllAccessibleAccounts(std::vector<AppAccountInfo> & appAccounts,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)965 ErrCode AppAccountControlManager::GetAllAccessibleAccounts(std::vector<AppAccountInfo> &appAccounts,
966 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
967 {
968 appAccounts.clear();
969
970 auto dataStoragePtr = GetDataStorage(uid);
971 if (dataStoragePtr == nullptr) {
972 ACCOUNT_LOGE("dataStoragePtr is nullptr");
973 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
974 }
975 ErrCode result = AccountPermissionManager::VerifyPermission(GET_ALL_APP_ACCOUNTS);
976 if (result == ERR_OK) {
977 return LoadAllAppAccounts(dataStoragePtr, appAccounts);
978 }
979 std::vector<std::string> accessibleAccounts;
980 result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleName, accessibleAccounts);
981 if (result != ERR_OK) {
982 ACCOUNT_LOGE("failed to get accessible account from data storage, result %{public}d.", result);
983 return result;
984 }
985
986 for (auto account : accessibleAccounts) {
987 AppAccountInfo appAccountInfo;
988
989 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
990 if (result != ERR_OK) {
991 ACCOUNT_LOGE("failed to get account info by id, result %{public}d.", result);
992 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
993 }
994
995 appAccounts.emplace_back(appAccountInfo);
996 }
997
998 std::vector<AppAccountInfo> currentAppAccounts;
999 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
1000 result = GetAllAccountsFromDataStorage(key, currentAppAccounts, bundleName, dataStoragePtr);
1001 if (result != ERR_OK) {
1002 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
1003 return result;
1004 }
1005
1006 std::transform(currentAppAccounts.begin(), currentAppAccounts.end(), std::back_inserter(appAccounts),
1007 [](auto account) { return account; });
1008
1009 return ERR_OK;
1010 }
1011
SelectAccountsByOptions(const SelectAccountsOptions & options,const sptr<IAppAccountAuthenticatorCallback> & callback,const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)1012 ErrCode AppAccountControlManager::SelectAccountsByOptions(
1013 const SelectAccountsOptions &options, const sptr<IAppAccountAuthenticatorCallback> &callback,
1014 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
1015 {
1016 AAFwk::Want result;
1017 if ((!options.hasAccounts) && (!options.hasOwners) && (!options.hasLabels)) {
1018 callback->OnResult(ERR_JS_SUCCESS, result);
1019 return ERR_OK;
1020 }
1021 std::set<std::string> allowedAccounts;
1022 for (auto account : options.allowedAccounts) {
1023 allowedAccounts.emplace(account.first + "_" + account.second);
1024 }
1025 std::set<std::string> allowedOwners(options.allowedOwners.begin(), options.allowedOwners.end());
1026 std::vector<AppAccountInfo> accessibleAccounts;
1027 ErrCode errCode = GetAllAccessibleAccounts(accessibleAccounts, uid, bundleName, appIndex);
1028 if (errCode != ERR_OK) {
1029 ACCOUNT_LOGE("failed to get all accessible accounts");
1030 return errCode;
1031 }
1032 std::vector<AppAccountInfo> candidateAccounts;
1033 for (auto account : accessibleAccounts) {
1034 std::string owner = account.GetOwner();
1035 if (options.hasOwners && allowedOwners.count(owner) == 0) {
1036 continue;
1037 }
1038 if (options.hasAccounts && allowedAccounts.count(owner + "_" + account.GetName()) == 0) {
1039 continue;
1040 }
1041 candidateAccounts.push_back(account);
1042 }
1043 if (options.requiredLabels.size() == 0) {
1044 std::vector<std::string> names;
1045 std::vector<std::string> owners;
1046 for (auto account : candidateAccounts) {
1047 names.push_back(account.GetName());
1048 owners.push_back(account.GetOwner());
1049 }
1050 result.SetParam(Constants::KEY_ACCOUNT_NAMES, names);
1051 result.SetParam(Constants::KEY_ACCOUNT_OWNERS, owners);
1052 callback->OnResult(ERR_JS_SUCCESS, result);
1053 return ERR_OK;
1054 }
1055 AuthenticatorSessionRequest request;
1056 request.callback = callback;
1057 request.callerUid = uid;
1058 request.labels = options.requiredLabels;
1059 return AppAccountAuthenticatorSessionManager::GetInstance().SelectAccountsByOptions(candidateAccounts, request);
1060 }
1061
RemoveAssociatedDataCacheByUid(const uid_t & uid)1062 void AppAccountControlManager::RemoveAssociatedDataCacheByUid(const uid_t &uid)
1063 {
1064 std::lock_guard<std::mutex> lock(associatedDataMutex_);
1065 associatedDataCache_.erase(uid);
1066 }
1067
RemoveAssociatedDataCacheByAccount(const uid_t & uid,const std::string & name)1068 void AppAccountControlManager::RemoveAssociatedDataCacheByAccount(const uid_t &uid, const std::string &name)
1069 {
1070 std::lock_guard<std::mutex> lock(associatedDataMutex_);
1071 auto it = associatedDataCache_.find(uid);
1072 if ((it == associatedDataCache_.end()) || (it->second.name != name)) {
1073 return;
1074 }
1075 associatedDataCache_.erase(it);
1076 }
1077
SetOsAccountRemoved(int32_t localId,bool isRemoved)1078 void AppAccountControlManager::SetOsAccountRemoved(int32_t localId, bool isRemoved)
1079 {
1080 if (isRemoved) {
1081 removedOsAccounts_.EnsureInsert(localId, true);
1082 } else {
1083 removedOsAccounts_.Erase(localId);
1084 }
1085 }
1086
IsOsAccountRemoved(int32_t localId)1087 bool AppAccountControlManager::IsOsAccountRemoved(int32_t localId)
1088 {
1089 bool isRemoved = false;
1090 return removedOsAccounts_.Find(localId, isRemoved);
1091 }
1092
OnPackageRemoved(const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)1093 ErrCode AppAccountControlManager::OnPackageRemoved(
1094 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
1095 {
1096 RemoveAssociatedDataCacheByUid(uid);
1097 int32_t localId = uid / UID_TRANSFORM_DIVISOR;
1098 if (IsOsAccountRemoved(localId)) {
1099 return ERR_OK;
1100 }
1101 ErrCode errCode = RemoveAppAccountData(uid, bundleName, appIndex);
1102 CloseDataStorage();
1103 return errCode;
1104 }
1105
RemoveAppAccountDataFromDataStorage(const std::shared_ptr<AppAccountDataStorage> & dataStoragePtr,const std::string & key,const uint32_t & appIndex,const std::shared_ptr<AppAccountDataStorage> & dataStorageSyncPtr=nullptr)1106 ErrCode AppAccountControlManager::RemoveAppAccountDataFromDataStorage(
1107 const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const std::string &key,
1108 const uint32_t &appIndex, const std::shared_ptr<AppAccountDataStorage> &dataStorageSyncPtr = nullptr)
1109 {
1110 DatabaseTransaction dbTransaction = nullptr;
1111 ErrCode result = StartDbTransaction(dataStoragePtr, dbTransaction);
1112 if (result != ERR_OK) {
1113 ACCOUNT_LOGE("StartDbTransaction failed, result = %{public}d", result);
1114 return result;
1115 }
1116 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1117 result = dataStoragePtr->LoadDataByLocalFuzzyQuery(key, accounts);
1118 if (result != ERR_OK) {
1119 ACCOUNT_LOGE("Failed to get accounts by owner, result = %{public}d, key = %{public}s", result, key.c_str());
1120 return result;
1121 }
1122
1123 AppAccountInfo appAccountInfo;
1124 for (auto account : accounts) {
1125 appAccountInfo = *(std::static_pointer_cast<AppAccountInfo>(account.second));
1126 std::set<std::string> authorizedApps;
1127 appAccountInfo.GetAuthorizedApps(authorizedApps);
1128 appAccountInfo.SetAppIndex(appIndex);
1129 for (auto authorizedApp : authorizedApps) {
1130 RemoveAuthorizedAccountFromDataStorage(authorizedApp, appAccountInfo, dataStoragePtr);
1131 #ifdef DISTRIBUTED_FEATURE_ENABLED
1132 if (NeedSyncDataStorage(appAccountInfo) == true) {
1133 RemoveAuthorizedAccountFromDataStorage(authorizedApp, appAccountInfo, dataStorageSyncPtr);
1134 }
1135 #endif // DISTRIBUTED_FEATURE_ENABLED
1136 }
1137 dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1138 #ifdef DISTRIBUTED_FEATURE_ENABLED
1139 if (NeedSyncDataStorage(appAccountInfo) == true) {
1140 dataStorageSyncPtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1141 }
1142 #else // DISTRIBUTED_FEATURE_ENABLED
1143 ACCOUNT_LOGI("No distributed feature!");
1144 #endif // DISTRIBUTED_FEATURE_ENABLED
1145 }
1146 result = CommitDbTransaction(dataStoragePtr, dbTransaction);
1147 if (result != ERR_OK) {
1148 ACCOUNT_LOGE("Failed to commit db transaction, result %{public}d.", result);
1149 return result;
1150 }
1151 return ERR_OK;
1152 }
1153
RemoveAppAccountData(const uid_t & uid,const std::string & bundleName,const uint32_t & appIndex)1154 ErrCode AppAccountControlManager::RemoveAppAccountData(
1155 const uid_t &uid, const std::string &bundleName, const uint32_t &appIndex)
1156 {
1157 auto dataStoragePtr = GetDataStorage(uid);
1158 if (dataStoragePtr == nullptr) {
1159 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1160 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1161 }
1162 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
1163 #ifdef DISTRIBUTED_FEATURE_ENABLED
1164 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1165 if (dataStorageSyncPtr == nullptr) {
1166 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1167 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1168 }
1169 ErrCode result = RemoveAppAccountDataFromDataStorage(dataStoragePtr, key, appIndex, dataStorageSyncPtr);
1170 #else
1171 ErrCode result = RemoveAppAccountDataFromDataStorage(dataStoragePtr, key, appIndex);
1172 #endif // DISTRIBUTED_FEATURE_ENABLED
1173 if (result != ERR_OK) {
1174 ACCOUNT_LOGE("Failed to remove accounts from database, result = %{public}d, bundleName = %{public}s",
1175 result, bundleName.c_str());
1176 return result;
1177 }
1178 #ifdef HAS_ASSET_PART
1179 RemoveDataFromAssetByLabel(uid / UID_TRANSFORM_DIVISOR, SEC_ASSET_TAG_DATA_LABEL_NORMAL_1, key);
1180 #endif
1181 return ERR_OK;
1182 }
1183
OnUserStopping(int32_t userId)1184 ErrCode AppAccountControlManager::OnUserStopping(int32_t userId)
1185 {
1186 std::string storeId = std::to_string(userId);
1187 std::string syncStoreId = storeId + DATA_STORAGE_SUFFIX;
1188 std::lock_guard<std::mutex> lock(storePtrMutex_);
1189 storePtrMap_.erase(storeId);
1190 storePtrMap_.erase(syncStoreId);
1191 return ERR_OK;
1192 }
1193
OnUserRemoved(int32_t userId)1194 ErrCode AppAccountControlManager::OnUserRemoved(int32_t userId)
1195 {
1196 return OnUserStopping(userId);
1197 }
1198
GetAllAccountsFromDataStorage(const std::string & owner,std::vector<AppAccountInfo> & appAccounts,const std::string & bundleName,const std::shared_ptr<AppAccountDataStorage> & dataStoragePtr)1199 ErrCode AppAccountControlManager::GetAllAccountsFromDataStorage(const std::string &owner,
1200 std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName,
1201 const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1202 {
1203 appAccounts.clear();
1204
1205 if (dataStoragePtr == nullptr) {
1206 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1207 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1208 }
1209
1210 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1211 ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(owner, accounts);
1212 if (result != ERR_OK) {
1213 ACCOUNT_LOGE("failed to get accounts by owner, result = %{public}d, owner = %{public}s",
1214 result, owner.c_str());
1215 return result;
1216 }
1217
1218 std::transform(accounts.begin(), accounts.end(), std::back_inserter(appAccounts),
1219 [](auto account) { return *(std::static_pointer_cast<AppAccountInfo>(account.second)); });
1220
1221 return ERR_OK;
1222 }
1223
GetAllAccessibleAccountsFromDataStorage(std::vector<AppAccountInfo> & appAccounts,const std::string & bundleName,const std::shared_ptr<AppAccountDataStorage> & dataStoragePtr,const uint32_t & appIndex)1224 ErrCode AppAccountControlManager::GetAllAccessibleAccountsFromDataStorage(
1225 std::vector<AppAccountInfo> &appAccounts, const std::string &bundleName,
1226 const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uint32_t &appIndex)
1227 {
1228 appAccounts.clear();
1229
1230 if (dataStoragePtr == nullptr) {
1231 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1232 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1233 }
1234
1235 std::vector<std::string> accessibleAccounts;
1236 ErrCode result = dataStoragePtr->GetAccessibleAccountsFromDataStorage(bundleName, accessibleAccounts);
1237 if (result != ERR_OK) {
1238 ACCOUNT_LOGE("failed to get accessible account from data storage, result = %{public}d.", result);
1239 return result;
1240 }
1241
1242 for (auto account : accessibleAccounts) {
1243 if (!AppAccountSubscribeManager::CheckAppIsMaster(account)) {
1244 continue;
1245 }
1246 AppAccountInfo appAccountInfo;
1247
1248 result = dataStoragePtr->GetAccountInfoById(account, appAccountInfo);
1249 if (result != ERR_OK) {
1250 ACCOUNT_LOGE("failed to get account info by id. result %{public}d.", result);
1251 return ERR_APPACCOUNT_SERVICE_GET_ACCOUNT_INFO_BY_ID;
1252 }
1253
1254 appAccounts.emplace_back(appAccountInfo);
1255 }
1256
1257 std::vector<AppAccountInfo> currentAppAccounts;
1258 std::string key = bundleName + Constants::HYPHEN + std::to_string(appIndex);
1259 result = GetAllAccountsFromDataStorage(key, currentAppAccounts, bundleName, dataStoragePtr);
1260 if (result != ERR_OK) {
1261 ACCOUNT_LOGE("failed to get all accounts from data storage, result = %{public}d", result);
1262 return result;
1263 }
1264
1265 std::transform(currentAppAccounts.begin(), currentAppAccounts.end(), std::back_inserter(appAccounts),
1266 [](auto account) { return account; });
1267
1268 return ERR_OK;
1269 }
1270
1271 #ifndef SQLITE_DLCLOSE_ENABLE
GetDataStorageByUserId(int32_t userId,const bool & autoSync,DistributedKv::SecurityLevel securityLevel)1272 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorageByUserId(
1273 int32_t userId, const bool &autoSync, DistributedKv::SecurityLevel securityLevel)
1274 {
1275 std::string storeId = std::to_string(userId);
1276 if (autoSync == true) {
1277 storeId = storeId + DATA_STORAGE_SUFFIX;
1278 }
1279 std::lock_guard<std::mutex> lock(storePtrMutex_);
1280 auto it = storePtrMap_.find(storeId);
1281 if ((it != storePtrMap_.end()) && (it->second != nullptr)) {
1282 return it->second;
1283 }
1284 AccountDataStorageOptions options;
1285 options.area = DistributedKv::EL2;
1286 #else
1287 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorageByUserId(
1288 int32_t userId, const bool &autoSync, DbAdapterSecurityLevel securityLevel)
1289 {
1290 std::string storeId = std::to_string(userId);
1291 if (autoSync == true) {
1292 storeId = storeId + DATA_STORAGE_SUFFIX;
1293 }
1294 std::lock_guard<std::mutex> lock(storePtrMutex_);
1295 auto it = storePtrMap_.find(storeId);
1296 if ((it != storePtrMap_.end()) && (it->second != nullptr)) {
1297 return it->second;
1298 }
1299 DbAdapterOptions options;
1300 options.area = DbAdapterArea::EL2;
1301 #endif // SQLITE_DLCLOSE_ENABLE
1302 options.autoSync = autoSync;
1303 options.securityLevel = securityLevel;
1304 options.baseDir = EL2_DATA_STORAGE_PATH_PREFIX + std::to_string(userId) + EL2_DATA_STORAGE_PATH_SUFFIX;
1305 auto storePtr = std::make_shared<AppAccountDataStorage>(EL2_DATA_STORE_PREFIX + storeId, options);
1306 storePtrMap_[storeId] = storePtr;
1307 return storePtr;
1308 }
1309
1310 #ifndef SQLITE_DLCLOSE_ENABLE
1311 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorage(
1312 const uid_t &uid, const bool &autoSync, DistributedKv::SecurityLevel securityLevel)
1313 #else
1314 std::shared_ptr<AppAccountDataStorage> AppAccountControlManager::GetDataStorage(
1315 const uid_t &uid, const bool &autoSync, DbAdapterSecurityLevel securityLevel)
1316 #endif // SQLITE_DLCLOSE_ENABLE
1317 {
1318 return GetDataStorageByUserId(uid / UID_TRANSFORM_DIVISOR, autoSync, securityLevel);
1319 }
1320
1321 void AppAccountControlManager::CloseDataStorage()
1322 {
1323 if (!storePtrMutex_.try_lock()) {
1324 return;
1325 }
1326 for (auto &item : storePtrMap_) {
1327 if (item.second == nullptr || item.second.use_count() > 1) {
1328 continue;
1329 }
1330 ErrCode result = item.second->Close();
1331 if (result == ERR_OK) {
1332 item.second = nullptr;
1333 }
1334 ACCOUNT_LOGI("Close storage, storeId: %{public}s, result: %{public}d", item.first.c_str(), result);
1335 }
1336 #ifdef SQLITE_DLCLOSE_ENABLE
1337 for (auto &item : storePtrMap_) {
1338 if (item.second != nullptr) {
1339 storePtrMutex_.unlock();
1340 return;
1341 }
1342 }
1343 bool dlCloseRet = DatabaseAdapterLoader::GetInstance().CheckAndUnload();
1344 ACCOUNT_LOGI("Close so end, ret: %{public}d", dlCloseRet);
1345 #endif // SQLITE_DLCLOSE_ENABLE
1346 storePtrMutex_.unlock();
1347 }
1348
1349 bool AppAccountControlManager::NeedSyncDataStorage(const AppAccountInfo &appAccountInfo)
1350 {
1351 bool syncEnable = false;
1352 appAccountInfo.GetSyncEnable(syncEnable);
1353
1354 if (syncEnable == false) {
1355 return false;
1356 }
1357 return true;
1358 }
1359
1360 ErrCode AppAccountControlManager::GetAccountInfoFromDataStorage(
1361 AppAccountInfo &appAccountInfo, std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1362 {
1363 if (dataStoragePtr == nullptr) {
1364 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1365 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1366 }
1367
1368 return dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);
1369 }
1370
1371 ErrCode AppAccountControlManager::AddAccountInfoIntoDataStorage(
1372 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1373 {
1374 if (dataStoragePtr == nullptr) {
1375 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1376 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1377 }
1378
1379 std::string owner;
1380 appAccountInfo.GetOwner(owner);
1381
1382 std::map<std::string, std::shared_ptr<IAccountInfo>> accounts;
1383 std::string key = owner + Constants::HYPHEN + std::to_string(appAccountInfo.GetAppIndex());
1384 ErrCode result = dataStoragePtr->LoadDataByLocalFuzzyQuery(key, accounts);
1385 if (result != ERR_OK) {
1386 ACCOUNT_LOGE("failed to get accounts by owner, result %{public}d, owner = %{public}s",
1387 result, owner.c_str());
1388 return result;
1389 }
1390
1391 if (accounts.size() >= ACCOUNT_MAX_SIZE) {
1392 ACCOUNT_LOGE("account exceeds max size");
1393 return ERR_APPACCOUNT_SERVICE_ACCOUNT_MAX_SIZE;
1394 }
1395
1396 result = dataStoragePtr->AddAccountInfoIntoDataStorage(appAccountInfo);
1397 if (result != ERR_OK) {
1398 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
1399 return result;
1400 }
1401
1402 // for sync data storage
1403 #ifdef DISTRIBUTED_FEATURE_ENABLED
1404 if (NeedSyncDataStorage(appAccountInfo) == true) {
1405 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1406 if (dataStorageSyncPtr == nullptr) {
1407 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1408 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1409 }
1410 // Here do not open transaction, as it should be opened before this func is called
1411 result = dataStorageSyncPtr->AddAccountInfoIntoDataStorage(appAccountInfo);
1412 if (result != ERR_OK) {
1413 ACCOUNT_LOGE("failed to add account info into data storage, result %{public}d.", result);
1414 return result;
1415 }
1416 }
1417 #else // DISTRIBUTED_FEATURE_ENABLED
1418 ACCOUNT_LOGI("No distributed feature!");
1419 #endif // DISTRIBUTED_FEATURE_ENABLED
1420
1421 return ERR_OK;
1422 }
1423
1424 ErrCode AppAccountControlManager::SaveAccountInfoIntoDataStorage(
1425 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1426 {
1427 if (dataStoragePtr == nullptr) {
1428 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1429 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1430 }
1431
1432 ErrCode result = dataStoragePtr->SaveAccountInfoIntoDataStorage(appAccountInfo);
1433 if (result != ERR_OK) {
1434 ACCOUNT_LOGE("failed to save account info into data storage, result %{public}d.", result);
1435 return result;
1436 }
1437
1438 // for sync data storage
1439 #ifdef DISTRIBUTED_FEATURE_ENABLED
1440 if (NeedSyncDataStorage(appAccountInfo) == true) {
1441 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1442 if (dataStorageSyncPtr == nullptr) {
1443 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1444 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1445 }
1446 // Here do not open transaction, as it should be opened before this func is called
1447 std::string appAccountInfoFromDataStorage;
1448 result = dataStorageSyncPtr->GetValueFromKvStore(appAccountInfo.GetPrimeKey(), appAccountInfoFromDataStorage);
1449 if (result != ERR_OK) {
1450 ACCOUNT_LOGE("failed to get config by id from data storage, result %{public}d.", result);
1451
1452 result = dataStorageSyncPtr->AddAccountInfo(appAccountInfo);
1453 if (result != ERR_OK) {
1454 ACCOUNT_LOGE("failed to add account info, result = %{public}d", result);
1455 return result;
1456 }
1457 } else {
1458 result = dataStorageSyncPtr->SaveAccountInfo(appAccountInfo);
1459 if (result != ERR_OK) {
1460 ACCOUNT_LOGE("failed to save account info, result = %{public}d", result);
1461 return result;
1462 }
1463 }
1464 }
1465 #else // DISTRIBUTED_FEATURE_ENABLED
1466 ACCOUNT_LOGI("No distributed feature!");
1467 #endif // DISTRIBUTED_FEATURE_ENABLED
1468
1469 return ERR_OK;
1470 }
1471
1472 ErrCode AppAccountControlManager::DeleteAccountInfoFromDataStorage(
1473 AppAccountInfo &appAccountInfo, std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1474 {
1475 if (dataStoragePtr == nullptr) {
1476 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1477 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1478 }
1479
1480 ErrCode result = dataStoragePtr->GetAccountInfoFromDataStorage(appAccountInfo);
1481 if (result != ERR_OK) {
1482 ACCOUNT_LOGE("failed to get account info from data storage, result %{public}d.", result);
1483 return result;
1484 }
1485
1486 result = dataStoragePtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1487 if (result != ERR_OK) {
1488 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
1489 return result;
1490 }
1491
1492 // for sync data storage
1493 #ifdef DISTRIBUTED_FEATURE_ENABLED
1494 if (NeedSyncDataStorage(appAccountInfo) == true) {
1495 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1496 if (dataStorageSyncPtr == nullptr) {
1497 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1498 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1499 }
1500 // Here do not open transaction, as it should be opened before this func is called
1501 result = dataStorageSyncPtr->DeleteAccountInfoFromDataStorage(appAccountInfo);
1502 if (result != ERR_OK) {
1503 ACCOUNT_LOGE("failed to delete account info from data storage, result %{public}d.", result);
1504 }
1505 }
1506 #else // DISTRIBUTED_FEATURE_ENABLED
1507 ACCOUNT_LOGI("No distributed feature!");
1508 #endif // DISTRIBUTED_FEATURE_ENABLED
1509 return ERR_OK;
1510 }
1511
1512 ErrCode AppAccountControlManager::SaveAuthorizedAccount(const std::string &bundleName,
1513 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1514 {
1515 if (dataStoragePtr == nullptr) {
1516 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1517 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1518 }
1519
1520 ErrCode result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo, dataStoragePtr);
1521 if (result != ERR_OK) {
1522 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1523 return result;
1524 }
1525
1526 // for sync data storage
1527 #ifdef DISTRIBUTED_FEATURE_ENABLED
1528 if (NeedSyncDataStorage(appAccountInfo) == true) {
1529 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1530 if (dataStorageSyncPtr == nullptr) {
1531 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1532 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1533 }
1534 // Here do not open transaction, as it should be opened before this func is called
1535 result = SaveAuthorizedAccountIntoDataStorage(bundleName, appAccountInfo, dataStorageSyncPtr);
1536 if (result != ERR_OK) {
1537 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1538 return result;
1539 }
1540 }
1541 #else // DISTRIBUTED_FEATURE_ENABLED
1542 ACCOUNT_LOGI("No distributed feature!");
1543 #endif // DISTRIBUTED_FEATURE_ENABLED
1544
1545 return ERR_OK;
1546 }
1547
1548 ErrCode AppAccountControlManager::RemoveAuthorizedAccount(const std::string &bundleName,
1549 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr, const uid_t &uid)
1550 {
1551 if (dataStoragePtr == nullptr) {
1552 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1553 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1554 }
1555
1556 ErrCode result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo, dataStoragePtr);
1557 if (result != ERR_OK) {
1558 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1559 return result;
1560 }
1561
1562 // for sync data storage
1563 #ifdef DISTRIBUTED_FEATURE_ENABLED
1564 if (NeedSyncDataStorage(appAccountInfo) == true) {
1565 auto dataStorageSyncPtr = GetDataStorage(uid, true);
1566 if (dataStorageSyncPtr == nullptr) {
1567 ACCOUNT_LOGE("dataStorageSyncPtr is nullptr");
1568 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1569 }
1570 // Here do not open transaction, as it should be opened before this func is called
1571 result = RemoveAuthorizedAccountFromDataStorage(bundleName, appAccountInfo, dataStorageSyncPtr);
1572 if (result != ERR_OK) {
1573 ACCOUNT_LOGE("failed to save authorized account, result %{public}d.", result);
1574 return result;
1575 }
1576 }
1577 #else // DISTRIBUTED_FEATURE_ENABLED
1578 ACCOUNT_LOGI("No distributed feature!");
1579 #endif // DISTRIBUTED_FEATURE_ENABLED
1580
1581 return ERR_OK;
1582 }
1583
1584 ErrCode AppAccountControlManager::SaveAuthorizedAccountIntoDataStorage(const std::string &authorizedApp,
1585 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1586 {
1587 if (dataStoragePtr == nullptr) {
1588 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1589 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1590 }
1591
1592 std::string authorizedAccounts;
1593 ErrCode result = dataStoragePtr->GetValueFromKvStore(AUTHORIZED_ACCOUNTS,
1594 authorizedAccounts);
1595 if (result != ERR_OK) {
1596 ACCOUNT_LOGE("failed to get config by id from data storage, result %{public}d.", result);
1597 }
1598
1599 std::vector<std::string> accessibleAccounts;
1600 auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(
1601 authorizedAccounts, authorizedApp, accessibleAccounts);
1602
1603 auto accountId = appAccountInfo.GetPrimeKey();
1604
1605 auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);
1606 if (it == accessibleAccounts.end()) {
1607 accessibleAccounts.emplace_back(accountId);
1608 }
1609
1610 AddVectorStringToJson(jsonObject, authorizedApp, accessibleAccounts);
1611 authorizedAccounts = PackJsonToString(jsonObject);
1612 if (authorizedAccounts.empty()) {
1613 ACCOUNT_LOGE("Failed to dump json object.");
1614 return ERR_ACCOUNT_COMMON_DUMP_JSON_ERROR;
1615 }
1616
1617 result = dataStoragePtr->PutValueToKvStore(AUTHORIZED_ACCOUNTS, authorizedAccounts);
1618 if (result != ERR_OK) {
1619 ACCOUNT_LOGE("PutValueToKvStore failed! result %{public}d.", result);
1620 }
1621 return result;
1622 }
1623
1624 ErrCode AppAccountControlManager::RemoveAuthorizedAccountFromDataStorage(const std::string &authorizedApp,
1625 AppAccountInfo &appAccountInfo, const std::shared_ptr<AppAccountDataStorage> &dataStoragePtr)
1626 {
1627 if (dataStoragePtr == nullptr) {
1628 ACCOUNT_LOGE("dataStoragePtr is nullptr");
1629 return ERR_APPACCOUNT_SERVICE_DATA_STORAGE_PTR_IS_NULLPTR;
1630 }
1631
1632 std::string authorizedAccounts;
1633 ErrCode result = dataStoragePtr->GetValueFromKvStore(AUTHORIZED_ACCOUNTS,
1634 authorizedAccounts);
1635 if (result != ERR_OK) {
1636 ACCOUNT_LOGE("failed to get authorized accounts from data storage, result %{public}d.", result);
1637 }
1638
1639 std::vector<std::string> accessibleAccounts;
1640 auto jsonObject = dataStoragePtr->GetAccessibleAccountsFromAuthorizedAccounts(
1641 authorizedAccounts, authorizedApp, accessibleAccounts);
1642
1643 auto accountId = appAccountInfo.GetPrimeKey();
1644
1645 auto it = std::find(accessibleAccounts.begin(), accessibleAccounts.end(), accountId);
1646 if (it != accessibleAccounts.end()) {
1647 accessibleAccounts.erase(it);
1648 }
1649
1650 AddVectorStringToJson(jsonObject, authorizedApp, accessibleAccounts);
1651 authorizedAccounts = PackJsonToString(jsonObject);
1652 if (authorizedAccounts.empty()) {
1653 ACCOUNT_LOGE("Failed to dump json object.");
1654 return ERR_ACCOUNT_COMMON_DUMP_JSON_ERROR;
1655 }
1656
1657 result = dataStoragePtr->PutValueToKvStore(AUTHORIZED_ACCOUNTS, authorizedAccounts);
1658 if (result != ERR_OK) {
1659 ACCOUNT_LOGE("failed to save config info, result %{public}d.", result);
1660 return result;
1661 }
1662
1663 return ERR_OK;
1664 }
1665 } // namespace AccountSA
1666 } // namespace OHOS
1667