diff --git a/BUILD.gn b/BUILD.gn index f2f0f0befcebec4bbf9bcadac510a212e03e2508..f334150b7b10a5f69643740bf143b0ba266f705d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -22,6 +22,7 @@ group("accesstoken_build_module_test") { "//base/security/access_token/interfaces/innerkits/accesstoken/test:unittest", "//base/security/access_token/interfaces/innerkits/nativetoken/test:unittest", "//base/security/access_token/interfaces/innerkits/privacy/test:unittest", + "//base/security/access_token/interfaces/innerkits/token_callback/test:unittest", "//base/security/access_token/interfaces/innerkits/token_setproc/test:unittest", "//base/security/access_token/services/accesstokenmanager/test:unittest", ] diff --git a/README.md b/README.md index 709d3a7bdf5f8753fa2f1a99f7468054e5de4aaa..177f40424d0468686b238db1c01ae3e763d7ec96 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ The ATM module provides the following functions: | --- | --- | | AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); | Allocates a token ID to an app.| | AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); | Allocates a local token ID to the app of a remote device.| -| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); | Updates token information.| +| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); | Updates token information.| | int DeleteToken(AccessTokenID tokenID); | Deletes the app's token ID and information.| | int GetTokenType(AccessTokenID tokenID); | Obtains the type of an access token.| | int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); | Checks whether the native process corresponding to the given token ID has the specified distributed capability.| diff --git a/README_zh.md b/README_zh.md index 60e5fa6b46ce7c491c86357978ccd8d44d689ed5..5405b3abad861150ca03531b67faa0c66e45795f 100644 --- a/README_zh.md +++ b/README_zh.md @@ -44,7 +44,7 @@ ATM模块主要提供如下功能: | --- | --- | | AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); | 为应用进程分配一个tokenID | | AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); | 为远端设备的应用进程分配一个本地tokenID | -| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); | 更新tokenId对应的tokenInfo信息 | +| int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); | 更新tokenId对应的tokenInfo信息 | | int DeleteToken(AccessTokenID tokenID); | 删除应用tokenID及其对应的tokenInfo信息 | | int GetTokenType(AccessTokenID tokenID); | 查询指定tokenID的类型 | | int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); | 检测指定tokenID对应的native进程是否具有指定的分布式能力 | diff --git a/bundle.json b/bundle.json index 49e9ec63ea1525b41adac8b9906e395ddcf1bc9d..d1714f0f6914dc2090f75f9f4e3157878f09e34d 100644 --- a/bundle.json +++ b/bundle.json @@ -15,6 +15,7 @@ "syscap": [ "SystemCapability.Security.AccessToken" ], + "features": [ "access_token_feature_coverage = false" ], "adapted_system_type": [ "standard" ], "rom": "2048KB", "ram": "5102KB", diff --git a/config/BUILD.gn b/config/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c66738cb14bd7d1be7e6898a5ddc9ddb3c62d6c9 --- /dev/null +++ b/config/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +declare_args() { + access_token_feature_coverage = false +} + +config("coverage_flags") { + if (access_token_feature_coverage) { + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + } +} diff --git a/frameworks/accesstoken/BUILD.gn b/frameworks/accesstoken/BUILD.gn index bdc63b3da30b7ead14e4ff3c6d81c18a9102c78c..cdce923a175b2292bcac352f2dd3d6efbff0cf57 100644 --- a/frameworks/accesstoken/BUILD.gn +++ b/frameworks/accesstoken/BUILD.gn @@ -27,6 +27,7 @@ ohos_shared_library("accesstoken_communication_adapter_cxx") { part_name = "access_token" public_configs = [ ":accesstoken_communication_adapter_cxx_public_config" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] include_dirs = [ "include", @@ -48,8 +49,5 @@ ohos_shared_library("accesstoken_communication_adapter_cxx") { "src/permission_state_full_parcel.cpp", ] - external_deps = [ - "c_utils:utils", - "ipc:ipc_single", - ] + external_deps = [ "c_utils:utils" ] } diff --git a/frameworks/accesstoken/include/i_accesstoken_manager.h b/frameworks/accesstoken/include/i_accesstoken_manager.h index 466cafd370da437681a84f4dcb9cb037a3a28967..d5216bf647b3a3e34ed332314c8ad51d14ca6067 100644 --- a/frameworks/accesstoken/include/i_accesstoken_manager.h +++ b/frameworks/accesstoken/include/i_accesstoken_manager.h @@ -62,8 +62,8 @@ public: virtual AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) = 0; virtual int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) = 0; virtual int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) = 0; - virtual int UpdateHapToken( - AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParcel& policyParcel) = 0; + virtual int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, + const HapPolicyParcel& policyParcel) = 0; virtual int32_t RegisterPermStateChangeCallback( const PermStateChangeScopeParcel& scope, const sptr& callback) = 0; virtual int32_t UnRegisterPermStateChangeCallback(const sptr& callback) = 0; @@ -81,7 +81,7 @@ public: virtual int DeleteRemoteDeviceTokens(const std::string& deviceID) = 0; #endif - virtual void DumpTokenInfo(std::string& tokenInfo) = 0; + virtual void DumpTokenInfo(AccessTokenID tokenID, std::string& tokenInfo) = 0; enum class InterfaceCode { VERIFY_ACCESSTOKEN = 0xff10, diff --git a/frameworks/accesstoken/src/hap_info_parcel.cpp b/frameworks/accesstoken/src/hap_info_parcel.cpp index 8168de39239f47408078b8848c5b6d8df9030a8c..1816c72967982ba48972c60ffe4cd893de2c3e81 100644 --- a/frameworks/accesstoken/src/hap_info_parcel.cpp +++ b/frameworks/accesstoken/src/hap_info_parcel.cpp @@ -26,6 +26,7 @@ bool HapInfoParcel::Marshalling(Parcel& out) const RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.instIndex)); RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.dlpType)); RETURN_IF_FALSE(out.WriteString(this->hapInfoParameter.appIDDesc)); + RETURN_IF_FALSE(out.WriteInt32(this->hapInfoParameter.apiVersion)); return true; } @@ -38,6 +39,7 @@ HapInfoParcel* HapInfoParcel::Unmarshalling(Parcel& in) RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.instIndex), hapInfoParcel); RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.dlpType), hapInfoParcel); hapInfoParcel->hapInfoParameter.appIDDesc = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapInfoParcel->hapInfoParameter.apiVersion), hapInfoParcel); return hapInfoParcel; } diff --git a/frameworks/accesstoken/src/hap_policy_parcel.cpp b/frameworks/accesstoken/src/hap_policy_parcel.cpp index a437e4614c2d7cce60fe17866b24065bccff4af3..6bbccf7de8c1db04c83497277681c1fb2e2b48f3 100644 --- a/frameworks/accesstoken/src/hap_policy_parcel.cpp +++ b/frameworks/accesstoken/src/hap_policy_parcel.cpp @@ -41,7 +41,7 @@ bool HapPolicyParcel::Marshalling(Parcel& out) const } const std::vector& permStateList = this->hapPolicyParameter.permStateList; - int32_t permStateListSize = (int32_t)permStateList.size(); + int32_t permStateListSize = static_cast(permStateList.size()); RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); for (int i = 0; i < permStateListSize; i++) { diff --git a/frameworks/accesstoken/src/hap_token_info_parcel.cpp b/frameworks/accesstoken/src/hap_token_info_parcel.cpp index 414587d82cc9b3369627cde7963156ce7fa572d3..6d209ca4b63e72db0208d8d55c71f838fd57d38d 100644 --- a/frameworks/accesstoken/src/hap_token_info_parcel.cpp +++ b/frameworks/accesstoken/src/hap_token_info_parcel.cpp @@ -25,6 +25,7 @@ bool HapTokenInfoParcel::Marshalling(Parcel& out) const RETURN_IF_FALSE(out.WriteUint8(this->hapTokenInfoParams.ver)); RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.userID)); RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.bundleName)); + RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.apiVersion)); RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.instIndex)); RETURN_IF_FALSE(out.WriteInt32(this->hapTokenInfoParams.dlpType)); RETURN_IF_FALSE(out.WriteString(this->hapTokenInfoParams.appID)); @@ -46,6 +47,7 @@ HapTokenInfoParcel* HapTokenInfoParcel::Unmarshalling(Parcel& in) hapTokenInfoParcel->hapTokenInfoParams.ver = ver; RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.userID), hapTokenInfoParcel); hapTokenInfoParcel->hapTokenInfoParams.bundleName = in.ReadString(); + RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.apiVersion), hapTokenInfoParcel); RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.instIndex), hapTokenInfoParcel); RELEASE_IF_FALSE(in.ReadInt32(hapTokenInfoParcel->hapTokenInfoParams.dlpType), hapTokenInfoParcel); hapTokenInfoParcel->hapTokenInfoParams.appID = in.ReadString(); diff --git a/frameworks/accesstoken/src/native_token_info_parcel.cpp b/frameworks/accesstoken/src/native_token_info_parcel.cpp index d48c7fbd8f08c2f1d2477b88af54a7188e719add..621ce872c591eae6ecb34184b2e9b315b691c114 100644 --- a/frameworks/accesstoken/src/native_token_info_parcel.cpp +++ b/frameworks/accesstoken/src/native_token_info_parcel.cpp @@ -38,7 +38,7 @@ bool NativeTokenInfoParcel::Marshalling(Parcel& out) const int32_t dcapSize = static_cast((this->nativeTokenInfoParams.dcap).size()); RETURN_IF_FALSE(out.WriteInt32(dcapSize)); - for (auto dcapItem : this->nativeTokenInfoParams.dcap) { + for (const auto& dcapItem : this->nativeTokenInfoParams.dcap) { RETURN_IF_FALSE(out.WriteString(dcapItem)); } @@ -48,7 +48,7 @@ bool NativeTokenInfoParcel::Marshalling(Parcel& out) const int32_t nativeAclSize = static_cast((this->nativeTokenInfoParams.nativeAcls).size()); RETURN_IF_FALSE(out.WriteInt32(nativeAclSize)); - for (auto item : this->nativeTokenInfoParams.nativeAcls) { + for (const auto& item : this->nativeTokenInfoParams.nativeAcls) { RETURN_IF_FALSE(out.WriteString(item)); } diff --git a/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp b/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp index 7305a31a39f70f2b615a1a723a7a9d1096f5558a..8555df3533764777dee7971f36034edad0b48a5d 100644 --- a/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp +++ b/frameworks/accesstoken/src/permission_state_change_scope_parcel.cpp @@ -22,7 +22,7 @@ namespace AccessToken { bool PermStateChangeScopeParcel::Marshalling(Parcel& out) const { RETURN_IF_FALSE(out.WriteUint32((this->scope.tokenIDs.size()))); - for (auto& tokenID : this->scope.tokenIDs) { + for (const auto& tokenID : this->scope.tokenIDs) { RETURN_IF_FALSE(out.WriteUint32(tokenID)); } diff --git a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts index bd3544ad7f8ddd4efd8512fcdcc29ce2dc07a5c8..ff7fefae8705ae501be629054c3b9ca017090c0a 100644 --- a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts +++ b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/ServiceExtAbility/ServiceExtAbility.ts @@ -18,8 +18,7 @@ import window from '@ohos.window'; import display from '@ohos.display'; var TAG = "PermissionManager_Log:"; -const MAX_WIDTH = 790; -const MAX_HEIGHT = 1100; +const BG_COLOR = '#33000000' export default class ServiceExtensionAbility extends extension { /** @@ -42,10 +41,10 @@ export default class ServiceExtensionAbility extends extension { display.getDefaultDisplay().then(dis => { let navigationBarRect = { - left: (dis.width - MAX_WIDTH)/2, - top: (dis.height - MAX_HEIGHT)/2, - width: MAX_WIDTH, - height: MAX_HEIGHT + left: 0, + top: 0, + width: dis.width, + height: dis.height } this.createWindow("permissionDialog" + startId, window.WindowType.TYPE_DIALOG, navigationBarRect) }) @@ -71,7 +70,7 @@ export default class ServiceExtensionAbility extends extension { await win.moveTo(rect.left, rect.top) await win.resetSize(rect.width, rect.height) await win.loadContent('pages/dialogPlus') - await win.setBackgroundColor('#00000000') + await win.setBackgroundColor(BG_COLOR) await win.show() globalThis.windowNum ++ } catch { diff --git a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets index feae6cd0e73d0de1231b437391649f90e486f42a..1bfa23125625a0a3ff173eceef2f590ae786bbd1 100644 --- a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets +++ b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/common/utils/constant.ets @@ -344,5 +344,6 @@ export default class Constants { // static INITIAL_INDEX = 10 + static ACCESS_TOKEN = 'ohos.security.accesstoken.tokencallback' } \ No newline at end of file diff --git a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets index f833b2b938c38f0016918f47932b60acf817db7a..a56068a7223ded5d18965f4530906d85fbd97424 100644 --- a/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets +++ b/frameworks/com.ohos.permissionmanager/permissionmanager/src/main/ets/pages/dialogPlus.ets @@ -150,18 +150,16 @@ struct dialogPlusPage { let option = new rpc.MessageOption() let data = new rpc.MessageParcel() let reply = new rpc.MessageParcel() - if(!data.writeStringArray(perms)) { - Log.error('writeStringArray permission failed!') + Promise.all([data.writeInterfaceToken(Constants.ACCESS_TOKEN), + data.writeStringArray(perms), + data.writeIntArray(results) + ]).then(() => { + this.proxy.sendRequest(Constants.RESULT_CODE, data, reply, option) this.destruction() - return - } - if (!data.writeIntArray(results)) { - Log.error('writeIntArray result failed!') + }).catch(() => { + Log.error('write result failed!') this.destruction() - return - } - this.proxy.sendRequest(Constants.RESULT_CODE, data, reply, option) - this.destruction() + }) } destruction() { diff --git a/frameworks/common/BUILD.gn b/frameworks/common/BUILD.gn index 3970b261d89776d1a2f08aac024dc9bb01b47527..94911401af167861c5870cc71163a2dfedeec913 100644 --- a/frameworks/common/BUILD.gn +++ b/frameworks/common/BUILD.gn @@ -44,5 +44,7 @@ ohos_shared_library("accesstoken_common_cxx") { "init:libbegetutil", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] } diff --git a/frameworks/privacy/BUILD.gn b/frameworks/privacy/BUILD.gn index e721025514c3b6b9cb4139b702574334541bf9f7..a286ba1b2be70101b93c6089027448caa807b969 100644 --- a/frameworks/privacy/BUILD.gn +++ b/frameworks/privacy/BUILD.gn @@ -23,8 +23,11 @@ ohos_shared_library("privacy_communication_adapter_cxx") { "//base/security/access_token/interfaces/innerkits/privacy/include", "//base/security/access_token/frameworks/common/include", "//commonlibrary/c_utils/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + sources = [ "src/bundle_used_record_parcel.cpp", "src/perm_active_response_parcel.cpp", @@ -34,8 +37,5 @@ ohos_shared_library("privacy_communication_adapter_cxx") { "src/used_record_detail_parcel.cpp", ] - external_deps = [ - "c_utils:utils", - "ipc:ipc_core", - ] + external_deps = [ "c_utils:utils" ] } diff --git a/frameworks/privacy/include/i_privacy_manager.h b/frameworks/privacy/include/i_privacy_manager.h index 137f5886406aaf77e073d446879683e823247240..ff8bebda82f39a273b4e9568985444c7b3d7800f 100644 --- a/frameworks/privacy/include/i_privacy_manager.h +++ b/frameworks/privacy/include/i_privacy_manager.h @@ -44,7 +44,7 @@ public: const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) = 0; virtual int32_t GetPermissionUsedRecords( const PermissionUsedRequestParcel& request, const sptr& callback) = 0; - virtual std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) = 0; + virtual std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) = 0; virtual int32_t RegisterPermActiveStatusCallback( std::vector& permList, const sptr& callback) = 0; virtual int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) = 0; diff --git a/interfaces/innerkits/accesstoken/BUILD.gn b/interfaces/innerkits/accesstoken/BUILD.gn index 30d5d61293a47078c1fe9bc93b54de58acc4d907..653309ee76d61107b4c723fd2b57bab887afacc9 100644 --- a/interfaces/innerkits/accesstoken/BUILD.gn +++ b/interfaces/innerkits/accesstoken/BUILD.gn @@ -59,6 +59,8 @@ if (is_standard_system) { "samgr:samgr_proxy", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE", "-DDEBUG_API_PERFORMANCE", diff --git a/interfaces/innerkits/accesstoken/include/access_token.h b/interfaces/innerkits/accesstoken/include/access_token.h index 383cd6c732aaadafccb36c7572fd295e7db95d04..6cc15595ed20f3dbf96103f09fefd1d6e4ee7fa4 100644 --- a/interfaces/innerkits/accesstoken/include/access_token.h +++ b/interfaces/innerkits/accesstoken/include/access_token.h @@ -46,6 +46,7 @@ typedef enum TypeATokenTypeEnum { TOKEN_HAP = 0, TOKEN_NATIVE, TOKEN_SHELL, + TOKEN_TYPE_BUTT, } ATokenTypeEnum; typedef enum TypeATokenAplEnum { diff --git a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h index 64f6b7b5cb2d57dacb19262006c39da0c892fe76..ba1ebc0ebae558272e164f2edc049accf3052336 100644 --- a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h +++ b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h @@ -35,7 +35,8 @@ class AccessTokenKit { public: static AccessTokenIDEx AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy); static AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); - static int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); + static int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); static int DeleteToken(AccessTokenID tokenID); /* Get token type by ATM service */ static ATokenTypeEnum GetTokenType(AccessTokenID tokenID); @@ -73,7 +74,7 @@ public: static AccessTokenID GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID); static int DeleteRemoteDeviceTokens(const std::string& deviceID); #endif - static void DumpTokenInfo(std::string& dumpInfo); + static void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); }; } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/include/hap_token_info.h b/interfaces/innerkits/accesstoken/include/hap_token_info.h index a483188435dc3fe793f2ddc4a658e477dabd14c3..917b8733b3bd4217b12d9870a51a7fe862c4e084 100644 --- a/interfaces/innerkits/accesstoken/include/hap_token_info.h +++ b/interfaces/innerkits/accesstoken/include/hap_token_info.h @@ -32,6 +32,7 @@ public: int instIndex; int dlpType; std::string appIDDesc; + int32_t apiVersion; }; class HapPolicyParams final { @@ -48,6 +49,7 @@ public: char ver; int userID; std::string bundleName; + int32_t apiVersion; int instIndex; int dlpType; std::string appID; diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp index 5efb0221c479b0269f8af951bbdcb19b9e1ccfde..73a0e5ce837b8750cac77b26cb219967132338df 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -34,7 +34,7 @@ static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) { AccessTokenIDEx res = {0}; - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called!"); if ((!DataValidator::IsUserIdValid(info.userID)) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAplNumValid(policy.apl) || !DataValidator::IsDomainValid(policy.domain) || !DataValidator::IsDlpTypeValid(info.dlpType)) { @@ -47,54 +47,55 @@ AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const H AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", - __func__, ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s, tokenID=%{public}d", + ConstantCommon::EncryptDevId(remoteDeviceID).c_str(), remoteTokenID); #ifdef DEBUG_API_PERFORMANCE - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:start call"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "api_performance:start call"); AccessTokenID resID = AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); - ACCESSTOKEN_LOG_INFO(LABEL, "api_performance:end call"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "api_performance:end call"); return resID; #else return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); #endif } -int AccessTokenKit::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) +int AccessTokenKit::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); if ((tokenID == 0) || (!DataValidator::IsAppIDDescValid(appIDDesc)) || (!DataValidator::IsAplNumValid(policy.apl))) { ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); return RET_FAILED; } - return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, policy); + return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, apiVersion, policy); } int AccessTokenKit::DeleteToken(AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().DeleteToken(tokenID); } ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return TOKEN_INVALID; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().GetTokenType(tokenID); } ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return TOKEN_INVALID; } AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); @@ -103,7 +104,7 @@ ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; @@ -112,51 +113,48 @@ int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dc ACCESSTOKEN_LOG_ERROR(LABEL, "dcap is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); return AccessTokenManagerClient::GetInstance().CheckNativeDCap(tokenID, dcap); } AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", + userID, bundleName.c_str(), instIndex); if (!DataValidator::IsUserIdValid(userID) || !DataValidator::IsBundleNameValid(bundleName)) { ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); return 0; } - ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", - userID, bundleName.c_str(), instIndex); return AccessTokenManagerClient::GetInstance().GetHapTokenID(userID, bundleName, instIndex); } int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().GetHapTokenInfo(tokenID, hapTokenInfoRes); } int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().GetNativeTokenInfo(tokenID, nativeTokenInfoRes); } PermissionOper AccessTokenKit::GetSelfPermissionsState(std::vector& permList) { - ACCESSTOKEN_LOG_INFO(LABEL, "called."); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, permList.size=%{public}d.", (int)permList.size()); return AccessTokenManagerClient::GetInstance().GetSelfPermissionsState(permList); } int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, permissionName=%{public}s", + tokenID, permissionName.c_str()); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return PERMISSION_DENIED; @@ -165,13 +163,14 @@ int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return PERMISSION_DENIED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); return AccessTokenManagerClient::GetInstance().VerifyAccessToken(tokenID, permissionName); } int AccessTokenKit::VerifyAccessToken( AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, callerTokenID=%{public}d, firstTokenID=%{public}d, permissionName=%{public}s", + callerTokenID, firstTokenID, permissionName.c_str()); int ret = AccessTokenKit::VerifyAccessToken(callerTokenID, permissionName); if (ret != PERMISSION_GRANTED) { return ret; @@ -184,7 +183,8 @@ int AccessTokenKit::VerifyAccessToken( int AccessTokenKit::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, permissionName=%{public}s", + tokenID, permissionName.c_str()); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID=%{public}d is invalid", tokenID); return PERMISSION_DENIED; @@ -193,33 +193,30 @@ int AccessTokenKit::VerifyNativeToken(AccessTokenID tokenID, const std::string& ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return PERMISSION_DENIED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); return AccessTokenManagerClient::GetInstance().VerifyNativeToken(tokenID, permissionName); } int AccessTokenKit::GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, permissionName=%{public}s", permissionName.c_str()); if (!DataValidator::IsPermissionNameValid(permissionName)) { ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); int ret = AccessTokenManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult); - ACCESSTOKEN_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str()); return ret; } int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& permDefList) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().GetDefPermissions(tokenID, permDefList); } @@ -227,19 +224,19 @@ int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, isSystemGrant=%{public}d", tokenID, isSystemGrant); return AccessTokenManagerClient::GetInstance().GetReqPermissions(tokenID, reqPermList, isSystemGrant); } int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, permissionName=%{public}s", + tokenID, permissionName.c_str()); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return PERMISSION_DEFAULT_FLAG; @@ -248,13 +245,13 @@ int AccessTokenKit::GetPermissionFlag(AccessTokenID tokenID, const std::string& ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return PERMISSION_DEFAULT_FLAG; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); return AccessTokenManagerClient::GetInstance().GetPermissionFlag(tokenID, permissionName); } int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; @@ -267,13 +264,13 @@ int AccessTokenKit::GrantPermission(AccessTokenID tokenID, const std::string& pe ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", - tokenID, permissionName.c_str(), flag); return AccessTokenManagerClient::GetInstance().GrantPermission(tokenID, permissionName, flag); } int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", + tokenID, permissionName.c_str(), flag); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; @@ -286,18 +283,16 @@ int AccessTokenKit::RevokePermission(AccessTokenID tokenID, const std::string& p ACCESSTOKEN_LOG_ERROR(LABEL, "flag is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s, flag=%{public}d", - tokenID, permissionName.c_str(), flag); return AccessTokenManagerClient::GetInstance().RevokePermission(tokenID, permissionName, flag); } int AccessTokenKit::ClearUserGrantedPermissionState(AccessTokenID tokenID) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().ClearUserGrantedPermissionState(tokenID); } @@ -317,11 +312,11 @@ int32_t AccessTokenKit::UnRegisterPermStateChangeCallback( int32_t AccessTokenKit::GetHapDlpFlag(AccessTokenID tokenID) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return INVALID_DLP_TOKEN_FLAG; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); return (int32_t)(idInner->dlpFlag); } @@ -329,19 +324,18 @@ int32_t AccessTokenKit::GetHapDlpFlag(AccessTokenID tokenID) #ifdef TOKEN_SYNC_ENABLE int AccessTokenKit::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); if (tokenID == 0) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); return AccessTokenManagerClient::GetInstance().GetHapTokenInfoFromRemote(tokenID, hapSync); } int AccessTokenKit::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called"); return AccessTokenManagerClient::GetInstance().GetAllNativeTokenInfo(nativeTokenInfosRes); } @@ -349,46 +343,43 @@ int AccessTokenKit::GetAllNativeTokenInfo(std::vector& n int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", - __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), hapSync.baseInfo.tokenID); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s, tokenID=%{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), hapSync.baseInfo.tokenID); return AccessTokenManagerClient::GetInstance().SetRemoteHapTokenInfo(deviceID, hapSync); } int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, std::vector& nativeTokenInfoList) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, - ConstantCommon::EncryptDevId(deviceID).c_str()); - return AccessTokenManagerClient::GetInstance() - .SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); + return AccessTokenManagerClient::GetInstance().SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); } int AccessTokenKit::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", - __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s, tokenID=%{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); return AccessTokenManagerClient::GetInstance().DeleteRemoteToken(deviceID, tokenID); } int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, - ConstantCommon::EncryptDevId(deviceID).c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s", ConstantCommon::EncryptDevId(deviceID).c_str()); return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); } AccessTokenID AccessTokenKit::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", - __func__, ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, deviceID=%{public}s, tokenID=%{public}d", + ConstantCommon::EncryptDevId(deviceID).c_str(), tokenID); return AccessTokenManagerClient::GetInstance().GetRemoteNativeTokenID(deviceID, tokenID); } #endif -void AccessTokenKit::DumpTokenInfo(std::string& dumpInfo) +void AccessTokenKit::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - AccessTokenManagerClient::GetInstance().DumpTokenInfo(dumpInfo); + ACCESSTOKEN_LOG_DEBUG(LABEL, "called, tokenID=%{public}d", tokenID); + AccessTokenManagerClient::GetInstance().DumpTokenInfo(tokenID, dumpInfo); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp index 44f47003733ad197c87b7960346974c650a4e6c8..59fea9d5492bc56dd023a5a2d87570d4f9068b95 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp @@ -48,7 +48,6 @@ AccessTokenManagerClient::~AccessTokenManagerClient() int AccessTokenManagerClient::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -59,7 +58,6 @@ int AccessTokenManagerClient::VerifyAccessToken(AccessTokenID tokenID, const std int AccessTokenManagerClient::VerifyNativeToken(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -71,7 +69,6 @@ int AccessTokenManagerClient::VerifyNativeToken(AccessTokenID tokenID, const std int AccessTokenManagerClient::GetDefPermission( const std::string& permissionName, PermissionDef& permissionDefResult) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -85,7 +82,6 @@ int AccessTokenManagerClient::GetDefPermission( int AccessTokenManagerClient::GetDefPermissions(AccessTokenID tokenID, std::vector& permList) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -103,7 +99,6 @@ int AccessTokenManagerClient::GetDefPermissions(AccessTokenID tokenID, std::vect int AccessTokenManagerClient::GetReqPermissions( AccessTokenID tokenID, std::vector& reqPermList, bool isSystemGrant) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -120,7 +115,6 @@ int AccessTokenManagerClient::GetReqPermissions( int AccessTokenManagerClient::GetPermissionFlag(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -129,10 +123,8 @@ int AccessTokenManagerClient::GetPermissionFlag(AccessTokenID tokenID, const std return proxy->GetPermissionFlag(tokenID, permissionName); } -PermissionOper AccessTokenManagerClient::GetSelfPermissionsState( - std::vector& permList) +PermissionOper AccessTokenManagerClient::GetSelfPermissionsState(std::vector& permList) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "permList.size() : %{public}d.", (int)permList.size()); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null."); @@ -166,7 +158,6 @@ PermissionOper AccessTokenManagerClient::GetSelfPermissionsState( int AccessTokenManagerClient::GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -177,7 +168,6 @@ int AccessTokenManagerClient::GrantPermission(AccessTokenID tokenID, const std:: int AccessTokenManagerClient::RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -188,7 +178,6 @@ int AccessTokenManagerClient::RevokePermission(AccessTokenID tokenID, const std: int AccessTokenManagerClient::ClearUserGrantedPermissionState(AccessTokenID tokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -226,8 +215,6 @@ int32_t AccessTokenManagerClient::CreatePermStateChangeCallback( int32_t AccessTokenManagerClient::RegisterPermStateChangeCallback( const std::shared_ptr& customizedCb) { - ACCESSTOKEN_LOG_INFO(LABEL, "called!"); - if (customizedCb == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "customizedCb is nullptr"); return RET_FAILED; @@ -253,8 +240,6 @@ int32_t AccessTokenManagerClient::RegisterPermStateChangeCallback( int32_t AccessTokenManagerClient::UnRegisterPermStateChangeCallback( const std::shared_ptr& customizedCb) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: called!", __func__); - std::lock_guard lock(callbackMutex_); auto goalCallback = callbackMap_.find(customizedCb); if (goalCallback == callbackMap_.end()) { @@ -278,7 +263,6 @@ int32_t AccessTokenManagerClient::UnRegisterPermStateChangeCallback( AccessTokenIDEx AccessTokenManagerClient::AllocHapToken(const HapInfoParams& info, const HapPolicyParams& policy) { AccessTokenIDEx res = { 0 }; - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -294,7 +278,6 @@ AccessTokenIDEx AccessTokenManagerClient::AllocHapToken(const HapInfoParams& inf int AccessTokenManagerClient::DeleteToken(AccessTokenID tokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -305,7 +288,6 @@ int AccessTokenManagerClient::DeleteToken(AccessTokenID tokenID) ATokenTypeEnum AccessTokenManagerClient::GetTokenType(AccessTokenID tokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -316,7 +298,6 @@ ATokenTypeEnum AccessTokenManagerClient::GetTokenType(AccessTokenID tokenID) int AccessTokenManagerClient::CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -327,7 +308,6 @@ int AccessTokenManagerClient::CheckNativeDCap(AccessTokenID tokenID, const std:: AccessTokenID AccessTokenManagerClient::GetHapTokenID(int userID, const std::string& bundleName, int instIndex) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -339,7 +319,6 @@ AccessTokenID AccessTokenManagerClient::GetHapTokenID(int userID, const std::str AccessTokenID AccessTokenManagerClient::AllocLocalTokenID( const std::string& remoteDeviceID, AccessTokenID remoteTokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -349,9 +328,8 @@ AccessTokenID AccessTokenManagerClient::AllocLocalTokenID( } int AccessTokenManagerClient::UpdateHapToken( - AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -359,12 +337,11 @@ int AccessTokenManagerClient::UpdateHapToken( } HapPolicyParcel hapPolicyParcel; hapPolicyParcel.hapPolicyParameter = policy; - return proxy->UpdateHapToken(tokenID, appIDDesc, hapPolicyParcel); + return proxy->UpdateHapToken(tokenID, appIDDesc, apiVersion, hapPolicyParcel); } int AccessTokenManagerClient::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -379,7 +356,6 @@ int AccessTokenManagerClient::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInf int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -394,7 +370,6 @@ int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTo #ifdef TOKEN_SYNC_ENABLE int AccessTokenManagerClient::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -409,7 +384,6 @@ int AccessTokenManagerClient::GetHapTokenInfoFromRemote(AccessTokenID tokenID, H int AccessTokenManagerClient::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -428,7 +402,6 @@ int AccessTokenManagerClient::GetAllNativeTokenInfo(std::vector& nativeTokenInfoList) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -464,7 +436,6 @@ int AccessTokenManagerClient::SetRemoteNativeTokenInfo(const std::string& device int AccessTokenManagerClient::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -477,7 +448,6 @@ int AccessTokenManagerClient::DeleteRemoteToken(const std::string& deviceID, Acc AccessTokenID AccessTokenManagerClient::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -490,7 +460,6 @@ AccessTokenID AccessTokenManagerClient::GetRemoteNativeTokenID(const std::string int AccessTokenManagerClient::DeleteRemoteDeviceTokens(const std::string& deviceID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); @@ -502,15 +471,14 @@ int AccessTokenManagerClient::DeleteRemoteDeviceTokens(const std::string& device } #endif -void AccessTokenManagerClient::DumpTokenInfo(std::string& dumpInfo) +void AccessTokenManagerClient::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); return; } - proxy->DumpTokenInfo(dumpInfo); + proxy->DumpTokenInfo(tokenID, dumpInfo); } void AccessTokenManagerClient::InitProxy() @@ -519,12 +487,12 @@ void AccessTokenManagerClient::InitProxy() if (proxy_ == nullptr) { auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sam == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); + ACCESSTOKEN_LOG_ERROR(LABEL, "GetSystemAbilityManager is null"); return; } auto accesstokenSa = sam->GetSystemAbility(IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); if (accesstokenSa == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", + ACCESSTOKEN_LOG_ERROR(LABEL, "GetSystemAbility %{public}d is null", IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); return; } @@ -535,7 +503,7 @@ void AccessTokenManagerClient::InitProxy() } proxy_ = iface_cast(accesstokenSa); if (proxy_ == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); + ACCESSTOKEN_LOG_ERROR(LABEL, "iface_cast get null"); } } } diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h index f2ef276aef302b6666796c5cd93fd63c4bc49124..8a0e14df3336098fe0699e87bb5652cb4b0b151d 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h @@ -60,7 +60,8 @@ public: int CheckNativeDCap(AccessTokenID tokenID, const std::string& dcap); AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); - int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); + int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); int32_t RegisterPermStateChangeCallback( @@ -79,7 +80,7 @@ public: int DeleteRemoteDeviceTokens(const std::string& deviceID); #endif - void DumpTokenInfo(std::string& dumpInfo); + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); void OnRemoteDiedHandle(); private: diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp index 0b5b01b17ce9d59028779c6ed7901ca490895d99..078f8e4e8303993a35b15650245b5b14ac244827 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp @@ -62,7 +62,7 @@ int AccessTokenManagerProxy::VerifyAccessToken(AccessTokenID tokenID, const std: } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -94,7 +94,7 @@ int AccessTokenManagerProxy::VerifyNativeToken(AccessTokenID tokenID, const std: } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -129,7 +129,7 @@ int AccessTokenManagerProxy::GetDefPermission( } permissionDefResult = *resultSptr; int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -169,7 +169,7 @@ int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, } } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -213,7 +213,7 @@ int AccessTokenManagerProxy::GetReqPermissions( } } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -245,7 +245,7 @@ int AccessTokenManagerProxy::GetPermissionFlag(AccessTokenID tokenID, const std: } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -280,10 +280,6 @@ PermissionOper AccessTokenManagerProxy::GetSelfPermissionsState( } PermissionOper result = static_cast(reply.ReadInt32()); - if (result == INVALID_OPER) { - ACCESSTOKEN_LOG_ERROR(LABEL, "result from server is invalid!"); - return result; - } size_t size = reply.ReadUint32(); if (size != permListParcel.size()) { ACCESSTOKEN_LOG_ERROR(LABEL, "permListParcel size from server is invalid!"); @@ -296,7 +292,7 @@ PermissionOper AccessTokenManagerProxy::GetSelfPermissionsState( } } - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -332,7 +328,7 @@ int AccessTokenManagerProxy::GrantPermission(AccessTokenID tokenID, const std::s } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -368,7 +364,7 @@ int AccessTokenManagerProxy::RevokePermission(AccessTokenID tokenID, const std:: } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -396,7 +392,7 @@ int AccessTokenManagerProxy::ClearUserGrantedPermissionState(AccessTokenID token } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -436,6 +432,7 @@ int32_t AccessTokenManagerProxy::RegisterPermStateChangeCallback( ACCESSTOKEN_LOG_ERROR(LABEL, "ReadInt32 fail"); return RET_FAILED; } + ACCESSTOKEN_LOG_INFO(LABEL, "result from server data = %{public}d", result); return result; } @@ -471,6 +468,7 @@ int32_t AccessTokenManagerProxy::UnRegisterPermStateChangeCallback(const sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::DUMP_TOKENINFO), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return; } dumpInfo = reply.ReadString(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server dumpInfo = %{public}s", __func__, dumpInfo.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server dumpInfo = %{public}s", dumpInfo.c_str()); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h index 6177b1c6da6ecc6397b9902930b1a0797d505191..809061d35d05cd394cb33188e16ebf1bfef055ef 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h @@ -57,7 +57,7 @@ public: AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) override; AccessTokenIDEx AllocHapToken(const HapInfoParcel& hapInfo, const HapPolicyParcel& policyParcel) override; int DeleteToken(AccessTokenID tokenID) override; - int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, + int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyPar) override; int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) override; int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) override; @@ -76,7 +76,7 @@ public: int DeleteRemoteDeviceTokens(const std::string& deviceID) override; #endif - void DumpTokenInfo(std::string& dumpInfo) override; + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) override; private: static inline BrokerDelegator delegator_; diff --git a/interfaces/innerkits/accesstoken/test/BUILD.gn b/interfaces/innerkits/accesstoken/test/BUILD.gn index 458557d8c615d3abf81ad3cf2996b4111e16d970..fb1fda81a6b8b35d9416696a360038c90a63f49e 100644 --- a/interfaces/innerkits/accesstoken/test/BUILD.gn +++ b/interfaces/innerkits/accesstoken/test/BUILD.gn @@ -26,12 +26,16 @@ ohos_unittest("libaccesstoken_sdk_test") { "//base/security/access_token/interfaces/innerkits/nativetoken/include", "//base/security/access_token/interfaces/innerkits/token_setproc/include", "//base/security/access_token/frameworks/common/include", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/common", ] sources = [ "unittest/src/accesstoken_kit_test.cpp" ] cflags_cc = [ "-DHILOG_ENABLE" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", @@ -40,9 +44,7 @@ ohos_unittest("libaccesstoken_sdk_test") { external_deps = [ "c_utils:utils", - "dsoftbus:softbus_client", "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", ] if (token_sync_enable == true) { cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp index 700a7bb989366ef57a3c019a4e1a049e8976e957..e4544897fe4f2ecfa587d2ce3e1fc43048d12c0e 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.cpp @@ -23,9 +23,13 @@ #include "softbus_bus_center.h" using namespace testing::ext; -using namespace OHOS::Security::AccessToken; +namespace OHOS { +namespace Security { +namespace AccessToken { namespace { +static constexpr int32_t DEFAULT_API_VERSION = 8; +static constexpr int32_t VAGUE_LOCATION_API_VERSION = 9; static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenKitTest"}; PermissionStateFull g_grantPermissionReq = { @@ -47,45 +51,46 @@ PermissionDef g_infoManagerTestPermDef1 = { .permissionName = "ohos.permission.test1", .bundleName = "accesstoken_test", .grantMode = 1, + .availableLevel = APL_NORMAL, .label = "label", .labelId = 1, .description = "open the door", - .descriptionId = 1, - .availableLevel = APL_NORMAL + .descriptionId = 1 }; PermissionDef g_infoManagerTestPermDef2 = { .permissionName = "ohos.permission.test2", .bundleName = "accesstoken_test", .grantMode = 1, + .availableLevel = APL_NORMAL, .label = "label", .labelId = 1, .description = "break the door", - .descriptionId = 1, - .availableLevel = APL_NORMAL + .descriptionId = 1 }; PermissionStateFull g_infoManagerTestState1 = { - .grantFlags = {1}, - .grantStatus = {PermissionState::PERMISSION_GRANTED}, - .isGeneral = true, .permissionName = "ohos.permission.test1", - .resDeviceID = {"local"} + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1} }; PermissionStateFull g_infoManagerTestState2 = { .permissionName = "ohos.permission.test2", .isGeneral = false, - .grantFlags = {1, 2}, + .resDeviceID = {"device 1", "device 2"}, .grantStatus = {PermissionState::PERMISSION_GRANTED, PermissionState::PERMISSION_GRANTED}, - .resDeviceID = {"device 1", "device 2"} + .grantFlags = {1, 2} }; HapInfoParams g_infoManagerTestInfoParms = { - .bundleName = "accesstoken_test", .userID = 1, + .bundleName = "accesstoken_test", .instIndex = 0, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; HapPolicyParams g_infoManagerTestPolicyPrams = { @@ -96,10 +101,11 @@ HapPolicyParams g_infoManagerTestPolicyPrams = { }; HapInfoParams g_infoManagerTestInfoParmsBak = { - .bundleName = "accesstoken_test", .userID = 1, + .bundleName = "accesstoken_test", .instIndex = 0, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; HapPolicyParams g_infoManagerTestPolicyPramsBak = { @@ -108,6 +114,113 @@ HapPolicyParams g_infoManagerTestPolicyPramsBak = { .permList = {g_infoManagerTestPermDef1, g_infoManagerTestPermDef2}, .permStateList = {g_infoManagerTestState1, g_infoManagerTestState2} }; + +HapInfoParams g_locationTestInfo = { + .userID = TEST_USER_ID, + .bundleName = "accesstoken_location_test", + .instIndex = 0, + .appIDDesc = "testtesttesttest" +}; + +PermissionDef g_locationTestDefVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .bundleName = "accesstoken_location_test", + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = true +}; + +PermissionDef g_locationTestDefAccurate = { + .permissionName = "ohos.permission.LOCATION", + .bundleName = "accesstoken_location_test", + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = true, + .distributedSceneEnable = true +}; + +PermissionDef g_locationTestDefSystemGrant = { + .permissionName = "ohos.permission.locationtest1", + .bundleName = "accesstoken_location_test", + .grantMode = GrantMode::SYSTEM_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; + +PermissionDef g_locationTestDefUserGrant = { + .permissionName = "ohos.permission.locationtest2", + .bundleName = "accesstoken_location_test", + .grantMode = GrantMode::USER_GRANT, + .availableLevel = APL_NORMAL, + .provisionEnable = false, + .distributedSceneEnable = false +}; + +PermissionStateFull g_locationTestStateSystemGrant = { + .permissionName = "ohos.permission.locationtest1", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} +}; + +PermissionStateFull g_locationTestStateUserGrant = { + .permissionName = "ohos.permission.locationtest2", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_DEFAULT_FLAG} +}; + +PermissionStateFull g_locationTestStateVague02 = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_FIXED} +}; + +PermissionStateFull g_locationTestStateVague10 = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_DEFAULT_FLAG} +}; + +PermissionStateFull g_locationTestStateVague12 = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_FIXED} +}; + +PermissionStateFull g_locationTestStateAccurate02 = { + .permissionName = "ohos.permission.LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_FIXED} +}; + +PermissionStateFull g_locationTestStateAccurate10 = { + .permissionName = "ohos.permission.LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_DEFAULT_FLAG} +}; + +PermissionStateFull g_locationTestStateAccurate12 = { + .permissionName = "ohos.permission.LOCATION", + .isGeneral = true, + .resDeviceID = {"device"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_USER_FIXED} +}; } void AccessTokenKitTest::SetUpTestCase() @@ -136,6 +249,7 @@ void AccessTokenKitTest::SetUp() .bundleName = TEST_BUNDLE_NAME, .instIndex = 0, .appIDDesc = "appIDDesc", + .apiVersion = DEFAULT_API_VERSION }; HapPolicyParams policy = { @@ -216,35 +330,35 @@ void AccessTokenKitTest::SetUp() .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED} }; PermissionStateFull permTestState1 = { - .grantFlags = {0}, - .grantStatus = {PermissionState::PERMISSION_DENIED}, - .isGeneral = true, .permissionName = "ohos.permission.testPermDef1", - .resDeviceID = {"local"} + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {0}, }; PermissionStateFull permTestState2 = { - .grantFlags = {1}, - .grantStatus = {PermissionState::PERMISSION_DENIED}, - .isGeneral = true, .permissionName = "ohos.permission.testPermDef2", - .resDeviceID = {"local"} + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {1} }; PermissionStateFull permTestState3 = { - .grantFlags = {2}, - .grantStatus = {PermissionState::PERMISSION_DENIED}, - .isGeneral = true, .permissionName = "ohos.permission.testPermDef3", - .resDeviceID = {"local"} + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {2} }; PermissionStateFull permTestState4 = { - .grantFlags = {1}, - .grantStatus = {PermissionState::PERMISSION_GRANTED}, - .isGeneral = true, .permissionName = "ohos.permission.testPermDef4", - .resDeviceID = {"local"} + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1} }; policy.permStateList.emplace_back(permStatAlpha); @@ -273,6 +387,31 @@ void AccessTokenKitTest::TearDown() SetSelfTokenID(selfTokenId_); } +void AccessTokenKitTest::AllocHapToken(std::vector& permmissionDefs, + std::vector& permissionStateFulls, int32_t apiVersion) +{ + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + AccessTokenKit::DeleteToken(tokenID); + + HapInfoParams info = g_locationTestInfo; + info.apiVersion = apiVersion; + + HapPolicyParams policy = { + .apl = APL_NORMAL, + .domain = "domain" + }; + + for (auto& permmissionDef:permmissionDefs) { + policy.permList.emplace_back(permmissionDef); + } + + for (auto& permissionStateFull:permissionStateFulls) { + policy.permStateList.emplace_back(permissionStateFull); + } + + AccessTokenKit::AllocHapToken(info, policy); +} + unsigned int AccessTokenKitTest::GetAccessTokenID(int userID, std::string bundleName, int instIndex) { return AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); @@ -495,7 +634,7 @@ HWTEST_F(AccessTokenKitTest, GetReqPermissions003, TestSize.Level1) }; policy.permStateList.clear(); - ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, policy); + ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, DEFAULT_API_VERSION, policy); ASSERT_EQ(RET_SUCCESS, ret); std::vector permStatUserList; @@ -726,7 +865,7 @@ HWTEST_F(AccessTokenKitTest, VerifyAccessToken004, TestSize.Level0) .permStateList = permStatList }; - ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, policy); + ret = AccessTokenKit::UpdateHapToken(tokenID, hapInfo.appID, DEFAULT_API_VERSION, policy); ASSERT_EQ(RET_SUCCESS, ret); ret = AccessTokenKit::VerifyAccessToken(tokenID, TEST_PERMISSION_NAME_ALPHA); @@ -1679,25 +1818,28 @@ HWTEST_F(AccessTokenKitTest, AllocHapToken018, TestSize.Level1) .permStateList = {} }; HapInfoParams infoManagerTestInfoParms1 = { - .bundleName = "dlp_test1", .userID = 1, + .bundleName = "dlp_test1", .instIndex = 0, .dlpType = DLP_COMMON, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; HapInfoParams infoManagerTestInfoParms2 = { - .bundleName = "dlp_test2", .userID = 1, + .bundleName = "dlp_test2", .instIndex = 1, .dlpType = DLP_READ, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; HapInfoParams infoManagerTestInfoParms3 = { - .bundleName = "dlp_test3", .userID = 1, + .bundleName = "dlp_test3", .instIndex = 2, .dlpType = DLP_FULL_CONTROL, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; HapTokenInfo hapTokenInfoRes; AccessTokenID tokenID; @@ -1765,11 +1907,12 @@ HWTEST_F(AccessTokenKitTest, AllocHapToken019, TestSize.Level1) .permStateList = {} }; HapInfoParams infoManagerTestInfoParms1 = { - .bundleName = "accesstoken_test", .userID = 1, + .bundleName = "accesstoken_test", .instIndex = 4, .dlpType = INVALID_DLP_TYPE, - .appIDDesc = "testtesttesttest" + .appIDDesc = "testtesttesttest", + .apiVersion = DEFAULT_API_VERSION }; tokenIdEx = AccessTokenKit::AllocHapToken(infoManagerTestInfoParms1, infoManagerTestPolicyPrams); @@ -1798,7 +1941,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken001, TestSize.Level1) GTEST_LOG_(INFO) << "tokenID :" << tokenID; g_infoManagerTestPolicyPrams.apl = APL_SYSTEM_BASIC; - int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(0, ret); HapTokenInfo hapTokenInfoRes; @@ -1820,7 +1963,8 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken001, TestSize.Level1) */ HWTEST_F(AccessTokenKitTest, UpdateHapToken002, TestSize.Level1) { - int ret = AccessTokenKit::UpdateHapToken(TEST_USER_ID_INVALID, "appIDDesc", g_infoManagerTestPolicyPrams); + int ret = AccessTokenKit::UpdateHapToken( + TEST_USER_ID_INVALID, "appIDDesc", DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_FAILED, ret); } @@ -1843,7 +1987,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken003, TestSize.Level1) AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(userID, bundleName, instIndex); - int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_FAILED, ret); HapTokenInfo hapTokenInfoRes; @@ -1877,7 +2021,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken004, TestSize.Level1) g_infoManagerTestPolicyPrams.apl = (ATokenAplEnum)5; - int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_FAILED, ret); HapTokenInfo hapTokenInfoRes; @@ -1909,7 +2053,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken005, TestSize.Level1) std::string backup = g_infoManagerTestPolicyPrams.permList[0].permissionName; g_infoManagerTestPolicyPrams.permList[0].permissionName = ""; - int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); ASSERT_EQ(RET_FAILED, ret); g_infoManagerTestPolicyPrams.permList[0].permissionName = backup; @@ -1918,7 +2062,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken005, TestSize.Level1) g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp11"; backup = g_infoManagerTestPolicyPrams.permList[0].bundleName; g_infoManagerTestPolicyPrams.permList[0].bundleName = ""; - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); ASSERT_EQ(RET_FAILED, ret); g_infoManagerTestPolicyPrams.permList[0].bundleName = backup; @@ -1928,7 +2072,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken005, TestSize.Level1) g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp12"; backup = g_infoManagerTestPolicyPrams.permList[0].label; g_infoManagerTestPolicyPrams.permList[0].label = ""; - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_SUCCESS, ret); ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); ASSERT_EQ(RET_SUCCESS, ret); @@ -1939,7 +2083,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken005, TestSize.Level1) g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.testtmp13"; backup = g_infoManagerTestPolicyPrams.permList[0].description; g_infoManagerTestPolicyPrams.permList[0].description = ""; - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_SUCCESS, ret); ret = AccessTokenKit::GetDefPermission(g_infoManagerTestPolicyPrams.permList[0].permissionName, permDefResult); ASSERT_EQ(RET_SUCCESS, ret); @@ -1988,7 +2132,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken006, TestSize.Level1) infoManagerTestInfo.instIndex = 1; g_infoManagerTestPolicyPrams.apl = APL_SYSTEM_BASIC; for (size_t i = 0; i < obj.size(); i++) { - ret = AccessTokenKit::UpdateHapToken(obj[i], appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(obj[i], appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); if (RET_SUCCESS != ret) { updateFlag = 1; break; @@ -2032,7 +2176,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken007, TestSize.Level1) backup = g_infoManagerTestPolicyPrams.permList[0].permissionName; g_infoManagerTestPolicyPrams.permList[0].permissionName = "ohos.permission.test3"; - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_SUCCESS, ret); g_infoManagerTestPolicyPrams.permList[0].permissionName = backup; @@ -2078,7 +2222,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken008, TestSize.Level1) backup = g_infoManagerTestPolicyPrams.permList[0].label; g_infoManagerTestPolicyPrams.permList[0].grantMode = 0; g_infoManagerTestPolicyPrams.permList[0].label = "updated label"; - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, g_infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, g_infoManagerTestPolicyPrams); ASSERT_EQ(RET_SUCCESS, ret); g_infoManagerTestPolicyPrams.permList[0].label = backup; g_infoManagerTestPolicyPrams.permList[0].grantMode = 1; @@ -2107,17 +2251,19 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken009, TestSize.Level1) const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; PermissionDef infoManagerTestPermDef = g_infoManagerTestPermDef1; PermissionStateFull infoManagerTestState = { - .grantFlags = {PermissionState::PERMISSION_DENIED}, - .grantStatus = {3}, - .isGeneral = true, .permissionName = "ohos.permission.test1", - .resDeviceID = {"local"}}; + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {3}, + .grantFlags = {PermissionState::PERMISSION_DENIED} + }; HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_NORMAL, .domain = "test.domain", .permList = {infoManagerTestPermDef}, - .permStateList = {infoManagerTestState}}; + .permStateList = {infoManagerTestState} + }; DeleteTestToken(); AccessTokenIDEx tokenIdEx = {0}; @@ -2128,7 +2274,7 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken009, TestSize.Level1) ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.test1"); ASSERT_EQ(ret, g_infoManagerTestState1.grantStatus[0]); - ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, infoManagerTestPolicyPrams); + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, DEFAULT_API_VERSION, infoManagerTestPolicyPrams); ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.test1"); ASSERT_EQ(ret, PermissionState::PERMISSION_DENIED); @@ -2137,6 +2283,34 @@ HWTEST_F(AccessTokenKitTest, UpdateHapToken009, TestSize.Level1) ASSERT_EQ(RET_SUCCESS, ret); } +/** + * @tc.name: UpdateHapToken010 + * @tc.desc: update api version. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, UpdateHapToken010, TestSize.Level1) +{ + AccessTokenIDEx tokenIdEx = {0}; + const std::string appIDDesc = g_infoManagerTestInfoParms.appIDDesc; + tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + GTEST_LOG_(INFO) << "tokenID :" << tokenID; + + uint32_t apiVersion = DEFAULT_API_VERSION - 1; + int ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, apiVersion, g_infoManagerTestPolicyPrams); + + HapTokenInfo hapTokenInfoRes; + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(apiVersion, hapTokenInfoRes.apiVersion); + + apiVersion = DEFAULT_API_VERSION + 1; + ret = AccessTokenKit::UpdateHapToken(tokenID, appIDDesc, apiVersion, g_infoManagerTestPolicyPrams); + + ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); + ASSERT_EQ(apiVersion, hapTokenInfoRes.apiVersion); +} + static void *ThreadTestFunc01(void *args) { ATokenTypeEnum type; @@ -2397,6 +2571,477 @@ HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState001, TestSize.Level1) ASSERT_EQ(PASS_OPER, ret); } +/** + * @tc.name: GetSelfPermissionsState002 + * @tc.desc: only vague location permission + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState002, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(1, permsList.size()); + ASSERT_EQ(DYNAMIC_OPER, permsList[0].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState003 + * @tc.desc: only vague location permission after refuse + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState003, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague12); // {-1,2} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(PASS_OPER, ret); + ASSERT_EQ(1, permsList.size()); + ASSERT_EQ(SETTING_OPER, permsList[0].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState004 + * @tc.desc: only vague location permission after accept + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState004, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague02); // {0,2} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(PASS_OPER, ret); + ASSERT_EQ(1, permsList.size()); + ASSERT_EQ(PASS_OPER, permsList[0].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState005 + * @tc.desc: only accurate location permission + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState005, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(INVALID_OPER, ret); + ASSERT_EQ(1, permsList.size()); + ASSERT_EQ(INVALID_OPER, permsList[0].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState006 + * @tc.desc: all location permissions + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState006, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague10); // {-1,0} + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(2, permsList.size()); + ASSERT_EQ(DYNAMIC_OPER, permsList[0].state); + ASSERT_EQ(DYNAMIC_OPER, permsList[1].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState007 + * @tc.desc: all location permissions after accept vague location permission + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState007, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague02); // {0,2} + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(2, permsList.size()); + ASSERT_EQ(PASS_OPER, permsList[0].state); + ASSERT_EQ(DYNAMIC_OPER, permsList[1].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState008 + * @tc.desc: all location permissions after refuse vague location permission + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState008, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague12); // {-1,2} + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(PASS_OPER, ret); + ASSERT_EQ(2, permsList.size()); + ASSERT_EQ(SETTING_OPER, permsList[0].state); + ASSERT_EQ(SETTING_OPER, permsList[1].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState009 + * @tc.desc: all location permissions after accept all location permissions + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState009, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague02); // {0,2} + permissionStateFulls.emplace_back(g_locationTestStateAccurate02); // {0,2} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(PASS_OPER, ret); + ASSERT_EQ(2, permsList.size()); + ASSERT_EQ(PASS_OPER, permsList[0].state); + ASSERT_EQ(PASS_OPER, permsList[1].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState010 + * @tc.desc: all location permissions whith other permissions + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState010, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + permmissionDefs.emplace_back(g_locationTestDefSystemGrant); + permmissionDefs.emplace_back(g_locationTestDefUserGrant); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague10); // {-1,0} + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + permissionStateFulls.emplace_back(g_locationTestStateSystemGrant); // {0,4} + permissionStateFulls.emplace_back(g_locationTestStateUserGrant); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, VAGUE_LOCATION_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + PermissionListState permSystem = { + .permissionName = "ohos.permission.locationtest1", + .state = -1, + }; + PermissionListState permUser = { + .permissionName = "ohos.permission.locationtest2", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + permsList.emplace_back(permSystem); + permsList.emplace_back(permUser); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(4, permsList.size()); + ASSERT_EQ(DYNAMIC_OPER, permsList[0].state); + ASSERT_EQ(DYNAMIC_OPER, permsList[1].state); + ASSERT_EQ(PASS_OPER, permsList[2].state); + ASSERT_EQ(DYNAMIC_OPER, permsList[3].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState011 + * @tc.desc: only accurate location permission whith api8 + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState011, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, DEFAULT_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(1, permsList.size()); + ASSERT_EQ(DYNAMIC_OPER, permsList[0].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + +/** + * @tc.name: GetSelfPermissionsState012 + * @tc.desc: all location permissions with api8 + * @tc.type: FUNC + * @tc.require: issueI5NOQI + */ +HWTEST_F(AccessTokenKitTest, GetSelfPermissionsState012, TestSize.Level1) +{ + std::vector permmissionDefs; + permmissionDefs.emplace_back(g_locationTestDefVague); + permmissionDefs.emplace_back(g_locationTestDefAccurate); + + std::vector permissionStateFulls; + permissionStateFulls.emplace_back(g_locationTestStateVague10); // {-1,0} + permissionStateFulls.emplace_back(g_locationTestStateAccurate10); // {-1,0} + + AllocHapToken(permmissionDefs, permissionStateFulls, DEFAULT_API_VERSION); + + AccessTokenID tokenID = GetAccessTokenID(TEST_USER_ID, "accesstoken_location_test", 0); + ASSERT_NE(0, tokenID); + ASSERT_EQ(0, SetSelfTokenID(tokenID)); + + PermissionListState permVague = { + .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", + .state = -1, + }; + PermissionListState permAccurate = { + .permissionName = "ohos.permission.LOCATION", + .state = -1, + }; + + std::vector permsList; + permsList.emplace_back(permVague); + permsList.emplace_back(permAccurate); + + PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList); + ASSERT_EQ(DYNAMIC_OPER, ret); + ASSERT_EQ(2, permsList.size()); + ASSERT_EQ(INVALID_OPER, permsList[0].state); + ASSERT_EQ(DYNAMIC_OPER, permsList[1].state); + + AccessTokenKit::DeleteToken(tokenID); + SetSelfTokenID(selfTokenId_); +} + /** * @tc.name: GetTokenTypeFlag003 * @tc.desc: Get token type with hap tokenID. @@ -2416,6 +3061,67 @@ HWTEST_F(AccessTokenKitTest, GetTokenTypeFlag003, TestSize.Level1) ASSERT_EQ(RET_SUCCESS, res); } +/** + * @tc.name: DumpTokenInfo001 + * @tc.desc: Get dump token information with invalid tokenID + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo001, TestSize.Level1) +{ + std::string info; + AccessTokenKit::DumpTokenInfo(123, info); + ASSERT_EQ("invalid tokenId", info); +} + +/** + * @tc.name: DumpTokenInfo002 + * @tc.desc: Get dump token information + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo002, TestSize.Level1) +{ + std::string info; + AccessTokenKit::DumpTokenInfo(0, info); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DumpTokenInfo003 + * @tc.desc: Get dump token information + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DumpTokenInfo003, TestSize.Level1) +{ + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + std::string info; + AccessTokenKit::DumpTokenInfo(tokenID, info); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DeleteRemoteToken001 + * @tc.desc: DeleteRemoteToken with invalid parameters. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(AccessTokenKitTest, DeleteRemoteToken001, TestSize.Level1) +{ + std::string deviceId = "device"; + AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, + g_infoManagerTestInfoParms.instIndex); + int res = AccessTokenKit::DeleteRemoteToken("", tokenID); + ASSERT_EQ(RET_FAILED, res); + + res = AccessTokenKit::DeleteRemoteToken(deviceId, tokenID); + ASSERT_EQ(RET_FAILED, res); +} + class CbCustomizeTest : public PermStateChangeCallbackCustomize { public: explicit CbCustomizeTest(const PermStateChangeScope &scopeInfo) @@ -2442,7 +3148,7 @@ public: * @tc.name: RegisterPermStateChangeCallback001 * @tc.desc: RegisterPermStateChangeCallback permList * @tc.type: FUNC - * @tc.require:AR000GK6TD + * @tc.require: issueI5NT1X */ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback001, TestSize.Level1) { @@ -2456,10 +3162,10 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback001, TestSize.Level1 static PermissionStateFull infoManagerTestStateA = { .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_DENIED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_DENIED}, + .grantFlags = {1} }; static HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_NORMAL, @@ -2521,7 +3227,7 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback001, TestSize.Level1 * @tc.name: RegisterPermStateChangeCallback002 * @tc.desc: RegisterPermStateChangeCallback permList * @tc.type: FUNC - * @tc.require:AR000GK6TD + * @tc.require: issueI5NT1X */ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback002, TestSize.Level1) { @@ -2535,17 +3241,17 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback002, TestSize.Level1 static PermissionStateFull infoManagerTestStateA = { .permissionName = "ohos.permission.GET_BUNDLE_INFO", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_GRANTED}, + .grantFlags = {1} }; static PermissionStateFull infoManagerTestStateB = { .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_GRANTED}, + .grantFlags = {1} }; static HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_SYSTEM_BASIC, @@ -2578,7 +3284,7 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback002, TestSize.Level1 * @tc.name: RegisterPermStateChangeCallback003 * @tc.desc: RegisterPermStateChangeCallback permList * @tc.type: FUNC - * @tc.require:AR000GK6TD + * @tc.require: issueI5NT1X */ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback003, TestSize.Level1) { @@ -2592,17 +3298,17 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback003, TestSize.Level1 static PermissionStateFull infoManagerTestStateA = { .permissionName = "ohos.permission.GET_BUNDLE_INFO", - .grantFlags = {1}, - .grantStatus = {PERMISSION_DENIED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_DENIED}, + .grantFlags = {1} }; static PermissionStateFull infoManagerTestStateB = { .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_DENIED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_DENIED}, + .grantFlags = {1} }; static HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_SYSTEM_CORE, @@ -2644,7 +3350,7 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback003, TestSize.Level1 * @tc.name: RegisterPermStateChangeCallback004 * @tc.desc: RegisterPermStateChangeCallback permList * @tc.type: FUNC - * @tc.require:AR000GK6TD + * @tc.require: issueI5NT1X */ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback004, TestSize.Level1) { @@ -2658,17 +3364,17 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback004, TestSize.Level1 static PermissionStateFull infoManagerTestStateA = { .permissionName = "ohos.permission.GET_BUNDLE_INFO", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_GRANTED}, + .grantFlags = {1}, }; static PermissionStateFull infoManagerTestStateB = { .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_GRANTED}, + .grantFlags = {1} }; static HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_NORMAL, @@ -2710,23 +3416,23 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback004, TestSize.Level1 * @tc.name: RegisterPermStateChangeCallback005 * @tc.desc: RegisterPermStateChangeCallback permList * @tc.type: FUNC - * @tc.require:AR000GK6TD + * @tc.require: issueI5NT1X */ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback005, TestSize.Level1) { static PermissionStateFull infoManagerTestStateA = { .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_DENIED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_DENIED}, + .grantFlags = {1} }; static PermissionStateFull infoManagerTestStateB = { .permissionName = "ohos.permission.GET_BUNDLE_INFO", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, .isGeneral = true, - .resDeviceID = {"local"} + .resDeviceID = {"local"}, + .grantStatus = {PERMISSION_GRANTED}, + .grantFlags = {1} }; static HapPolicyParams infoManagerTestPolicyPrams = { .apl = APL_NORMAL, @@ -2769,3 +3475,6 @@ HWTEST_F(AccessTokenKitTest, RegisterPermStateChangeCallback005, TestSize.Level1 res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); ASSERT_EQ(RET_SUCCESS, res); } +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h index 2328ec1473138fd67540c762a38d1baba3d07240..46b4fe8c35e0352004df152adead70cb2e788167 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h +++ b/interfaces/innerkits/accesstoken/test/unittest/src/accesstoken_kit_test.h @@ -18,6 +18,10 @@ #include +#include "access_token.h" +#include "permission_def.h" +#include "permission_state_full.h" + namespace OHOS { namespace Security { namespace AccessToken { @@ -48,6 +52,8 @@ public: void TearDown(); unsigned int GetAccessTokenID(int userID, std::string bundleName, int instIndex); + void AllocHapToken(std::vector& permmissionDefs, + std::vector& permissionStateFulls, int32_t apiVersion); void DeleteTestToken() const; void AllocTestToken() const; uint64_t selfTokenId_; diff --git a/interfaces/innerkits/nativetoken/include/nativetoken.h b/interfaces/innerkits/nativetoken/include/nativetoken.h index 7c3c9f9be0143fdc850f6ec2d85c05aecf08ef5c..4506309b4afb2ca1a21995380107ca38e351496b 100644 --- a/interfaces/innerkits/nativetoken/include/nativetoken.h +++ b/interfaces/innerkits/nativetoken/include/nativetoken.h @@ -26,6 +26,7 @@ extern "C" { #define TOKEN_ID_CFG_FILE_PATH "/data/service/el0/access_token/nativetoken.json" #define TOKEN_ID_CFG_DIR_PATH "/data/service/el0/access_token" #define TOKEN_NATIVE_TYPE 1 +#define TOKEN_SHELL_TYPE 2 #define DEFAULT_AT_VERSION 1 #define TRANSFER_KEY_WORDS "NativeTokenInfo" #define MAX_JSON_FILE_LEN 102400 @@ -50,6 +51,7 @@ extern "C" { #define APL_KEY_NAME "APL" #define VERSION_KEY_NAME "version" #define PROCESS_KEY_NAME "processName" +#define HDC_PROCESS_NAME "hdcd" #define SYSTEM_CORE 3 #define SYSTEM_BASIC 2 diff --git a/interfaces/innerkits/nativetoken/src/nativetoken.c b/interfaces/innerkits/nativetoken/src/nativetoken.c index d9c08e8dbc80e3eaf371cc46fb00a27f47e72998..3136a16e28403d3664a1e9c1b8450ed6dc801974 100644 --- a/interfaces/innerkits/nativetoken/src/nativetoken.c +++ b/interfaces/innerkits/nativetoken/src/nativetoken.c @@ -277,7 +277,7 @@ static int32_t IsTokenUniqueIdExist(uint32_t tokenUniqueId) return 0; } -static NativeAtId CreateNativeTokenId(void) +static NativeAtId CreateNativeTokenId(const char *processName) { uint32_t rand; NativeAtId tokenId; @@ -302,8 +302,14 @@ static NativeAtId CreateNativeTokenId(void) innerId->reserved = 0; innerId->tokenUniqueId = rand & (TOKEN_RANDOM_MASK); - innerId->type = TOKEN_NATIVE_TYPE; innerId->version = 1; + + if (strcmp(processName, HDC_PROCESS_NAME) == 0) { + innerId->type = TOKEN_SHELL_TYPE; + } else { + innerId->type = TOKEN_NATIVE_TYPE; + } + return tokenId; } @@ -328,7 +334,7 @@ static int32_t GetAplLevel(const char *aplStr) static void WriteToFile(const cJSON *root) { size_t strLen; - size_t writtenLen; + ssize_t writtenLen; char *jsonStr = NULL; jsonStr = cJSON_PrintUnformatted(root); @@ -347,7 +353,7 @@ static void WriteToFile(const cJSON *root) strLen = strlen(jsonStr); writtenLen = write(fd, (void *)jsonStr, (size_t)strLen); close(fd); - if (writtenLen != strLen) { + if (writtenLen < 0 || (size_t)writtenLen != strLen) { AT_LOG_ERROR("[ATLIB-%s]:write failed, writtenLen is %zu.", __func__, writtenLen); break; } @@ -465,7 +471,7 @@ static uint32_t AddNewTokenToListAndFile(const NativeTokenInfoParams *tokenInfo, NativeTokenList *tokenNode; NativeAtId id; - id = CreateNativeTokenId(); + id = CreateNativeTokenId(tokenInfo->processName); if (id == INVALID_TOKEN_ID) { return ATRET_FAILED; } diff --git a/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c b/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c index 25062d1b7715470920cb20b7fc44610507b696b8..2f7247250eaf34cf5e2a4b8651d6dc48fd260fa2 100644 --- a/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c +++ b/interfaces/innerkits/nativetoken/src/nativetoken_json_oper.c @@ -52,7 +52,7 @@ uint32_t GetTokenIdFromJson(cJSON *cjsonItem, NativeTokenList *tokenNode) } AtInnerInfo *atIdInfo = (AtInnerInfo *)&(tokenIdJson->valueint); - if (atIdInfo->type != TOKEN_NATIVE_TYPE) { + if (atIdInfo->type != TOKEN_NATIVE_TYPE && atIdInfo->type != TOKEN_SHELL_TYPE) { AT_LOG_ERROR("[ATLIB-%s]:tokenId type is invalid.", __func__); return ATRET_FAILED; } diff --git a/interfaces/innerkits/nativetoken/test/BUILD.gn b/interfaces/innerkits/nativetoken/test/BUILD.gn index ca884c8a06ef4bab390ee2d256e34d484f1c7dd3..8fc0ab217bd81405f9ac8801c93dd71f591ccb93 100644 --- a/interfaces/innerkits/nativetoken/test/BUILD.gn +++ b/interfaces/innerkits/nativetoken/test/BUILD.gn @@ -26,6 +26,8 @@ ohos_unittest("libnativetoken_test") { sources = [ "unittest/src/nativetoken_kit_test.cpp" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + deps = [ "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", "//third_party/bounds_checking_function:libsec_static", diff --git a/interfaces/innerkits/privacy/BUILD.gn b/interfaces/innerkits/privacy/BUILD.gn index 42ec2da9f8f3cb85ac980618469d97a218a9ab23..a01776a30797e955149754e496e0d88e3c853ce3 100644 --- a/interfaces/innerkits/privacy/BUILD.gn +++ b/interfaces/innerkits/privacy/BUILD.gn @@ -52,6 +52,8 @@ if (is_standard_system) { "//base/security/access_token/frameworks/privacy:privacy_communication_adapter_cxx", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", diff --git a/interfaces/innerkits/privacy/include/privacy_kit.h b/interfaces/innerkits/privacy/include/privacy_kit.h index 1279757e7eb8dca9a98e26421347d2a6148fb784..a06fa1f8c85e10e99c1105a289bcec7624e9e759 100644 --- a/interfaces/innerkits/privacy/include/privacy_kit.h +++ b/interfaces/innerkits/privacy/include/privacy_kit.h @@ -37,7 +37,7 @@ public: static int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); static int32_t GetPermissionUsedRecords( const PermissionUsedRequest& request, const sptr& callback); - static std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName); + static std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName); static int32_t RegisterPermActiveStatusCallback(const std::shared_ptr& callback); static int32_t UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback); }; diff --git a/interfaces/innerkits/privacy/src/privacy_kit.cpp b/interfaces/innerkits/privacy/src/privacy_kit.cpp index 2e91a684dea85272c6f9471c79359c86366d9949..b6349f0b74854d561f40e57da995ad0dd769fce5 100644 --- a/interfaces/innerkits/privacy/src/privacy_kit.cpp +++ b/interfaces/innerkits/privacy/src/privacy_kit.cpp @@ -61,33 +61,29 @@ int32_t PrivacyKit::RemovePermissionUsedRecords(AccessTokenID tokenID, const std int32_t PrivacyKit::GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); return PrivacyManagerClient::GetInstance().GetPermissionUsedRecords(request, result); } int32_t PrivacyKit::GetPermissionUsedRecords( const PermissionUsedRequest& request, const sptr& callback) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); return PrivacyManagerClient::GetInstance().GetPermissionUsedRecords(request, callback); } -std::string PrivacyKit::DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) +std::string PrivacyKit::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, bundleName=%{public}s, permissionName=%{public}s", - bundleName.c_str(), permissionName.c_str()); - return PrivacyManagerClient::GetInstance().DumpRecordInfo(bundleName, permissionName); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID=%{public}d, permissionName=%{public}s", + tokenID, permissionName.c_str()); + return PrivacyManagerClient::GetInstance().DumpRecordInfo(tokenID, permissionName); } int32_t PrivacyKit::RegisterPermActiveStatusCallback(const std::shared_ptr& callback) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); return PrivacyManagerClient::GetInstance().RegisterPermActiveStatusCallback(callback); } int32_t PrivacyKit::UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); return PrivacyManagerClient::GetInstance().UnRegisterPermActiveStatusCallback(callback); } } // namespace AccessToken diff --git a/interfaces/innerkits/privacy/src/privacy_manager_client.cpp b/interfaces/innerkits/privacy/src/privacy_manager_client.cpp index 769dc785ad86720b8c9e3551490b8b27fae2cbc4..12ac9e296752de45807a434ade965eee3ee7ba92 100644 --- a/interfaces/innerkits/privacy/src/privacy_manager_client.cpp +++ b/interfaces/innerkits/privacy/src/privacy_manager_client.cpp @@ -133,7 +133,7 @@ int32_t PrivacyManagerClient::GetPermissionUsedRecords(const PermissionUsedReque return proxy->GetPermissionUsedRecords(requestParcel, callback); } -std::string PrivacyManagerClient::DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) +std::string PrivacyManagerClient::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) { auto proxy = GetProxy(); if (proxy == nullptr) { @@ -141,7 +141,7 @@ std::string PrivacyManagerClient::DumpRecordInfo(const std::string& bundleName, return ""; } - return proxy->DumpRecordInfo(bundleName, permissionName); + return proxy->DumpRecordInfo(tokenID, permissionName); } int32_t PrivacyManagerClient::CreateActiveStatusChangeCbk( diff --git a/interfaces/innerkits/privacy/src/privacy_manager_client.h b/interfaces/innerkits/privacy/src/privacy_manager_client.h index ebae78818372656a08426f1daa67942634206fca..ee288ad69046c9f73dca259255ab43a13e0366b2 100644 --- a/interfaces/innerkits/privacy/src/privacy_manager_client.h +++ b/interfaces/innerkits/privacy/src/privacy_manager_client.h @@ -43,7 +43,7 @@ public: int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); int32_t GetPermissionUsedRecords( const PermissionUsedRequest& request, const sptr& callback); - std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName); + std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName); int32_t RegisterPermActiveStatusCallback(const std::shared_ptr& callback); int32_t UnRegisterPermActiveStatusCallback(const std::shared_ptr& callback); int32_t CreateActiveStatusChangeCbk( diff --git a/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp b/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp index c8f7c149e6b6d0ee3fd87ade716aa466ca8ecdd9..0014a3c02e8daa7e24f28dc6eb9c0fa2b28b52a2 100644 --- a/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp +++ b/interfaces/innerkits/privacy/src/privacy_manager_proxy.cpp @@ -41,7 +41,7 @@ int32_t PrivacyManagerProxy::AddPermissionUsedRecord(AccessTokenID tokenID, cons MessageParcel data; data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(tokenID)"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); return ERROR; } if (!data.WriteString(permissionName)) { @@ -72,7 +72,7 @@ int32_t PrivacyManagerProxy::StartUsingPermission(AccessTokenID tokenID, const s MessageParcel data; data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(tokenID)"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); return ERROR; } if (!data.WriteString(permissionName)) { @@ -95,7 +95,7 @@ int32_t PrivacyManagerProxy::StopUsingPermission(AccessTokenID tokenID, const st MessageParcel data; data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(tokenID)"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); return ERROR; } if (!data.WriteString(permissionName)) { @@ -118,7 +118,7 @@ int32_t PrivacyManagerProxy::RemovePermissionUsedRecords(AccessTokenID tokenID, MessageParcel data; data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(tokenID)"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); return ERROR; } if (!data.WriteString(deviceID)) { @@ -189,17 +189,17 @@ int32_t PrivacyManagerProxy::GetPermissionUsedRecords(const PermissionUsedReques return ret; } -std::string PrivacyManagerProxy::DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) +std::string PrivacyManagerProxy::DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) { MessageParcel data; MessageParcel reply; data.WriteInterfaceToken(IPrivacyManager::GetDescriptor()); - if (!data.WriteString(bundleName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(bundleName)"); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteUint32(%{public}d)", tokenID); return ""; } if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(permissionName)"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to WriteString(%{public}s)", permissionName.c_str()); return ""; } int32_t requestResult = SendRequest(IPrivacyManager::InterfaceCode::DUMP_RECORD_INFO, data, reply); diff --git a/interfaces/innerkits/privacy/src/privacy_manager_proxy.h b/interfaces/innerkits/privacy/src/privacy_manager_proxy.h index 50ca074da6201c11519043cdd3d28c1a9a32200f..5ea5aaa615a6399bc22b7549e1c9f195924a0224 100644 --- a/interfaces/innerkits/privacy/src/privacy_manager_proxy.h +++ b/interfaces/innerkits/privacy/src/privacy_manager_proxy.h @@ -38,7 +38,7 @@ public: const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) override; int32_t GetPermissionUsedRecords(const PermissionUsedRequestParcel& request, const sptr& callback) override; - std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) override; + std::string DumpRecordInfo(AccessTokenID tokenID, const std::string& permissionName) override; int32_t RegisterPermActiveStatusCallback( std::vector& permList, const sptr& callback) override; int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) override; diff --git a/interfaces/innerkits/privacy/test/BUILD.gn b/interfaces/innerkits/privacy/test/BUILD.gn index e5c3925710cdce6cddcbdfd9d57d0a7cb89264d0..2c1fed1ba4c29ba6b866aec367f6334fedaf7939 100644 --- a/interfaces/innerkits/privacy/test/BUILD.gn +++ b/interfaces/innerkits/privacy/test/BUILD.gn @@ -32,6 +32,8 @@ ohos_unittest("libprivacy_sdk_test") { cflags_cc = [ "-DHILOG_ENABLE" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", @@ -43,7 +45,6 @@ ohos_unittest("libprivacy_sdk_test") { "c_utils:utils", "init:libbegetutil", "ipc:ipc_core", - "samgr:samgr_proxy", ] } diff --git a/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp b/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp index 4f7ed70a661cbeb6ffc4395b4df958cdcb2716b0..d31e89533ce2477ba90b6ceaaddb9a72d5fd1579 100644 --- a/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp +++ b/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp @@ -51,6 +51,27 @@ static HapInfoParams g_InfoParmsB = { .appIDDesc = "privacy_test.bundleB" }; +static PermissionStateFull g_infoManagerTestStateA = { + .permissionName = "ohos.permission.CAMERA", + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; + +static PermissionStateFull g_infoManagerTestStateB = { + .permissionName = "ohos.permission.MICROPHONE", + .grantFlags = {1}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .isGeneral = true, + .resDeviceID = {"local"} +}; +static HapPolicyParams g_PolicyPramsE = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {g_infoManagerTestStateA, g_infoManagerTestStateB} +}; static HapInfoParams g_InfoParmsE = { .userID = 1, .bundleName = "ohos.privacy_test.bundleE", @@ -61,9 +82,30 @@ static HapInfoParams g_InfoParmsE = { static AccessTokenID g_selfTokenId = 0; static AccessTokenID g_TokenId_A = 0; static AccessTokenID g_TokenId_B = 0; +static AccessTokenID g_TokenId_E = 0; + + +static void DeleteTestToken() +{ + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, + g_InfoParmsA.bundleName, + g_InfoParmsA.instIndex); + AccessTokenKit::DeleteToken(tokenId); + + tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsB.userID, + g_InfoParmsB.bundleName, + g_InfoParmsB.instIndex); + AccessTokenKit::DeleteToken(tokenId); + + tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, + g_InfoParmsE.bundleName, + g_InfoParmsE.instIndex); + AccessTokenKit::DeleteToken(tokenId); +} void PrivacyKitTest::SetUpTestCase() { + DeleteTestToken(); g_selfTokenId = GetSelfTokenID(); } @@ -73,9 +115,9 @@ void PrivacyKitTest::TearDownTestCase() void PrivacyKitTest::SetUp() { - AccessTokenID tokenId; AccessTokenKit::AllocHapToken(g_InfoParmsA, g_PolicyPramsA); AccessTokenKit::AllocHapToken(g_InfoParmsB, g_PolicyPramsB); + AccessTokenKit::AllocHapToken(g_InfoParmsE, g_PolicyPramsE); g_TokenId_A = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, g_InfoParmsA.bundleName, @@ -83,32 +125,18 @@ void PrivacyKitTest::SetUp() g_TokenId_B = AccessTokenKit::GetHapTokenID(g_InfoParmsB.userID, g_InfoParmsB.bundleName, g_InfoParmsB.instIndex); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, - g_InfoParmsE.bundleName, - g_InfoParmsE.instIndex); - AccessTokenKit::DeleteToken(tokenId); + g_TokenId_E = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, + g_InfoParmsE.bundleName, + g_InfoParmsE.instIndex); - tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); // 100 is userID + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); // 100 is userID SetSelfTokenID(tokenId); } void PrivacyKitTest::TearDown() { SetSelfTokenID(g_selfTokenId); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsA.userID, - g_InfoParmsA.bundleName, - g_InfoParmsA.instIndex); - AccessTokenKit::DeleteToken(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsB.userID, - g_InfoParmsB.bundleName, - g_InfoParmsB.instIndex); - AccessTokenKit::DeleteToken(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParmsE.userID, - g_InfoParmsE.bundleName, - g_InfoParmsE.instIndex); - AccessTokenKit::DeleteToken(tokenId); + DeleteTestToken(); } std::string PrivacyKitTest::GetLocalDeviceUdid() @@ -150,6 +178,45 @@ void PrivacyKitTest::CheckPermissionUsedResult(const PermissionUsedRequest& requ ASSERT_EQ(totalFailCount, failCount); } +static void SetTokenID(std::vector& g_InfoParms_List, + std::vector& g_TokenId_List, int32_t number) +{ + SetSelfTokenID(g_selfTokenId); + for (int32_t i = 0; i < number; i++) { + HapInfoParams g_InfoParmsTmp = { + .userID = i, + .bundleName = "ohos.privacy_test.bundle" + std::to_string(i), + .instIndex = i, + .appIDDesc = "privacy_test.bundle" + std::to_string(i) + }; + g_InfoParms_List.push_back(g_InfoParmsTmp); + HapPolicyParams g_PolicyPramsTmp = { + .apl = APL_NORMAL, + .domain = "test.domain." + std::to_string(i) + }; + AccessTokenKit::AllocHapToken(g_InfoParmsTmp, g_PolicyPramsTmp); + AccessTokenID g_TokenId_Tmp = AccessTokenKit::GetHapTokenID(g_InfoParmsTmp.userID, + g_InfoParmsTmp.bundleName, + g_InfoParmsTmp.instIndex); + g_TokenId_List.push_back(g_TokenId_Tmp); + } + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); + SetSelfTokenID(tokenId); +} + +static void DeleteTokenID(std::vector& g_InfoParms_List) +{ + SetSelfTokenID(g_selfTokenId); + for (size_t i = 0; i < g_InfoParms_List.size(); i++) { + AccessTokenID g_TokenId_Tmp = AccessTokenKit::GetHapTokenID(g_InfoParms_List[i].userID, + g_InfoParms_List[i].bundleName, + g_InfoParms_List[i].instIndex); + AccessTokenKit::DeleteToken(g_TokenId_Tmp); + } + AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.permissionmanager", 0); + SetSelfTokenID(tokenId); +} + /** * @tc.name: AddPermissionUsedRecord001 * @tc.desc: cannot AddPermissionUsedRecord with illegal tokenId and permission. @@ -231,7 +298,7 @@ HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord003, TestSize.Level1) delete[] dcaps; delete[] acls; - ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord( + ASSERT_EQ(RET_ERROR, PrivacyKit::AddPermissionUsedRecord( tokenId, "ohos.permission.READ_CONTACTS", 1, 0)); PermissionUsedRequest request; @@ -333,6 +400,51 @@ HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord006, TestSize.Level1) CheckPermissionUsedResult(request, result, 1, 5, 0); } +/** + * @tc.name: AddPermissionUsedRecord007 + * @tc.desc: AddPermissionUsedRecord user_grant permission. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord007, TestSize.Level1) +{ + std::vector g_InfoParms_List; + std::vector g_TokenId_List; + SetTokenID(g_InfoParms_List, g_TokenId_List, 100); + std::vector addPermissionList = { + "ohos.permission.ANSWER_CALL", + "ohos.permission.READ_CALENDAR", + }; + for (int32_t i = 0; i < 200; i++) { + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_List[i % 100], + addPermissionList[i % 2], 1, 0)); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_List[i % 100], GetLocalDeviceUdid(), + g_InfoParms_List[i % 100].bundleName, permissionList, request); + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + } + sleep(70); + for (int32_t i = 0; i < 100; i++) { + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_List[i], GetLocalDeviceUdid(), + g_InfoParms_List[i].bundleName, permissionList, request); + request.flag = FLAG_PERMISSION_USAGE_DETAIL; + + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords[0].accessRecords.size()); + CheckPermissionUsedResult(request, result, 1, 2, 0); + } + DeleteTokenID(g_InfoParms_List); +} + /** * @tc.name: RemovePermissionUsedRecords001 * @tc.desc: cannot RemovePermissionUsedRecords with illegal tokenId and deviceID. @@ -434,28 +546,11 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords002, TestSize.Level1) request.bundleName = g_InfoParmsA.bundleName; CheckPermissionUsedResult(request, result, 3, 3, 0); - // query by deviceId and bundle Name - BuildQueryRequest(0, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); - ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); - ASSERT_EQ(1, result.bundleRecords.size()); - request.tokenId = g_TokenId_A; - CheckPermissionUsedResult(request, result, 3, 3, 0); - // query by unmatched tokenId, deviceId and bundle Name BuildQueryRequest(123, GetLocalDeviceUdid(), g_InfoParmsA.bundleName, permissionList, request); ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); ASSERT_EQ(0, result.bundleRecords.size()); - // query by unmatched tokenId, deviceId and bundle Name - BuildQueryRequest(g_TokenId_A, "local device", g_InfoParmsA.bundleName, permissionList, request); - ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); - ASSERT_EQ(0, result.bundleRecords.size()); - - // query by unmatched tokenId, deviceId and bundle Name - BuildQueryRequest(g_TokenId_A, GetLocalDeviceUdid(), "bundleA", permissionList, request); - ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); - ASSERT_EQ(0, result.bundleRecords.size()); - // query by invalid permission Name permissionList.clear(); permissionList.emplace_back("invalid permission"); @@ -555,6 +650,63 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync002, TestSize.Level1) ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, callback)); } +/** + * @tc.name: DumpRecordInfo001 + * @tc.desc: cannot DumpRecordInfo with invalid params. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo001, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + + // invalid tokenId + std::string info = PrivacyKit::DumpRecordInfo(123, permission); + ASSERT_EQ(true, info.empty()); + + // invalid permission + info = PrivacyKit::DumpRecordInfo(g_TokenId_A, "invalid permission"); + ASSERT_EQ(true, info.empty()); +} + +/** + * @tc.name: DumpRecordInfo002 + * @tc.desc: cannot DumpRecordInfo with no record. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo002, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(g_TokenId_A, permission, 1, 0)); + + std::string info = PrivacyKit::DumpRecordInfo(g_TokenId_A, ""); + ASSERT_EQ(false, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, permission); + ASSERT_EQ(false, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, ""); + ASSERT_EQ(false, info.empty()); +} + +/** + * @tc.name: DumpRecordInfo003 + * @tc.desc: cannot DumpRecordInfo with record. + * @tc.type: FUNC + * @tc.require:Issue Number + */ +HWTEST_F(PrivacyKitTest, DumpRecordInfo003, TestSize.Level1) +{ + std::string permission = "ohos.permission.CAMERA"; + + std::string info = PrivacyKit::DumpRecordInfo(g_TokenId_A, ""); + ASSERT_EQ(true, info.empty()); + + info = PrivacyKit::DumpRecordInfo(0, ""); + ASSERT_EQ(true, info.empty()); +} + class CbCustomizeTest1 : public PermActiveStatusCustomizedCbk { public: explicit CbCustomizeTest1(const std::vector &permList) @@ -570,10 +722,10 @@ public: { type_ = result.type; GTEST_LOG_(INFO) << "CbCustomizeTest1 ActiveChangeResponse"; - GTEST_LOG_(INFO) << "tokenid " << result.tokenID; - GTEST_LOG_(INFO) << "permissionName " << result.permissionName; - GTEST_LOG_(INFO) << "deviceId " << result.deviceId; - GTEST_LOG_(INFO) << "type " << result.type; + GTEST_LOG_(INFO) << "CbCustomizeTest1 tokenid " << result.tokenID; + GTEST_LOG_(INFO) << "CbCustomizeTest1 permissionName " << result.permissionName; + GTEST_LOG_(INFO) << "CbCustomizeTest1 deviceId " << result.deviceId; + GTEST_LOG_(INFO) << "CbCustomizeTest1 type " << result.type; } ActiveChangeType type_ = PERM_INACTIVE; @@ -594,10 +746,10 @@ public: { type_ = result.type; GTEST_LOG_(INFO) << "CbCustomizeTest2 ActiveChangeResponse"; - GTEST_LOG_(INFO) << "tokenid " << result.tokenID; - GTEST_LOG_(INFO) << "permissionName " << result.permissionName; - GTEST_LOG_(INFO) << "deviceId " << result.deviceId; - GTEST_LOG_(INFO) << "type " << result.type; + GTEST_LOG_(INFO) << "CbCustomizeTest2 tokenid " << result.tokenID; + GTEST_LOG_(INFO) << "CbCustomizeTest2 permissionName " << result.permissionName; + GTEST_LOG_(INFO) << "CbCustomizeTest2 deviceId " << result.deviceId; + GTEST_LOG_(INFO) << "CbCustomizeTest2 type " << result.type; } ActiveChangeType type_; @@ -607,7 +759,7 @@ public: * @tc.name: RegisterPermActiveStatusCallback001 * @tc.desc: RegisterPermActiveStatusCallback with valid permission. * @tc.type: FUNC - * @tc.require:Issue Number + * @tc.require: issueI5NT1X */ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback001, TestSize.Level1) { @@ -618,61 +770,36 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback001, TestSize.Level1) int32_t res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr); - static PermissionStateFull infoManagerTestStateA = { - .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, - .isGeneral = true, - .resDeviceID = {"local"} - }; - static HapPolicyParams infoManagerTestPolicyPrams = { - .apl = APL_NORMAL, - .domain = "test.domain", - .permList = {}, - .permStateList = {infoManagerTestStateA} - }; - - AccessTokenIDEx tokenIdEx = {0}; - AccessTokenID tokenID; - tokenIdEx = AccessTokenKit::AllocHapToken(g_InfoParmsE, infoManagerTestPolicyPrams); - - tokenID = tokenIdEx.tokenIdExStruct.tokenID; - ASSERT_NE(0, tokenID); - - ATokenTypeEnum ret = AccessTokenKit::GetTokenTypeFlag(tokenID); - ASSERT_EQ(ret, TOKEN_HAP); - - res = PrivacyKit::StartUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr->type_); - res = PrivacyKit::StopUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + ASSERT_EQ(RET_NO_ERROR, res); callbackPtr->type_ = PERM_INACTIVE; - res = PrivacyKit::StartUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); - res = PrivacyKit::StopUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); ASSERT_EQ(PERM_INACTIVE, callbackPtr->type_); - - res = AccessTokenKit::DeleteToken(tokenID); - ASSERT_EQ(RET_SUCCESS, res); } - /** * @tc.name: RegisterPermActiveStatusCallback002 * @tc.desc: RegisterPermActiveStatusCallback with valid permission. * @tc.type: FUNC - * @tc.require:Issue Number + * @tc.require: issueI5NT1X */ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback002, TestSize.Level1) @@ -681,60 +808,121 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback002, TestSize.Level1) auto callbackPtr1 = std::make_shared(permList1); callbackPtr1->type_ = PERM_INACTIVE; - std::vector permList2 = {"ohos.permission.GET_BUNDLE_INFO"}; + std::vector permList2 = {"ohos.permission.MICROPHONE"}; auto callbackPtr2 = std::make_shared(permList2); callbackPtr2->type_ = PERM_INACTIVE; int32_t res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr1); res = PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr2); - static PermissionStateFull infoManagerTestStateA = { - .permissionName = "ohos.permission.CAMERA", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, - .isGeneral = true, - .resDeviceID = {"local"} - }; - static PermissionStateFull infoManagerTestStateB = { - .permissionName = "ohos.permission.GET_BUNDLE_INFO", - .grantFlags = {1}, - .grantStatus = {PERMISSION_GRANTED}, - .isGeneral = true, - .resDeviceID = {"local"} - }; - static HapPolicyParams infoManagerTestPolicyPrams = { - .apl = APL_NORMAL, - .domain = "test.domain", - .permList = {}, - .permStateList = {infoManagerTestStateA, infoManagerTestStateB} - }; - - AccessTokenIDEx tokenIdEx = {0}; - AccessTokenID tokenID; - tokenIdEx = AccessTokenKit::AllocHapToken(g_InfoParmsE, infoManagerTestPolicyPrams); - - tokenID = tokenIdEx.tokenIdExStruct.tokenID; - ASSERT_NE(0, tokenID); - - res = PrivacyKit::StartUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr1->type_); ASSERT_EQ(PERM_INACTIVE, callbackPtr2->type_); - res = PrivacyKit::StopUsingPermission(tokenID, "ohos.permission.CAMERA"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.CAMERA"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_INACTIVE, callbackPtr1->type_); - res = PrivacyKit::StartUsingPermission(tokenID, "ohos.permission.GET_BUNDLE_INFO"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StartUsingPermission(g_TokenId_E, "ohos.permission.MICROPHONE"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_INACTIVE, callbackPtr1->type_); ASSERT_EQ(PERM_ACTIVE_IN_FOREGROUND, callbackPtr2->type_); - res = PrivacyKit::StopUsingPermission(tokenID, "ohos.permission.GET_BUNDLE_INFO"); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::StopUsingPermission(g_TokenId_E, "ohos.permission.MICROPHONE"); + ASSERT_EQ(RET_NO_ERROR, res); + + usleep(500000); // 500000us = 0.5s ASSERT_EQ(PERM_INACTIVE, callbackPtr2->type_); - res = AccessTokenKit::DeleteToken(tokenID); - ASSERT_EQ(RET_SUCCESS, res); + res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr1); + ASSERT_EQ(RET_NO_ERROR, res); + res = PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr2); + ASSERT_EQ(RET_NO_ERROR, res); +} + +/** + * @tc.name: StartUsingPermission001 + * @tc.desc: StartUsingPermission with invalid tokenId or permission. + * @tc.type: FUNC + * @tc.require: issueI5NT1X + */ +HWTEST_F(PrivacyKitTest, StartUsingPermission001, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.CAMERA"; + int32_t ret = PrivacyKit::StartUsingPermission(0, permissionName); + ASSERT_EQ(RET_ERROR, ret); + + ret = PrivacyKit::StartUsingPermission(0, "permissionName"); + ASSERT_EQ(RET_ERROR, ret); +} + +/** + * @tc.name: StartUsingPermission002 + * @tc.desc: StartUsingPermission is called twice with same permission. + * @tc.type: FUNC + * @tc.require: issueI5NT1X + */ +HWTEST_F(PrivacyKitTest, StartUsingPermission002, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.CAMERA"; + int32_t ret = PrivacyKit::StartUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(RET_NO_ERROR, ret); + + ret = PrivacyKit::StartUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(RET_ERROR, ret); + + ret = PrivacyKit::StopUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(RET_NO_ERROR, ret); +} + + +/** + * @tc.name: StopUsingPermission003 + * @tc.desc: Add record when StopUsingPermission is called. + * @tc.type: FUNC + * @tc.require: issueI5NT1X + */ +HWTEST_F(PrivacyKitTest, StartUsingPermission003, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.CAMERA"; + int32_t ret = PrivacyKit::StartUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(RET_NO_ERROR, ret); + + usleep(500000); // 500000us = 0.5s + ret = PrivacyKit::StopUsingPermission(g_TokenId_E, permissionName); + ASSERT_EQ(RET_NO_ERROR, ret); + + PermissionUsedRequest request; + PermissionUsedResult result; + std::vector permissionList; + BuildQueryRequest(g_TokenId_E, GetLocalDeviceUdid(), g_InfoParmsE.bundleName, permissionList, request); + ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); + ASSERT_EQ(1, result.bundleRecords.size()); + ASSERT_EQ(g_TokenId_E, result.bundleRecords[0].tokenId); + ASSERT_EQ(g_InfoParmsE.bundleName, result.bundleRecords[0].bundleName); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords.size()); + ASSERT_EQ(1, result.bundleRecords[0].permissionRecords[0].accessCount); +} + +/** + * @tc.name: StopUsingPermission001 + * @tc.desc: StopUsingPermission with invalid tokenId or permission. + * @tc.type: FUNC + * @tc.require: issueI5NT1X + */ +HWTEST_F(PrivacyKitTest, StopUsingPermission001, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.CAMERA"; + int32_t ret = PrivacyKit::StopUsingPermission(0, permissionName); + ASSERT_EQ(RET_ERROR, ret); + + ret = PrivacyKit::StopUsingPermission(0, "permissionName"); + ASSERT_EQ(RET_ERROR, ret); } \ No newline at end of file diff --git a/interfaces/innerkits/token_callback/BUILD.gn b/interfaces/innerkits/token_callback/BUILD.gn index aab55f80149633bb540343eb181530ed8d13a8b3..d7cee7b3257027b270b9b0475d4f1e4a84317e1e 100644 --- a/interfaces/innerkits/token_callback/BUILD.gn +++ b/interfaces/innerkits/token_callback/BUILD.gn @@ -27,6 +27,8 @@ if (is_standard_system) { public_configs = [ ":token_callback" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + include_dirs = [ "//commonlibrary/c_utils/base/include", "include", @@ -40,15 +42,12 @@ if (is_standard_system) { "src/token_callback_stub.cpp", ] - deps = [ - "//base/security/access_token/frameworks/common:accesstoken_common_cxx", - ] + deps = [] external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr:samgr_proxy", ] cflags_cc = [ diff --git a/interfaces/innerkits/token_callback/src/token_callback_stub.cpp b/interfaces/innerkits/token_callback/src/token_callback_stub.cpp index 1d70b043ee9b388d3d2b8e80c7f6f9cf6ca7c1e8..e51cd4c87201e505268343a76c98fd043f541973 100644 --- a/interfaces/innerkits/token_callback/src/token_callback_stub.cpp +++ b/interfaces/innerkits/token_callback/src/token_callback_stub.cpp @@ -29,6 +29,11 @@ static const int32_t LIST_SIZE_MAX = 200; static const int32_t FAILED = -1; } +static std::string to_utf8(std::u16string str16) +{ + return std::wstring_convert, char16_t> {}.to_bytes(str16); +} + int32_t TokenCallbackStub::OnRemoteRequest( uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) { @@ -43,18 +48,19 @@ int32_t TokenCallbackStub::OnRemoteRequest( if (msgCode == ITokenCallback::GRANT_RESULT_CALLBACK) { uint32_t permListSize = data.ReadUint32(); if (permListSize > LIST_SIZE_MAX) { - ACCESSTOKEN_LOG_ERROR(LABEL, "read permListSize fail"); + ACCESSTOKEN_LOG_ERROR(LABEL, "read permListSize fail %{public}u", permListSize); return FAILED; } std::vector permList; for (uint32_t i = 0; i < permListSize; i++) { - std::string perm = data.ReadString(); + std::u16string u16Perm = data.ReadString16(); + std::string perm = to_utf8(u16Perm); permList.emplace_back(perm); } uint32_t statusListSize = data.ReadUint32(); if (statusListSize != permListSize) { - ACCESSTOKEN_LOG_ERROR(LABEL, "read permListSize fail"); + ACCESSTOKEN_LOG_ERROR(LABEL, "read statusListSize fail %{public}u", statusListSize); return FAILED; } std::vector grantResults; diff --git a/interfaces/innerkits/token_callback/test/BUILD.gn b/interfaces/innerkits/token_callback/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e0bae90eaa81177c6f208581ada360fdf949bf28 --- /dev/null +++ b/interfaces/innerkits/token_callback/test/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +ohos_unittest("libtoken_callback_test") { + subsystem_name = "security" + part_name = "access_token" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//third_party/googletest/include", + "//base/security/access_token/interfaces/innerkits/token_callback/include", + ] + + sources = [ "unittest/src/token_callback_test.cpp" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + configs = [ "//base/security/access_token/config:coverage_flags" ] + + deps = [ "//base/security/access_token/interfaces/innerkits/token_callback:libtoken_callback_sdk" ] + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":libtoken_callback_test" ] +} diff --git a/interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.cpp b/interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a22b1a5bab032caeecddbd82300b3d2c03aa0f1 --- /dev/null +++ b/interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "token_callback_test.h" +#include "string_ex.h" +#include "token_callback_stub.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::AccessToken; + +const static int32_t RET_NO_ERROR = 0; + +void TokenCallbackTest::SetUpTestCase() +{ +} + +void TokenCallbackTest::TearDownTestCase() +{ +} + +void TokenCallbackTest::SetUp() +{ +} + +void TokenCallbackTest::TearDown() +{ +} + +class TestCallBack : public TokenCallbackStub { +public: + TestCallBack() = default; + virtual ~TestCallBack() = default; + + void GrantResultsCallback( + const std::vector &permissions, const std::vector &grantResults) + { + GTEST_LOG_(INFO) << "GrantResultsCallback, permissions.size:" << permissions.size() << + ", grantResults.size :" << grantResults.size(); + } +}; + +/** + * @tc.name: OnRemoteRequest001 + * @tc.desc: OnRemoteRequest empty. + * @tc.type: FUNC + * @tc.require: issueI5NU8U + */ +HWTEST_F(TokenCallbackTest, OnRemoteRequest001, TestSize.Level1) +{ + std::vector permissions; + std::vector grantResults; + uint32_t listSize = permissions.size(); + uint32_t resultSize = grantResults.size(); + + TestCallBack callback; + MessageParcel data; + ASSERT_EQ(true, data.WriteInterfaceToken(ITokenCallback::GetDescriptor())); + + ASSERT_EQ(true, data.WriteUint32(listSize)); + for (uint32_t i = 0; i < listSize; i++) { + ASSERT_EQ(true, data.WriteString16(Str8ToStr16(permissions[i]))); + } + + ASSERT_EQ(true, data.WriteUint32(resultSize)); + for (uint32_t i = 0; i < resultSize; i++) { + ASSERT_EQ(true, data.WriteInt32(grantResults[i])); + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + ASSERT_EQ(RET_NO_ERROR, + callback.OnRemoteRequest(static_cast(ITokenCallback::GRANT_RESULT_CALLBACK), data, reply, option)); +} + +/** + * @tc.name: OnRemoteRequest002 + * @tc.desc: OnRemoteRequest not empty. + * @tc.type: FUNC + * @tc.require: issueI5NU8U + */ +HWTEST_F(TokenCallbackTest, OnRemoteRequest002, TestSize.Level1) +{ + std::vector permissions; + std::vector grantResults; + permissions.emplace_back("ohos.permission.CAMERA"); + grantResults.emplace_back(0); + uint32_t listSize = permissions.size(); + uint32_t resultSize = grantResults.size(); + + TestCallBack callback; + MessageParcel data; + ASSERT_EQ(true, data.WriteInterfaceToken(ITokenCallback::GetDescriptor())); + + ASSERT_EQ(true, data.WriteUint32(listSize)); + for (uint32_t i = 0; i < listSize; i++) { + ASSERT_EQ(true, data.WriteString16(Str8ToStr16(permissions[i]))); + } + + ASSERT_EQ(true, data.WriteUint32(resultSize)); + for (uint32_t i = 0; i < resultSize; i++) { + ASSERT_EQ(true, data.WriteInt32(grantResults[i])); + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + ASSERT_EQ(RET_NO_ERROR, + callback.OnRemoteRequest(static_cast(ITokenCallback::GRANT_RESULT_CALLBACK), data, reply, option)); +} diff --git a/services/privacymanager/include/record/permission_visitor.h b/interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.h similarity index 55% rename from services/privacymanager/include/record/permission_visitor.h rename to interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.h index 212094c510bd6b2052ccd68f1bada4996d64fae7..60fca1191cf1c8c14fba5047e11e922f2afe6cbc 100644 --- a/services/privacymanager/include/record/permission_visitor.h +++ b/interfaces/innerkits/token_callback/test/unittest/src/token_callback_test.h @@ -13,30 +13,25 @@ * limitations under the License. */ -#ifndef PERMISSION_VISITOR_H -#define PERMISSION_VISITOR_H - -#include -#include "access_token.h" -#include "generic_values.h" +#ifndef PRIVACY_KIT_TEST_H +#define PRIVACY_KIT_TEST_H +#include +#include namespace OHOS { namespace Security { namespace AccessToken { -struct PermissionVisitor { - int32_t id = -1; - AccessTokenID tokenId = 0; - bool isRemoteDevice = false; - std::string deviceId; - int32_t userId; - std::string bundleName; +class TokenCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); - PermissionVisitor() = default; + void SetUp(); - static void TranslationIntoGenericValues(const PermissionVisitor& visitor, GenericValues& values); - static void TranslationIntoPermissionVisitor(const GenericValues& values, PermissionVisitor& visitor); + void TearDown(); }; } // namespace AccessToken } // namespace Security } // namespace OHOS -#endif // PERMISSION_VISITOR_H +#endif // PRIVACY_KIT_TEST_H diff --git a/interfaces/innerkits/token_setproc/test/BUILD.gn b/interfaces/innerkits/token_setproc/test/BUILD.gn index b6e11d2adb3e0c6c8d408b41e7f2908259da3981..9d8158678c7cde987217eeec802915f65763d513 100644 --- a/interfaces/innerkits/token_setproc/test/BUILD.gn +++ b/interfaces/innerkits/token_setproc/test/BUILD.gn @@ -24,6 +24,7 @@ ohos_unittest("libtoken_setproc_test") { sources = [ "unittest/src/tokensetproc_kit_test.cpp" ] cflags_cc = [ "-fexceptions" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] deps = [ "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", diff --git a/interfaces/innerkits/tokensync/BUILD.gn b/interfaces/innerkits/tokensync/BUILD.gn index 40ba7d399a347762ced8882233bc385723302ebc..295ce5ca5a76ca86caeced4dba8a8a1f69277f7a 100644 --- a/interfaces/innerkits/tokensync/BUILD.gn +++ b/interfaces/innerkits/tokensync/BUILD.gn @@ -60,6 +60,8 @@ if (is_standard_system) { "samgr:samgr_proxy", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] } } diff --git a/interfaces/innerkits/tokensync/test/BUILD.gn b/interfaces/innerkits/tokensync/test/BUILD.gn index 19728ed2c011b5aa6a36b7748b679364b719f132..cfa07caf657c753af7d17bf36c694210c80a8350 100644 --- a/interfaces/innerkits/tokensync/test/BUILD.gn +++ b/interfaces/innerkits/tokensync/test/BUILD.gn @@ -29,10 +29,9 @@ ohos_unittest("libtokensync_sdk_test") { cflags_cc = [ "-DHILOG_ENABLE" ] - deps = [ - #"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", - "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", - ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + + deps = [] external_deps = [ "c_utils:utils" ] } diff --git a/interfaces/kits/accesstoken/BUILD.gn b/interfaces/kits/accesstoken/BUILD.gn index 71bd9856de28d9c72e0fb57f9e2f46f7cdc1281c..566139e17c33d8ac3f88659f88602f4a20b6f7e9 100644 --- a/interfaces/kits/accesstoken/BUILD.gn +++ b/interfaces/kits/accesstoken/BUILD.gn @@ -18,6 +18,7 @@ ohos_shared_library("libabilityaccessctrl") { "//base/security/access_token/frameworks/common/include", "//base/security/access_token/interfaces/innerkits/accesstoken/include", "//base/security/access_token/interfaces/kits/accesstoken/napi/include", + "//base/security/access_token/interfaces/kits/common/include", "//foundation/arkui/napi/interfaces/inner_api", "//foundation/arkui/napi/interfaces/kits", ] @@ -26,13 +27,12 @@ ohos_shared_library("libabilityaccessctrl") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "//base/security/access_token/interfaces/kits/common:libnapi_common", "//foundation/arkui/napi:ace_napi", ] cflags_cc = [ "-DHILOG_ENABLE" ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] relative_install_dir = "module" subsystem_name = "security" diff --git a/interfaces/kits/accesstoken/napi/include/napi_atmanager.h b/interfaces/kits/accesstoken/napi/include/napi_atmanager.h index 167e816c95b74db111d3727f2a08908c293b7b12..0be35fe4c1051af96f993f9a9dbb23f32c9e1eea 100644 --- a/interfaces/kits/accesstoken/napi/include/napi_atmanager.h +++ b/interfaces/kits/accesstoken/napi/include/napi_atmanager.h @@ -19,23 +19,68 @@ #include #include #include +#include +#include "access_token.h" +#include "accesstoken_kit.h" +#include "napi_common.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "perm_state_change_callback_customize.h" namespace OHOS { namespace Security { namespace AccessToken { const int AT_PERM_OPERA_FAIL = -1; const int AT_PERM_OPERA_SUCC = 0; -const int VALUE_BUFFER_SIZE = 256; -const int ASYNC_CALL_BACK_VALUES_NUM = 2; const int VERIFY_OR_FLAG_INPUT_MAX_VALUES = 2; const int GRANT_OR_REVOKE_INPUT_MAX_VALUES = 4; +enum PermissionStateChangeType { + PERMISSION_REVOKED_OPER = 0, + PERMISSION_GRANTED_OPER = 1, +}; + static thread_local napi_ref atManagerRef_; const std::string ATMANAGER_CLASS_NAME = "atManager"; +class RegisterPermStateChangeScopePtr : public PermStateChangeCallbackCustomize { +public: + explicit RegisterPermStateChangeScopePtr(const PermStateChangeScope& subscribeInfo); + ~RegisterPermStateChangeScopePtr(); + void PermStateChangeCallback(PermStateChangeInfo& result) override; + void SetEnv(const napi_env& env); + void SetCallbackRef(const napi_ref& ref); +private: + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; +}; + +struct RegisterPermStateChangeWorker { + napi_env env = nullptr; + napi_ref ref = nullptr; + PermStateChangeInfo result; + RegisterPermStateChangeScopePtr* subscriber = nullptr; +}; + +struct PermStateChangeContext { + virtual ~PermStateChangeContext(); + napi_env env = nullptr; + napi_async_work work = nullptr; + napi_ref callbackRef = nullptr; + int32_t errCode = RET_FAILED; + std::string permStateChangeType; + PermStateChangeScope scopeInfo; + AccessTokenKit* accessTokenKit = nullptr; + std::shared_ptr subscriber = nullptr; +}; + +struct RegisterPermStateChangeInfo : public PermStateChangeContext {}; + +struct UnregisterPermStateChangeInfo : public PermStateChangeContext { + ~UnregisterPermStateChangeInfo(); +}; + struct AtManagerAsyncContext { napi_env env = nullptr; uint32_t tokenId = 0; @@ -75,6 +120,19 @@ private: static void GetPermissionFlagsExcute(napi_env env, void *data); static void GetPermissionFlagsComplete(napi_env env, napi_status status, void *data); static void SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName); + static bool ParseInputToRegister(const napi_env env, napi_callback_info cbInfo, + RegisterPermStateChangeInfo& registerPermStateChangeInfo); + static napi_value RegisterPermStateChangeCallback(napi_env env, napi_callback_info cbinfo); + static void RegisterPermStateChangeExecute(napi_env env, void* data); + static void RegisterPermStateChangeComplete(napi_env env, napi_status status, void* data); + static bool IsExistRegister(const RegisterPermStateChangeInfo* registerPermStateChangeInfo); + static bool ParseInputToUnregister(const napi_env env, napi_callback_info cbInfo, + UnregisterPermStateChangeInfo& unregisterPermStateChangeInfo); + static napi_value UnregisterPermStateChangeCallback(napi_env env, napi_callback_info cbinfo); + static void UnregisterPermStateChangeExecute(napi_env env, void* data); + static void UnregisterPermStateChangeCompleted(napi_env env, napi_status status, void* data); + static bool FindAndGetSubscriberInMap(UnregisterPermStateChangeInfo* unregisterPermStateChangeInfo); + static void DeleteRegisterInMap(AccessTokenKit* accessTokenKit, const PermStateChangeScope& scopeInfo); }; } // namespace AccessToken } // namespace Security diff --git a/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp b/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp index a74f44ccc758463b49c647b33e686631b6922ae8..b24861695d80208fa46657bd1c1bb75a9118c361 100644 --- a/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp +++ b/interfaces/kits/accesstoken/napi/src/napi_atmanager.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -27,12 +28,146 @@ namespace OHOS { namespace Security { namespace AccessToken { +std::mutex g_lockForPermStateChangeRegisters; +std::map> g_permStateChangeRegisters; namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenAbilityAccessCtrl" }; + +static bool ConvertPermStateChangeInfo(napi_env env, napi_value value, const PermStateChangeInfo& result) +{ + napi_value element; + NAPI_CALL_BASE(env, napi_create_int32(env, result.PermStateChangeType, &element), false); + NAPI_CALL_BASE(env, napi_set_named_property(env, value, "change", element), false); + element = nullptr; + NAPI_CALL_BASE(env, napi_create_int32(env, result.tokenID, &element), false); + NAPI_CALL_BASE(env, napi_set_named_property(env, value, "tokenID", element), false); + element = nullptr; + NAPI_CALL_BASE(env, napi_create_string_utf8(env, result.permissionName.c_str(), + NAPI_AUTO_LENGTH, &element), false); + NAPI_CALL_BASE(env, napi_set_named_property(env, value, "permissionName", element), false); + return true; +}; + +static bool CompareScopeInfo(const PermStateChangeScope& scopeInfo, + const std::vector& tokenIDs, const std::vector& permList) +{ + std::vector targetTokenIDs = scopeInfo.tokenIDs; + std::vector targetPermList = scopeInfo.permList; + if (targetTokenIDs.size() != tokenIDs.size() || targetPermList.size() != permList.size()) { + return false; + } + std::sort(targetTokenIDs.begin(), targetTokenIDs.end()); + std::sort(targetPermList.begin(), targetPermList.end()); + if (std::equal(targetTokenIDs.begin(), targetTokenIDs.end(), tokenIDs.begin()) && + std::equal(targetPermList.begin(), targetPermList.end(), permList.begin())) { + return true; + } + return false; +}; + +static void UvQueueWorkPermStateChanged(uv_work_t* work, int status) +{ + if (work == nullptr || work->data == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "work == nullptr || work->data == nullptr"); + return; + } + std::unique_ptr uvWorkPtr {work}; + RegisterPermStateChangeWorker* registerPermStateChangeData = + reinterpret_cast(work->data); + std::unique_ptr workPtr {registerPermStateChangeData}; + napi_value result[ARGS_ONE] = {nullptr}; + NAPI_CALL_RETURN_VOID(registerPermStateChangeData->env, + napi_create_array(registerPermStateChangeData->env, &result[PARAM0])); + if (!ConvertPermStateChangeInfo(registerPermStateChangeData->env, + result[PARAM0], registerPermStateChangeData->result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertPermStateChangeInfo failed"); + return; + } + + napi_value undefined = nullptr; + napi_value callback = nullptr; + napi_value resultout = nullptr; + NAPI_CALL_RETURN_VOID(registerPermStateChangeData->env, + napi_get_undefined(registerPermStateChangeData->env, &undefined)); + NAPI_CALL_RETURN_VOID(registerPermStateChangeData->env, + napi_get_reference_value(registerPermStateChangeData->env, registerPermStateChangeData->ref, &callback)); + NAPI_CALL_RETURN_VOID(registerPermStateChangeData->env, + napi_call_function(registerPermStateChangeData->env, + undefined, callback, ARGS_ONE, &result[PARAM0], &resultout)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "UvQueueWorkPermStateChanged end"); +}; } // namespace +RegisterPermStateChangeScopePtr::RegisterPermStateChangeScopePtr(const PermStateChangeScope& subscribeInfo) + : PermStateChangeCallbackCustomize(subscribeInfo) +{} + +RegisterPermStateChangeScopePtr::~RegisterPermStateChangeScopePtr() +{} + +void RegisterPermStateChangeScopePtr::PermStateChangeCallback(PermStateChangeInfo& result) +{ + uv_loop_s* loop = nullptr; + NAPI_CALL_RETURN_VOID(env_, napi_get_uv_event_loop(env_, &loop)); + if (loop == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "loop instance is nullptr"); + return; + } + uv_work_t* work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "insufficient memory for work!"); + return; + } + std::unique_ptr uvWorkPtr {work}; + RegisterPermStateChangeWorker* registerPermStateChangeWorker = + new (std::nothrow) RegisterPermStateChangeWorker(); + if (registerPermStateChangeWorker == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "insufficient memory for RegisterPermStateChangeWorker!"); + return; + } + std::unique_ptr workPtr {registerPermStateChangeWorker}; + registerPermStateChangeWorker->env = env_; + registerPermStateChangeWorker->ref = ref_; + registerPermStateChangeWorker->result = result; + ACCESSTOKEN_LOG_DEBUG(LABEL, + "result PermStateChangeType = %{public}d, tokenID = %{public}d, permissionName = %{public}s", + result.PermStateChangeType, result.tokenID, result.permissionName.c_str()); + registerPermStateChangeWorker->subscriber = this; + work->data = reinterpret_cast(registerPermStateChangeWorker); + NAPI_CALL_RETURN_VOID(env_, + uv_queue_work(loop, work, [](uv_work_t* work) {}, UvQueueWorkPermStateChanged)); + uvWorkPtr.release(); + workPtr.release(); +} + +void RegisterPermStateChangeScopePtr::SetEnv(const napi_env& env) +{ + env_ = env; +} + +void RegisterPermStateChangeScopePtr::SetCallbackRef(const napi_ref& ref) +{ + ref_ = ref; +} + +PermStateChangeContext::~PermStateChangeContext() +{ + if (callbackRef != nullptr) { + napi_delete_reference(env, callbackRef); + callbackRef = nullptr; + } +} + +UnregisterPermStateChangeInfo::~UnregisterPermStateChangeInfo() +{ + if (work != nullptr) { + napi_delete_async_work(env, work); + work = nullptr; + } +} + void NapiAtManager::SetNamedProperty(napi_env env, napi_value dstObj, const int32_t objValue, const char *propName) { napi_value prop = nullptr; @@ -54,7 +189,9 @@ napi_value NapiAtManager::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("verifyAccessTokenSync", VerifyAccessTokenSync), DECLARE_NAPI_FUNCTION("grantUserGrantedPermission", GrantUserGrantedPermission), DECLARE_NAPI_FUNCTION("revokeUserGrantedPermission", RevokeUserGrantedPermission), - DECLARE_NAPI_FUNCTION("getPermissionFlags", GetPermissionFlags) + DECLARE_NAPI_FUNCTION("getPermissionFlags", GetPermissionFlags), + DECLARE_NAPI_FUNCTION("on", RegisterPermStateChangeCallback), + DECLARE_NAPI_FUNCTION("off", UnregisterPermStateChangeCallback), }; napi_value cons = nullptr; @@ -70,8 +207,15 @@ napi_value NapiAtManager::Init(napi_env env, napi_value exports) SetNamedProperty(env, GrantStatus, PERMISSION_DENIED, "PERMISSION_DENIED"); SetNamedProperty(env, GrantStatus, PERMISSION_GRANTED, "PERMISSION_GRANTED"); + napi_value permStateChangeType = nullptr; + napi_create_object(env, &permStateChangeType); + + SetNamedProperty(env, permStateChangeType, PERMISSION_REVOKED_OPER, "PERMISSION_REVOKED_OPER"); + SetNamedProperty(env, permStateChangeType, PERMISSION_GRANTED_OPER, "PERMISSION_GRANTED_OPER"); + napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("GrantStatus", GrantStatus), + DECLARE_NAPI_PROPERTY("PermissionStateChangeType", permStateChangeType), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); @@ -85,6 +229,21 @@ napi_value NapiAtManager::JsConstructor(napi_env env, napi_callback_info cbinfo) napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, nullptr)); + AccessTokenKit* objectInfo = new (std::nothrow) AccessTokenKit(); + if (objectInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "objectInfo is nullptr"); + return nullptr; + } + if (napi_wrap(env, thisVar, objectInfo, [](napi_env env, void* data, void* hint) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "delete accesstoken kit"); + if (data != nullptr) { + AccessTokenKit* objectInfo = (AccessTokenKit*) data; + delete objectInfo; + } + }, nullptr, nullptr) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_wrap failed"); + return nullptr; + } return thisVar; } @@ -550,6 +709,321 @@ napi_value NapiAtManager::GetPermissionFlags(napi_env env, napi_callback_info in return result; } + +bool NapiAtManager::ParseInputToRegister(const napi_env env, const napi_callback_info cbInfo, + RegisterPermStateChangeInfo& registerPermStateChangeInfo) +{ + size_t argc = ARGS_FOUR; + napi_value argv[ARGS_FOUR] = {nullptr}; + napi_value thisVar = nullptr; + napi_ref callback = nullptr; + if (napi_get_cb_info(env, cbInfo, &argc, argv, &thisVar, NULL) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_get_cb_info failed"); + return false; + } + std::string type = ParseString(env, argv[PARAM0]); + PermStateChangeScope scopeInfo; + if (!ParseAccessTokenIDArray(env, argv[PARAM1], scopeInfo.tokenIDs)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ParseAccessTokenIDArray failed"); + return false; + } + scopeInfo.permList = ParseStringArray(env, argv[PARAM2]); + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[PARAM3], &valueType); // get PRARM[3] type + if (valueType == napi_function) { + if (napi_create_reference(env, argv[PARAM3], 1, &callback) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_create_reference failed"); + return false; + } + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "argv[PARAM3] type matching failed"); + return false; + } + registerPermStateChangeInfo.env = env; + registerPermStateChangeInfo.work = nullptr; + registerPermStateChangeInfo.callbackRef = callback; + registerPermStateChangeInfo.permStateChangeType = type; + registerPermStateChangeInfo.scopeInfo = scopeInfo; + registerPermStateChangeInfo.subscriber = std::make_shared(scopeInfo); + AccessTokenKit* accessTokenKitInfo = nullptr; + if (napi_unwrap(env, thisVar, reinterpret_cast(&accessTokenKitInfo)) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_unwrap failed"); + return false; + } + registerPermStateChangeInfo.accessTokenKit = accessTokenKitInfo; + return true; +} + +void NapiAtManager::RegisterPermStateChangeExecute(napi_env env, void* data) +{ + if (data == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "data is null"); + return; + } + RegisterPermStateChangeInfo* registerPermStateChangeInfo = + reinterpret_cast(data); + (*registerPermStateChangeInfo->subscriber).SetEnv(env); + (*registerPermStateChangeInfo->subscriber).SetCallbackRef(registerPermStateChangeInfo->callbackRef); + registerPermStateChangeInfo->errCode = + AccessTokenKit::RegisterPermStateChangeCallback(registerPermStateChangeInfo->subscriber); + ACCESSTOKEN_LOG_DEBUG(LABEL, "RegisterPermStateChangeCallback ret = %{public}d", + registerPermStateChangeInfo->errCode); +} + +void NapiAtManager::RegisterPermStateChangeComplete(napi_env env, napi_status status, void *data) +{ + if (data == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "data is null"); + return; + } + RegisterPermStateChangeInfo* registerPermStateChangeInfo = + reinterpret_cast(data); + if (registerPermStateChangeInfo->errCode != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "errCode = %{public}d, delete register in map", + registerPermStateChangeInfo->errCode); + // Even if napi_delete_async_work failed, invalid registerPermStateChangeInfo needs to be deleted + napi_delete_async_work(env, registerPermStateChangeInfo->work); + registerPermStateChangeInfo->work = nullptr; + DeleteRegisterInMap(registerPermStateChangeInfo->accessTokenKit, registerPermStateChangeInfo->scopeInfo); + return; + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, registerPermStateChangeInfo->work)); + registerPermStateChangeInfo->work = nullptr; +} + +napi_value NapiAtManager::RegisterPermStateChangeCallback(napi_env env, napi_callback_info cbInfo) +{ + RegisterPermStateChangeInfo* registerPermStateChangeInfo = + new (std::nothrow) RegisterPermStateChangeInfo(); + if (registerPermStateChangeInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "insufficient memory for subscribeCBInfo!"); + return nullptr; + } + std::unique_ptr callbackPtr {registerPermStateChangeInfo}; + if (!ParseInputToRegister(env, cbInfo, *registerPermStateChangeInfo)) { + return nullptr; + } + if (IsExistRegister(registerPermStateChangeInfo)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Subscribe failed. The current subscriber has been existed"); + return nullptr; + } + { // add to map + std::lock_guard lock(g_lockForPermStateChangeRegisters); + g_permStateChangeRegisters[registerPermStateChangeInfo->accessTokenKit].emplace_back( + registerPermStateChangeInfo); + ACCESSTOKEN_LOG_DEBUG(LABEL, "add g_PermStateChangeRegisters->second.size = %{public}zu", + g_permStateChangeRegisters[registerPermStateChangeInfo->accessTokenKit].size()); + } + napi_value resource = nullptr; + if (napi_create_string_utf8(env, "RegisterPermStateChangeCallback", NAPI_AUTO_LENGTH, &resource) != napi_ok) { + DeleteRegisterInMap(registerPermStateChangeInfo->accessTokenKit, registerPermStateChangeInfo->scopeInfo); + return nullptr; + } + if (napi_create_async_work(env, + nullptr, + resource, + RegisterPermStateChangeExecute, + RegisterPermStateChangeComplete, + reinterpret_cast(registerPermStateChangeInfo), + ®isterPermStateChangeInfo->work) != napi_ok) { + DeleteRegisterInMap(registerPermStateChangeInfo->accessTokenKit, registerPermStateChangeInfo->scopeInfo); + return nullptr; + } + if (napi_queue_async_work(env, registerPermStateChangeInfo->work) != napi_ok) { + DeleteRegisterInMap(registerPermStateChangeInfo->accessTokenKit, registerPermStateChangeInfo->scopeInfo); + return nullptr; + } + callbackPtr.release(); + return nullptr; +} + +bool NapiAtManager::ParseInputToUnregister(const napi_env env, napi_callback_info cbInfo, + UnregisterPermStateChangeInfo& unregisterPermStateChangeInfo) +{ + size_t argc = ARGS_FOUR; + napi_value argv[ARGS_FOUR] = {nullptr}; + napi_value thisVar = nullptr; + napi_ref callback = nullptr; + if (napi_get_cb_info(env, cbInfo, &argc, argv, &thisVar, NULL) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_get_cb_info failed"); + return false; + } + std::string type = ParseString(env, argv[PARAM0]); + PermStateChangeScope scopeInfo; + if (!ParseAccessTokenIDArray(env, argv[PARAM1], scopeInfo.tokenIDs)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ParseAccessTokenIDArray failed"); + return false; + } + scopeInfo.permList = ParseStringArray(env, argv[PARAM2]); + if (argc >= ARGS_FOUR) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[PARAM3], &valueType); // get PRARM[3] type + if (valueType == napi_function) { + if (napi_create_reference(env, argv[PARAM3], 1, &callback) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_create_reference failed"); + return false; + } + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "argv[PARAM3] type matching failed"); + return false; + } + } + unregisterPermStateChangeInfo.env = env; + unregisterPermStateChangeInfo.callbackRef = callback; + unregisterPermStateChangeInfo.permStateChangeType = type; + unregisterPermStateChangeInfo.scopeInfo = scopeInfo; + AccessTokenKit* accessTokenKitInfo = nullptr; + if (napi_unwrap(env, thisVar, reinterpret_cast(&accessTokenKitInfo)) != napi_ok) { + ACCESSTOKEN_LOG_ERROR(LABEL, "napi_unwrap failed"); + return false; + } + unregisterPermStateChangeInfo.accessTokenKit = accessTokenKitInfo; + return true; +} + +void NapiAtManager::UnregisterPermStateChangeExecute(napi_env env, void* data) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "UnregisterPermStateChangeExecute begin"); + if (data == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "data is null"); + return; + } + UnregisterPermStateChangeInfo* unregisterPermStateChangeInfo = + reinterpret_cast(data); + auto subscriber = unregisterPermStateChangeInfo->subscriber; + unregisterPermStateChangeInfo->errCode = AccessTokenKit::UnRegisterPermStateChangeCallback(subscriber); +} + +void NapiAtManager::UnregisterPermStateChangeCompleted(napi_env env, napi_status status, void* data) +{ + if (data == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "data is null"); + return; + } + UnregisterPermStateChangeInfo* unregisterPermStateChangeInfo = + reinterpret_cast(data); + std::unique_ptr callbackPtr {unregisterPermStateChangeInfo}; + if (unregisterPermStateChangeInfo->callbackRef != nullptr) { + napi_value results[ARGS_ONE] = {nullptr}; + NAPI_CALL_RETURN_VOID(env, napi_get_null(env, &results[PARAM0])); + napi_value undefined; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + napi_value resultout = nullptr; + napi_value callback = nullptr; + NAPI_CALL_RETURN_VOID(env, + napi_get_reference_value(env, unregisterPermStateChangeInfo->callbackRef, &callback)); + NAPI_CALL_RETURN_VOID(env, + napi_call_function(env, undefined, callback, ARGS_ONE, &results[PARAM0], &resultout)); + } + if (unregisterPermStateChangeInfo->errCode == RET_SUCCESS) { + DeleteRegisterInMap(unregisterPermStateChangeInfo->accessTokenKit, unregisterPermStateChangeInfo->scopeInfo); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "errCode = %{public}d", unregisterPermStateChangeInfo->errCode); + } +} + +napi_value NapiAtManager::UnregisterPermStateChangeCallback(napi_env env, napi_callback_info cbInfo) +{ + UnregisterPermStateChangeInfo* unregisterPermStateChangeInfo = + new (std::nothrow) UnregisterPermStateChangeInfo(); + if (unregisterPermStateChangeInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "insufficient memory for subscribeCBInfo!"); + return nullptr; + } + std::unique_ptr callbackPtr {unregisterPermStateChangeInfo}; + if (!ParseInputToUnregister(env, cbInfo, *unregisterPermStateChangeInfo)) { + return nullptr; + } + if (!FindAndGetSubscriberInMap(unregisterPermStateChangeInfo)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Unsubscribe failed. The current subscriber does not exist"); + return nullptr; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "The current subscriber exist"); + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "RegisterPermStateChangeCallback", NAPI_AUTO_LENGTH, &resource)); + NAPI_CALL(env, napi_create_async_work(env, + nullptr, + resource, + UnregisterPermStateChangeExecute, + UnregisterPermStateChangeCompleted, + reinterpret_cast(unregisterPermStateChangeInfo), + &(unregisterPermStateChangeInfo->work))); + NAPI_CALL(env, napi_queue_async_work(env, unregisterPermStateChangeInfo->work)); + callbackPtr.release(); + return nullptr; +} + +bool NapiAtManager::FindAndGetSubscriberInMap(UnregisterPermStateChangeInfo* unregisterPermStateChangeInfo) +{ + std::lock_guard lock(g_lockForPermStateChangeRegisters); + std::vector tokenIDs = unregisterPermStateChangeInfo->scopeInfo.tokenIDs; + std::vector permList = unregisterPermStateChangeInfo->scopeInfo.permList; + std::sort(tokenIDs.begin(), tokenIDs.end()); + std::sort(permList.begin(), permList.end()); + auto registerInstance = g_permStateChangeRegisters.find(unregisterPermStateChangeInfo->accessTokenKit); + if (registerInstance != g_permStateChangeRegisters.end()) { + for (const auto& item : registerInstance->second) { + PermStateChangeScope scopeInfo; + item->subscriber->GetScope(scopeInfo); + if (CompareScopeInfo(scopeInfo, tokenIDs, permList)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "find subscriber in map"); + unregisterPermStateChangeInfo->subscriber = item->subscriber; + return true; + } + } + } + return false; +} + +bool NapiAtManager::IsExistRegister(const RegisterPermStateChangeInfo* registerPermStateChangeInfo) +{ + std::lock_guard lock(g_lockForPermStateChangeRegisters); + std::vector tokenIDs = registerPermStateChangeInfo->scopeInfo.tokenIDs; + std::vector permList = registerPermStateChangeInfo->scopeInfo.permList; + std::sort(tokenIDs.begin(), tokenIDs.end()); + std::sort(permList.begin(), permList.end()); + auto registerInstance = g_permStateChangeRegisters.find(registerPermStateChangeInfo->accessTokenKit); + if (registerInstance != g_permStateChangeRegisters.end()) { + for (const auto& item : registerInstance->second) { + PermStateChangeScope scopeInfo; + item->subscriber->GetScope(scopeInfo); + if (CompareScopeInfo(scopeInfo, tokenIDs, permList)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "find subscriber in map"); + return true; + } + } + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "cannot find subscriber in map"); + return false; +} + +void NapiAtManager::DeleteRegisterInMap(AccessTokenKit* accessTokenKit, const PermStateChangeScope& scopeInfo) +{ + std::vector tokenIDs = scopeInfo.tokenIDs; + std::vector permList = scopeInfo.permList; + std::sort(tokenIDs.begin(), tokenIDs.end()); + std::sort(permList.begin(), permList.end()); + std::lock_guard lock(g_lockForPermStateChangeRegisters); + auto subscribers = g_permStateChangeRegisters.find(accessTokenKit); + if (subscribers != g_permStateChangeRegisters.end()) { + auto it = subscribers->second.begin(); + while (it != subscribers->second.end()) { + if (CompareScopeInfo((*it)->scopeInfo, tokenIDs, permList)) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "Find subscribers in map, delete"); + delete *it; + *it = nullptr; + subscribers->second.erase(it); + break; + } else { + ++it; + } + } + if (subscribers->second.empty()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "No subscriberInfo in the vector, erase the map."); + g_permStateChangeRegisters.erase(subscribers); + } + } +} } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn b/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn index 8852db8985173ec9e94c80e531d6810c3c2d965f..5b665785891e217d3eab7e21ce2bc1323da2a5ce 100644 --- a/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn +++ b/interfaces/kits/accesstoken/test/benchmarktest/BUILD.gn @@ -28,6 +28,8 @@ config("access_token_kits_config_benchmarktest") { "//base/security/access_token/interfaces/innerkits/accesstoken/include/permission_def.h", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] @@ -38,7 +40,10 @@ ohos_benchmarktest("NapiAtmanagerTest") { module_out_path = module_output_path sources = [ "napi_atmanager_test.cpp" ] - configs = [ ":access_token_kits_config_benchmarktest" ] + configs = [ + ":access_token_kits_config_benchmarktest", + "//base/security/access_token/config:coverage_flags", + ] deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", diff --git a/interfaces/kits/common/BUILD.gn b/interfaces/kits/common/BUILD.gn index 7e98c3eea9f896907db387e6a96c53e136baa328..e317d6d741e99db76d27a3478a5c3a0dacea29f4 100644 --- a/interfaces/kits/common/BUILD.gn +++ b/interfaces/kits/common/BUILD.gn @@ -17,11 +17,13 @@ ohos_static_library("libnapi_common") { include_dirs = [ "include", "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", "//foundation/arkui/napi/interfaces/inner_api", "//foundation/arkui/napi/interfaces/kits", ] sources = [ "src/napi_common.cpp" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] deps = [ "//foundation/arkui/napi:ace_napi" ] cflags_cc = [ "-DHILOG_ENABLE" ] diff --git a/interfaces/kits/common/include/napi_common.h b/interfaces/kits/common/include/napi_common.h index 22c77629348377422dec8c36bfe70c16d1810fd0..4dda17ac74b1a469d57a42f8a63537d4c603b811 100644 --- a/interfaces/kits/common/include/napi_common.h +++ b/interfaces/kits/common/include/napi_common.h @@ -16,20 +16,24 @@ #ifndef INTERFACES_PRIVACY_KITS_NAPI_COMMON_H #define INTERFACES_PRIVACY_KITS_NAPI_COMMON_H +#include "access_token.h" #include "napi/native_api.h" #include "napi/native_node_api.h" namespace OHOS { namespace Security { namespace AccessToken { +const int ARGS_ONE = 1; const int ARGS_TWO = 2; const int ARGS_THREE = 3; +const int ARGS_FOUR = 4; const int ARGS_FIVE = 5; const int ASYNC_CALL_BACK_VALUES_NUM = 2; const int PARAM0 = 0; const int PARAM1 = 1; const int PARAM2 = 2; const int PARAM3 = 3; +const int VALUE_BUFFER_SIZE = 256; bool ParseBool(const napi_env env, const napi_value value); int32_t ParseInt32(const napi_env env, const napi_value value); @@ -37,6 +41,8 @@ int64_t ParseInt64(const napi_env env, const napi_value value); uint32_t ParseUint32(const napi_env env, const napi_value value); std::string ParseString(const napi_env env, const napi_value value); std::vector ParseStringArray(const napi_env env, const napi_value value); +bool ParseAccessTokenIDArray(const napi_env& env, const napi_value& value, std::vector& res); +bool IsArray(const napi_env& env, const napi_value& value); } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/kits/common/src/napi_common.cpp b/interfaces/kits/common/src/napi_common.cpp index 28c487953d0655b7262dd7729f88c77ab5f43b94..000d7a8a1f92a4f8cb8d58246c7d389705c3caf6 100644 --- a/interfaces/kits/common/src/napi_common.cpp +++ b/interfaces/kits/common/src/napi_common.cpp @@ -109,6 +109,9 @@ std::string ParseString(const napi_env env, const napi_value value) std::vector ParseStringArray(const napi_env env, const napi_value value) { std::vector res; + if (!IsArray(env, value)) { + return res; + } uint32_t length = 0; napi_valuetype valuetype = napi_undefined; @@ -124,6 +127,31 @@ std::vector ParseStringArray(const napi_env env, const napi_value v } return res; } + +bool ParseAccessTokenIDArray(const napi_env& env, const napi_value& value, std::vector& res) +{ + uint32_t length = 0; + if (!IsArray(env, value)) { + return false; + } + napi_get_array_length(env, value, &length); + napi_value valueArray; + for (uint32_t i = 0; i < length; i++) { + napi_get_element(env, value, i, &valueArray); + res.emplace_back(ParseUint32(env, valueArray)); + } + return true; +}; + +bool IsArray(const napi_env& env, const napi_value& value) +{ + bool isArray = false; + napi_status ret = napi_is_array(env, value, &isArray); + if (ret != napi_ok) { + return false; + } + return isArray; +} } // namespace AccessToken } // namespace Security } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/privacy/BUILD.gn b/interfaces/kits/privacy/BUILD.gn index fb369bd606abe3a00855be5223865a7b76d88fdf..6b6fc2305b8b698ac92effd2b65180b1dc991302 100644 --- a/interfaces/kits/privacy/BUILD.gn +++ b/interfaces/kits/privacy/BUILD.gn @@ -22,6 +22,7 @@ ohos_shared_library("libprivacymanager") { "//base/security/access_token/interfaces/kits/common/include", "//foundation/arkui/napi/interfaces/inner_api", "//foundation/arkui/napi/interfaces/kits", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//commonlibrary/c_utils/base/include", ] @@ -40,8 +41,8 @@ ohos_shared_library("libprivacymanager") { external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] relative_install_dir = "module" subsystem_name = "security" diff --git a/services/accesstokenmanager/BUILD.gn b/services/accesstokenmanager/BUILD.gn index 116041ae5948e30e3195640e446b41ed8427a7fc..2ade820072a5837b8fe88177cf656ff5545c792b 100644 --- a/services/accesstokenmanager/BUILD.gn +++ b/services/accesstokenmanager/BUILD.gn @@ -67,6 +67,7 @@ if (is_standard_system) { ] cflags_cc = [ "-DHILOG_ENABLE" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] if (dlp_permission_enable == true) { cflags_cc += [ "-DSUPPORT_SANDBOX_APP" ] diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h b/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h index 30f6d542a0b13e1aba853dc287f9f5993deea018..c910b06da4ae4025dd1cc057389f1a0eee47cec2 100644 --- a/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_manager.h @@ -24,6 +24,7 @@ #include "iremote_broker.h" #include "permission_def.h" #include "permission_list_state.h" +#include "permission_list_state_parcel.h" #include "permission_state_change_info.h" #include "permission_state_full.h" @@ -33,6 +34,11 @@ namespace OHOS { namespace Security { namespace AccessToken { +constexpr const char* VAGUE_LOCATION_PERMISSION_NAME = "ohos.permission.APPROXIMATELY_LOCATION"; +constexpr const char* ACCURATE_LOCATION_PERMISSION_NAME = "ohos.permission.LOCATION"; +const int32_t ELEMENT_NOT_FOUND = -1; +const int32_t ACCURATE_LOCATION_API_VERSION = 9; + class PermissionManager final { public: static PermissionManager& GetInstance(); @@ -54,16 +60,26 @@ public: void RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); void ClearUserGrantedPermissionState(AccessTokenID tokenID); void GetSelfPermissionState( - std::vector permsList, PermissionListState &permState); + std::vector permsList, PermissionListState &permState, int32_t apiVersion); int32_t AddPermStateChangeCallback( const PermStateChangeScope& scope, const sptr& callback); int32_t RemovePermStateChangeCallback(const sptr& callback); + bool GetApiVersionByTokenId(AccessTokenID tokenID, int32_t& apiVersion); + bool GetLocationPermissionIndex(std::vector& reqPermList, int& vagueIndex, + int& accurateIndex); + bool LocationPermissionSpecialHandle(std::vector& reqPermList, int32_t apiVersion, + std::vector permsList, int vagueIndex, int accurateIndex); private: PermissionManager(); void UpdateTokenPermissionState( AccessTokenID tokenID, const std::string& permissionName, bool isGranted, int flag); std::string TransferPermissionDefToString(const PermissionDef& inPermissionDef); + bool IsPermissionVaild(const std::string& permissionName); + bool GetPermissionStatusAndFlag(const std::string& permissionName, + const std::vector& permsList, int32_t& status, uint32_t& flag); + void AllLocationPermissionHandle(std::vector& reqPermList, + std::vector permsList, int vagueIndex, int accurateIndex); DISALLOW_COPY_AND_MOVE(PermissionManager); }; diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h index ebc754ad1142266180ed602e445f71b3551fccec..2b46210f17abee76a7783b2370990cbb3b2edf68 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h @@ -61,7 +61,7 @@ public: int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& InfoParcel) override; int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) override; int UpdateHapToken(AccessTokenID tokenID, - const std::string& appIDDesc, const HapPolicyParcel& policyParcel) override; + const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyParcel) override; int32_t RegisterPermStateChangeCallback( const PermStateChangeScopeParcel& scope, const sptr& callback) override; int32_t UnRegisterPermStateChangeCallback(const sptr& callback) override; @@ -79,7 +79,7 @@ public: void DestroyDeviceListenner(); #endif - void DumpTokenInfo(std::string& dumpInfo) override; + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) override; private: bool Initialize(); diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h index cbc45c2beaf56f40810e05a8f8c800dcf94682ce..e95fa76f9324f036f53b23e64dbac58691f7a69f 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -72,6 +72,7 @@ private: bool IsAuthorizedCalling() const; bool IsAccessTokenCalling() const; + bool IsNativeProcessCalling(); static const int32_t SYSTEM_UID = 1000; static const int32_t ROOT_UID = 0; static const int32_t ACCESSTOKEN_UID = 3020; diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h index 0620800f015da3c9d56b0e1976d6d0b9718579fd..d6e866d56f0a1e0039aa08d1a465b711eb20d601 100644 --- a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h @@ -53,8 +53,9 @@ public: AccessTokenID GetHapTokenID(int userID, const std::string& bundleName, int instIndex); AccessTokenID AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID); void ProcessNativeTokenInfos(const std::vector>& tokenInfos); - int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); - void DumpTokenInfo(std::string& dumpInfo); + int UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); + void DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo); void RefreshTokenInfoIfNeeded(); #ifdef TOKEN_SYNC_ENABLE diff --git a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h index 73781ccaa04ee1dce91592a5ea54a043cae14ce0..ace08daad6469c4ba25e64277b3b1f042e2b6c99 100644 --- a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h +++ b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h @@ -38,11 +38,11 @@ public: const std::vector& permStateList); virtual ~HapTokenInfoInner(); - void Update(const std::string& appIDDesc, const HapPolicyParams& policy); + void Update(const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy); void TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const; void StoreHapInfo(std::vector& hapInfoValues, std::vector& permStateValues) const; - int RestoreHapTokenInfo(AccessTokenID tokenId, GenericValues& tokenValue, + int RestoreHapTokenInfo(AccessTokenID tokenId, const GenericValues& tokenValue, const std::vector& permStateRes); std::shared_ptr GetHapInfoPermissionPolicySet() const; diff --git a/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp index ed72bd2d8f0054ab37a90a964cf8a21b3d820562..5763a0c4ae0319995c4a35e8682ab2db40c0463d 100644 --- a/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp +++ b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp @@ -58,7 +58,7 @@ SqliteStorage::SqliteStorage() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATA FIELD_BUNDLE_NAME, FIELD_INST_INDEX, FIELD_DLP_TYPE, FIELD_APP_ID, FIELD_DEVICE_ID, FIELD_APL, FIELD_TOKEN_VERSION, - FIELD_TOKEN_ATTR + FIELD_TOKEN_ATTR, FIELD_API_VERSION }; SqliteTable NativeTokenInfoTable; @@ -299,6 +299,7 @@ int SqliteStorage::CreateHapTokenInfoTable() const .append(FIELD_APL + " integer not null,") .append(FIELD_TOKEN_VERSION + " integer not null,") .append(FIELD_TOKEN_ATTR + " integer not null,") + .append(FIELD_API_VERSION + " integer not null,") .append("primary key(" + FIELD_TOKEN_ID) .append("))"); return ExecuteSql(sql); diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp index 4819bf77637ca14c80a76ed5abf15f5788d64d60..90f65aefe59d4d5e157b12579b6699ee37553229 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp @@ -150,7 +150,7 @@ int PermissionManager::VerifyAccessToken(AccessTokenID tokenID, const std::strin } ATokenTypeEnum tokenType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID); - if (tokenType == TOKEN_NATIVE) { + if ((tokenType == TOKEN_NATIVE) || (tokenType == TOKEN_SHELL)) { return VerifyNativeAccessToken(tokenID, permissionName); } if (tokenType == TOKEN_HAP) { @@ -239,15 +239,23 @@ int PermissionManager::GetReqPermissions( } void PermissionManager::GetSelfPermissionState(std::vector permsList, - PermissionListState &permState) + PermissionListState &permState, int32_t apiVersion) { bool foundGoal = false; int32_t goalGrantStatus; uint32_t goalGrantFlags; + + // api8 require vague location permission refuse directlty beause there is no vague location permission in api8 + if ((permState.permissionName == VAGUE_LOCATION_PERMISSION_NAME) && + (apiVersion < ACCURATE_LOCATION_API_VERSION)) { + permState.state = INVALID_OPER; + return; + } + for (const auto& perm : permsList) { if (perm.permissionName == permState.permissionName) { - ACCESSTOKEN_LOG_INFO(LABEL, - "find goal permission: %{public}s!", permState.permissionName.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "find goal permission: %{public}s, status: %{public}d, flag: %{public}d", + permState.permissionName.c_str(), perm.grantStatus[0], perm.grantFlags[0]); foundGoal = true; goalGrantStatus = perm.grantStatus[0]; goalGrantFlags = static_cast(perm.grantFlags[0]); @@ -405,6 +413,167 @@ int32_t PermissionManager::RemovePermStateChangeCallback(const sptr(&tokenID); + ATokenTypeEnum tokenType = (ATokenTypeEnum)(idInner->type); + if (tokenType != TOKEN_HAP) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid token type %{public}d", tokenType); + return false; + } + + HapTokenInfo hapInfo; + int ret = AccessTokenInfoManager::GetInstance().GetHapTokenInfo(tokenID, hapInfo); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get hap token info error!"); + return false; + } + + apiVersion = hapInfo.apiVersion; + + return true; +} + +bool PermissionManager::GetLocationPermissionIndex(std::vector& reqPermList, + int& vagueIndex, int& accurateIndex) +{ + int index = 0; + bool hasFound = false; + + for (const auto& perm : reqPermList) { + if (perm.permsState.permissionName == VAGUE_LOCATION_PERMISSION_NAME) { + vagueIndex = index; + hasFound = true; + } else if (perm.permsState.permissionName == ACCURATE_LOCATION_PERMISSION_NAME) { + accurateIndex = index; + hasFound = true; + } + + index++; + + if ((vagueIndex != ELEMENT_NOT_FOUND) && (accurateIndex != ELEMENT_NOT_FOUND)) { + break; + } + } + + ACCESSTOKEN_LOG_INFO(LABEL, + "vague location permission index is %{public}d, accurate location permission index is %{public}d!", + vagueIndex, accurateIndex); + + return hasFound; +} + +bool PermissionManager::IsPermissionVaild(const std::string& permissionName) +{ + if (!PermissionValidator::IsPermissionNameValid(permissionName)) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid permissionName %{public}s", permissionName.c_str()); + return false; + } + + if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + ACCESSTOKEN_LOG_WARN(LABEL, "permission %{public}s has no definition ", permissionName.c_str()); + return false; + } + return true; +} + +bool PermissionManager::GetPermissionStatusAndFlag(const std::string& permissionName, + const std::vector& permsList, int32_t& status, uint32_t& flag) +{ + if (!IsPermissionVaild(permissionName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission %{public}s", permissionName.c_str()); + return false; + } + + for (const auto& perm : permsList) { + if (perm.permissionName == permissionName) { + status = perm.grantStatus[0]; + flag = static_cast(perm.grantFlags[0]); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "permission:%{public}s, status:%{public}d, flag:%{public}d!", + permissionName.c_str(), status, flag); + return true; + } + } + return false; +} + +void PermissionManager::AllLocationPermissionHandle(std::vector& reqPermList, + std::vector permsList, int vagueIndex, int accurateIndex) +{ + int32_t vagueStatus = PERMISSION_DENIED; + uint32_t vagueFlag = PERMISSION_DEFAULT_FLAG; + int32_t vagueState = INVALID_OPER; + int32_t accurateStatus = PERMISSION_DENIED; + uint32_t accurateFlag = PERMISSION_DEFAULT_FLAG; + int32_t accurateState = INVALID_OPER; + + if (!GetPermissionStatusAndFlag(VAGUE_LOCATION_PERMISSION_NAME, permsList, vagueStatus, vagueFlag) || + !GetPermissionStatusAndFlag(ACCURATE_LOCATION_PERMISSION_NAME, permsList, accurateStatus, accurateFlag)) { + return; + } + + // vague location status -1 means vague location permission has been refused + if (vagueStatus == PERMISSION_DENIED) { + if ((vagueFlag == PERMISSION_DEFAULT_FLAG) || ((vagueFlag & PERMISSION_USER_SET) != 0)) { + // vague location flag 0 or 1 means permission has not been operated or valid only once + vagueState = DYNAMIC_OPER; + accurateState = DYNAMIC_OPER; + } else if ((vagueFlag & PERMISSION_USER_FIXED) != 0) { + // vague location flag 2 means vague location has been operated, only can be changed by settings + // so that accurate location is no need to operate + vagueState = SETTING_OPER; + accurateState = SETTING_OPER; + } + } else if (vagueStatus == PERMISSION_GRANTED) { + // vague location status 0 means vague location permission has been accepted + // now flag 1 is not in use so return PASS_OPER, otherwise should judge by flag + vagueState = PASS_OPER; + + if (accurateStatus == PERMISSION_DENIED) { + if ((accurateFlag == PERMISSION_DEFAULT_FLAG) || ((accurateFlag & PERMISSION_USER_SET) != 0)) { + accurateState = DYNAMIC_OPER; + } else if ((accurateFlag & PERMISSION_USER_FIXED) != 0) { + accurateState = SETTING_OPER; + } + } else if (accurateStatus == PERMISSION_GRANTED) { + accurateState = PASS_OPER; + } + } + + ACCESSTOKEN_LOG_INFO(LABEL, + "vague location permission state is %{public}d, accurate location permission state is %{public}d", + vagueState, accurateState); + + reqPermList[vagueIndex].permsState.state = vagueState; + reqPermList[accurateIndex].permsState.state = accurateState; +} + +bool PermissionManager::LocationPermissionSpecialHandle(std::vector& reqPermList, + int32_t apiVersion, std::vector permsList, int vagueIndex, int accurateIndex) +{ + if ((vagueIndex != ELEMENT_NOT_FOUND) && (accurateIndex == ELEMENT_NOT_FOUND)) { + // only vague location permission + GetSelfPermissionState(permsList, reqPermList[vagueIndex].permsState, apiVersion); + if (reqPermList[vagueIndex].permsState.state == DYNAMIC_OPER) { + return true; + } + } + + if ((vagueIndex == ELEMENT_NOT_FOUND) && (accurateIndex != ELEMENT_NOT_FOUND)) { + // only accurate location permission refuse directly + ACCESSTOKEN_LOG_ERROR(LABEL, "operate invaild, accurate location permission base on vague location permission"); + reqPermList[accurateIndex].permsState.state = INVALID_OPER; + return false; + } + + // all location permissions + AllLocationPermissionHandle(reqPermList, permsList, vagueIndex, accurateIndex); + return ((reqPermList[vagueIndex].permsState.state == DYNAMIC_OPER) || + (reqPermList[accurateIndex].permsState.state == DYNAMIC_OPER)); +} + void PermissionManager::ClearUserGrantedPermissionState(AccessTokenID tokenID) { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: %{public}u", __func__, tokenID); diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp index f09dcdccb023a6caf79fe60b016fc2bb96792051..7065736bf3a084376c5f500adcf6e51485b3cd5d 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -145,7 +145,13 @@ PermissionOper AccessTokenManagerService::GetSelfPermissionsState( std::vector& reqPermList) { AccessTokenID callingTokenID = IPCSkeleton::GetCallingTokenID(); - ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}d", callingTokenID); + + int32_t apiVersion = 0; + if (!PermissionManager::GetInstance().GetApiVersionByTokenId(callingTokenID, apiVersion)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get api version error"); + return INVALID_OPER; + } + ACCESSTOKEN_LOG_INFO(LABEL, "callingTokenID: %{public}d, apiVersion: %{public}d", callingTokenID, apiVersion); bool needRes = false; std::vector permsList; @@ -158,10 +164,25 @@ PermissionOper AccessTokenManagerService::GetSelfPermissionsState( return INVALID_OPER; } + int vagueIndex = ELEMENT_NOT_FOUND; + int accurateIndex = ELEMENT_NOT_FOUND; + + if (apiVersion >= ACCURATE_LOCATION_API_VERSION) { + if (PermissionManager::GetInstance().GetLocationPermissionIndex(reqPermList, vagueIndex, accurateIndex)) { + needRes = PermissionManager::GetInstance().LocationPermissionSpecialHandle(reqPermList, apiVersion, + permsList, vagueIndex, accurateIndex); // api9 location permission handle here + } + } + uint32_t size = reqPermList.size(); for (uint32_t i = 0; i < size; i++) { - PermissionManager::GetInstance().GetSelfPermissionState( - permsList, reqPermList[i].permsState); + if (((reqPermList[i].permsState.permissionName == VAGUE_LOCATION_PERMISSION_NAME) || + (reqPermList[i].permsState.permissionName == ACCURATE_LOCATION_PERMISSION_NAME)) && + (apiVersion >= ACCURATE_LOCATION_API_VERSION)) { + continue; // api9 location permission special handle above + } + + PermissionManager::GetInstance().GetSelfPermissionState(permsList, reqPermList[i].permsState, apiVersion); if (reqPermList[i].permsState.state == DYNAMIC_OPER) { needRes = true; } @@ -170,6 +191,11 @@ PermissionOper AccessTokenManagerService::GetSelfPermissionsState( } if (needRes) { return DYNAMIC_OPER; + } else { + if ((vagueIndex == ELEMENT_NOT_FOUND) && (accurateIndex != ELEMENT_NOT_FOUND)) { + // only accurate location permission without other DYNAMIC_OPER state return INVALID_OPER + return INVALID_OPER; + } } return PASS_OPER; } @@ -271,12 +297,12 @@ AccessTokenID AccessTokenManagerService::AllocLocalTokenID( return AccessTokenInfoManager::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); } -int AccessTokenManagerService::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, - const HapPolicyParcel& policyParcel) +int AccessTokenManagerService::UpdateHapToken( + AccessTokenID tokenID, const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParcel& policyParcel) { ACCESSTOKEN_LOG_INFO(LABEL, "called, tokenID: 0x%{public}x", tokenID); - return AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenID, appIDDesc, + return AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenID, appIDDesc, apiVersion, policyParcel.hapPolicyParameter); } @@ -367,11 +393,11 @@ int AccessTokenManagerService::DeleteRemoteDeviceTokens(const std::string& devic } #endif -void AccessTokenManagerService::DumpTokenInfo(std::string& dumpInfo) +void AccessTokenManagerService::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) { ACCESSTOKEN_LOG_INFO(LABEL, "called"); - AccessTokenInfoManager::GetInstance().DumpTokenInfo(dumpInfo); + AccessTokenInfoManager::GetInstance().DumpTokenInfo(tokenID, dumpInfo); } #ifdef TOKEN_SYNC_ENABLE void AccessTokenManagerService::CreateDeviceListenner() diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp index 4d40336116237a39fda335691bf82f26770228ad..5039f472f188d8ff01e5e46683368308927258e7 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -234,8 +234,7 @@ void AccessTokenManagerStub::GetTokenTypeInner(MessageParcel& data, MessageParce void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + if (!IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -248,8 +247,7 @@ void AccessTokenManagerStub::CheckNativeDCapInner(MessageParcel& data, MessagePa void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + if (!IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(INVALID_TOKENID); return; @@ -263,8 +261,7 @@ void AccessTokenManagerStub::GetHapTokenIDInner(MessageParcel& data, MessageParc void AccessTokenManagerStub::AllocLocalTokenIDInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if ((!IsAuthorizedCalling()) && (this->GetTokenType(tokenCaller) != TOKEN_NATIVE)) { + if ((!IsAuthorizedCalling()) && (!IsNativeProcessCalling())) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(INVALID_TOKENID); return; @@ -284,20 +281,20 @@ void AccessTokenManagerStub::UpdateHapTokenInner(MessageParcel& data, MessagePar } AccessTokenID tokenID = data.ReadUint32(); std::string appIDDesc = data.ReadString(); + int32_t apiVersion = data.ReadInt32(); sptr policyParcel = data.ReadParcelable(); if (policyParcel == nullptr) { ACCESSTOKEN_LOG_ERROR(LABEL, "policyParcel read faild"); reply.WriteInt32(RET_FAILED); return; } - int32_t result = this->UpdateHapToken(tokenID, appIDDesc, *policyParcel); + int32_t result = this->UpdateHapToken(tokenID, appIDDesc, apiVersion, *policyParcel); reply.WriteInt32(result); } void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if ((this->GetTokenType(tokenCaller) != TOKEN_NATIVE)) { + if (!IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -311,8 +308,7 @@ void AccessTokenManagerStub::GetHapTokenInfoInner(MessageParcel& data, MessagePa void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + if (!IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -477,14 +473,14 @@ void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, void AccessTokenManagerStub::DumpTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (this->GetTokenType(tokenCaller) != TOKEN_NATIVE) { + if (!IsNativeProcessCalling()) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; } + AccessTokenID tokenID = data.ReadUint32(); std::string dumpInfo = ""; - this->DumpTokenInfo(dumpInfo); + this->DumpTokenInfo(tokenID, dumpInfo); reply.WriteString(dumpInfo); } @@ -501,6 +497,17 @@ bool AccessTokenManagerStub::IsAccessTokenCalling() const return callingUid == ACCESSTOKEN_UID; } +bool AccessTokenManagerStub::IsNativeProcessCalling() +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + int32_t type = this->GetTokenType(tokenCaller); + ACCESSTOKEN_LOG_DEBUG(LABEL, "Calling tokenID: %{public}d, type: %{public}d", tokenCaller, type); + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { + return false; + } + return true; +} + AccessTokenManagerStub::AccessTokenManagerStub() { requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::VERIFY_ACCESSTOKEN)] = diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp index a4cabdbea818eda4c5c5400a67f69dd15ac3dd35..3da271eff9f29e38529bfc699719458ecf0cf2cb 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -81,7 +81,7 @@ void AccessTokenInfoManager::InitHapTokenInfos() DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_DEF, permDefRes); DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); - for (GenericValues& tokenValue : hapTokenRes) { + for (const GenericValues& tokenValue : hapTokenRes) { AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(FIELD_TOKEN_ID); int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP); if (ret != RET_SUCCESS) { @@ -121,9 +121,10 @@ void AccessTokenInfoManager::InitNativeTokenInfos() DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_NATIVE_INFO, nativeTokenResults); DataStorage::GetRealDataStorage().Find(DataStorage::ACCESSTOKEN_PERMISSION_STATE, permStateRes); - for (GenericValues nativeTokenValue : nativeTokenResults) { + for (const GenericValues& nativeTokenValue : nativeTokenResults) { AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(FIELD_TOKEN_ID); - int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_NATIVE); + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenId); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, type); if (ret != RET_SUCCESS) { ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId %{public}u add failed.", tokenId); continue; @@ -341,7 +342,7 @@ int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id) int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id) { ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); - if (type != TOKEN_NATIVE) { + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { ACCESSTOKEN_LOG_ERROR( LABEL, "token %{public}u is not hap.", id); return RET_FAILED; @@ -380,10 +381,10 @@ static void GetPolicyCopied(const HapPolicyParams& policy, HapPolicyParams& poli policyNew.apl = policy.apl; policyNew.domain = policy.domain; - for (auto& state : policy.permStateList) { + for (const auto& state : policy.permStateList) { policyNew.permStateList.emplace_back(state); } - for (auto& def : policy.permList) { + for (const auto& def : policy.permList) { policyNew.permList.emplace_back(def); } } @@ -527,7 +528,8 @@ void AccessTokenInfoManager::ProcessNativeTokenInfos( "token %{public}u process name %{public}s is new, add to manager!", infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); AccessTokenID id = infoPtr->GetTokenID(); - int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_NATIVE); + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(id); + int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, type); if (ret != RET_SUCCESS) { ACCESSTOKEN_LOG_ERROR(LABEL, "token Id register fail"); continue; @@ -545,7 +547,7 @@ void AccessTokenInfoManager::ProcessNativeTokenInfos( } int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, - const std::string& appIDDesc, const HapPolicyParams& policy) + const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) { if (!DataValidator::IsAppIDDescValid(appIDDesc)) { ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u parm format error!", tokenID); @@ -564,7 +566,7 @@ int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, { Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); - infoPtr->Update(appIDDesc, policy); + infoPtr->Update(appIDDesc, apiVersion, policy); ACCESSTOKEN_LOG_INFO(LABEL, "token %{public}u bundle name %{public}s user %{public}d inst %{public}d update ok!", tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex()); @@ -610,10 +612,10 @@ void AccessTokenInfoManager::GetAllNativeTokenInfo( std::vector& nativeTokenInfosRes) { Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); - for (auto nativeTokenInner : nativeTokenInfoMap_) { + for (const auto& nativeTokenInner : nativeTokenInfoMap_) { std::shared_ptr nativeTokenInnerPtr = nativeTokenInner.second; if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote() - || nativeTokenInnerPtr->GetDcap().size() <= 0) { + || nativeTokenInnerPtr->GetDcap().empty()) { continue; } NativeTokenInfoForSync token; @@ -729,11 +731,12 @@ int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID } for (NativeTokenInfoForSync& nativeToken : nativeTokenInfoList) { + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(nativeToken.baseInfo.tokenID); if (!DataValidator::IsAplNumValid(nativeToken.baseInfo.apl) || nativeToken.baseInfo.ver != DEFAULT_TOKEN_VERSION || !DataValidator::IsProcessNameValid(nativeToken.baseInfo.processName) || - nativeToken.baseInfo.dcap.size() <= 0 || - AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(nativeToken.baseInfo.tokenID) != TOKEN_NATIVE) { + nativeToken.baseInfo.dcap.empty() || + (type != TOKEN_NATIVE && type != TOKEN_SHELL)) { ACCESSTOKEN_LOG_ERROR( LABEL, "device %{public}s token %{public}u is invalid.", ConstantCommon::EncryptDevId(deviceID).c_str(), nativeToken.baseInfo.tokenID); @@ -805,7 +808,7 @@ int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, Acces return RET_FAILED; } hapTokenInfoMap_.erase(mapID); - } else if (type == TOKEN_NATIVE) { + } else if ((type == TOKEN_NATIVE) || (type == TOKEN_SHELL)) { Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); if (nativeTokenInfoMap_.count(mapID) == 0) { ACCESSTOKEN_LOG_ERROR( @@ -822,8 +825,9 @@ int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, Acces AccessTokenID AccessTokenInfoManager::GetRemoteNativeTokenID(const std::string& deviceID, AccessTokenID tokenID) { - if (!DataValidator::IsDeviceIdValid(deviceID) - || AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) { + if ((!DataValidator::IsDeviceIdValid(deviceID)) || (tokenID == 0) || + ((AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_NATIVE) && + (AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(tokenID) != TOKEN_SHELL))) { ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", ConstantCommon::EncryptDevId(deviceID).c_str()); return 0; } @@ -949,10 +953,26 @@ void AccessTokenInfoManager::RefreshTokenInfoIfNeeded() }); } -void AccessTokenInfoManager::DumpTokenInfo(std::string& dumpInfo) +void AccessTokenInfoManager::DumpTokenInfo(AccessTokenID tokenID, std::string& dumpInfo) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); ACCESSTOKEN_LOG_INFO(LABEL, "get hapTokenInfo"); + if (tokenID != 0) { + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID); + if (type == TOKEN_HAP) { + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr != nullptr) { + infoPtr->ToString(dumpInfo); + } + } else if (type == TOKEN_NATIVE) { + std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); + if (infoPtr != nullptr) { + infoPtr->ToString(dumpInfo); + } + } else { + dumpInfo.append("invalid tokenId"); + } + return; + } Utils::UniqueReadGuard hapInfoGuard(this->hapTokenInfoLock_); for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp index d2240dfe5fc7127dde5b9c3cb1a4c59ad207fc20..1dc737bcdab4cbb9add47486c565b6e782750add 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -48,7 +48,7 @@ AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const s return 0; } ATokenTypeEnum tokeType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(remoteID); - if (tokeType != TOKEN_HAP && tokeType != TOKEN_NATIVE) { + if ((tokeType <= TOKEN_INVALID) || (tokeType >= TOKEN_TYPE_BUTT)) { ACCESSTOKEN_LOG_ERROR( LABEL, "token %{public}x type is invalid.", remoteID); return 0; diff --git a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp index 5c34e309626597044e03dcd3f00ad9baf9c06da9..195743792d721344371b3d994b314e8a19e723d5 100644 --- a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp @@ -26,6 +26,7 @@ namespace Security { namespace AccessToken { namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "HapTokenInfoInner"}; +static const std::string DEFAULT_DEVICEID = "0"; } HapTokenInfoInner::HapTokenInfoInner() : isRemote_(false) @@ -34,6 +35,7 @@ HapTokenInfoInner::HapTokenInfoInner() : isRemote_(false) tokenInfoBasic_.tokenID = 0; tokenInfoBasic_.tokenAttr = 0; tokenInfoBasic_.userID = 0; + tokenInfoBasic_.apiVersion = 0; tokenInfoBasic_.instIndex = 0; tokenInfoBasic_.dlpType = 0; tokenInfoBasic_.apl = APL_NORMAL; @@ -47,10 +49,11 @@ HapTokenInfoInner::HapTokenInfoInner(AccessTokenID id, tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; tokenInfoBasic_.tokenAttr = 0; tokenInfoBasic_.bundleName = info.bundleName; + tokenInfoBasic_.apiVersion = info.apiVersion; tokenInfoBasic_.instIndex = info.instIndex; tokenInfoBasic_.dlpType = info.dlpType; tokenInfoBasic_.appID = info.appIDDesc; - tokenInfoBasic_.deviceID = "0"; + tokenInfoBasic_.deviceID = DEFAULT_DEVICEID; tokenInfoBasic_.apl = policy.apl; permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, policy.permStateList); } @@ -68,9 +71,10 @@ HapTokenInfoInner::~HapTokenInfoInner() "tokenID: 0x%{public}x destruction", tokenInfoBasic_.tokenID); } -void HapTokenInfoInner::Update(const std::string& appIDDesc, const HapPolicyParams& policy) +void HapTokenInfoInner::Update(const std::string& appIDDesc, int32_t apiVersion, const HapPolicyParams& policy) { tokenInfoBasic_.appID = appIDDesc; + tokenInfoBasic_.apiVersion = apiVersion; tokenInfoBasic_.apl = policy.apl; if (permPolicySet_ == nullptr) { permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(tokenInfoBasic_.tokenID, @@ -92,6 +96,7 @@ void HapTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericVa outGenericValues.Put(FIELD_TOKEN_ID, (int)tokenInfoBasic_.tokenID); outGenericValues.Put(FIELD_USER_ID, tokenInfoBasic_.userID); outGenericValues.Put(FIELD_BUNDLE_NAME, tokenInfoBasic_.bundleName); + outGenericValues.Put(FIELD_API_VERSION, tokenInfoBasic_.apiVersion); outGenericValues.Put(FIELD_INST_INDEX, tokenInfoBasic_.instIndex); outGenericValues.Put(FIELD_DLP_TYPE, tokenInfoBasic_.dlpType); outGenericValues.Put(FIELD_APP_ID, tokenInfoBasic_.appID); @@ -111,6 +116,7 @@ int HapTokenInfoInner::RestoreHapTokenBasicInfo(const GenericValues& inGenericVa return RET_FAILED; } + tokenInfoBasic_.apiVersion = inGenericValues.GetInt(FIELD_API_VERSION); tokenInfoBasic_.instIndex = inGenericValues.GetInt(FIELD_INST_INDEX); tokenInfoBasic_.dlpType = inGenericValues.GetInt(FIELD_DLP_TYPE); tokenInfoBasic_.appID = inGenericValues.GetString(FIELD_APP_ID); @@ -147,7 +153,7 @@ int HapTokenInfoInner::RestoreHapTokenBasicInfo(const GenericValues& inGenericVa } int HapTokenInfoInner::RestoreHapTokenInfo(AccessTokenID tokenId, - GenericValues& tokenValue, + const GenericValues& tokenValue, const std::vector& permStateRes) { tokenInfoBasic_.tokenID = tokenId; diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp index 37cd2eee05c5f17a3a65fcb0b6d20c9a41d254db..aaa4527364d66fb97bd8270f859803aca1fc6579 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp @@ -95,8 +95,11 @@ void from_json(const nlohmann::json& j, std::shared_ptr& p if (j.find(JSON_TOKEN_ID) != j.end()) { native.tokenID = j.at(JSON_TOKEN_ID).get(); - if (native.tokenID == 0 || - AccessTokenIDManager::GetTokenIdTypeEnum(native.tokenID) != TOKEN_NATIVE) { + if (native.tokenID == 0) { + return; + } + ATokenTypeEnum type = AccessTokenIDManager::GetTokenIdTypeEnum(native.tokenID); + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { return; } } else { diff --git a/services/accesstokenmanager/test/BUILD.gn b/services/accesstokenmanager/test/BUILD.gn index 0dd6433ded8e186d1ee569b1cd73dd7153f91535..14a41d363b5a2bd5864f1c8a78d260684ba8a180 100644 --- a/services/accesstokenmanager/test/BUILD.gn +++ b/services/accesstokenmanager/test/BUILD.gn @@ -22,6 +22,7 @@ ohos_unittest("libaccesstoken_manager_service_standard_test") { include_dirs = [ "//base/security/access_token/frameworks/common/include", "//base/security/access_token/frameworks/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", "//base/security/access_token/interfaces/innerkits/nativetoken/include", "//base/security/access_token/services/accesstokenmanager/main/cpp/include/service", @@ -46,10 +47,9 @@ ohos_unittest("libaccesstoken_manager_service_standard_test") { cflags_cc += [ "-DSUPPORT_SANDBOX_APP" ] } + configs = [ "//base/security/access_token/config:coverage_flags" ] + deps = [ - "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", - "//base/security/access_token/frameworks/common:accesstoken_common_cxx", - "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", "//base/security/access_token/services/accesstokenmanager/:accesstoken_manager_service", "//base/security/access_token/services/common/database:accesstoken_database_cxx", diff --git a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp index 1f73623baf0c9edba8a6ee2f1baf3485e759de97..fbe8f922a2c8c95e24469d510bb711e4753eb80e 100644 --- a/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp +++ b/services/accesstokenmanager/test/unittest/cpp/src/accesstoken_info_manager_test.cpp @@ -35,6 +35,7 @@ static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManagerTest" }; +static constexpr int32_t DEFAULT_API_VERSION = 8; static PermissionDef g_infoManagerTestPermDef1 = { .permissionName = "open the door", .bundleName = "accesstoken_test", @@ -181,14 +182,14 @@ void AccessTokenInfoManagerTest::TearDown() HWTEST_F(AccessTokenInfoManagerTest, Init001, TestSize.Level1) { AccessTokenInfoManager::GetInstance().Init(); + AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + std::string dumpInfo; - AccessTokenInfoManager::GetInstance().DumpTokenInfo(dumpInfo); + AccessTokenInfoManager::GetInstance().DumpTokenInfo(getTokenId, dumpInfo); GTEST_LOG_(INFO) << "dump all:" << dumpInfo.c_str(); // delete test token - AccessTokenID getTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenID(g_infoManagerTestInfoParms.userID, - g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); - if (getTokenId != 0) { int ret = AccessTokenInfoManager::GetInstance().RemoveHapTokenInfo(getTokenId); ASSERT_EQ(RET_SUCCESS, ret); @@ -308,7 +309,7 @@ HWTEST_F(AccessTokenInfoManagerTest, UpdateHapToken001, TestSize.Level1) HapPolicyParams policy = g_infoManagerTestPolicyPrams; policy.apl = APL_SYSTEM_BASIC; ret = AccessTokenInfoManager::GetInstance().UpdateHapToken(tokenIdEx.tokenIdExStruct.tokenID, - std::string("updateAppId"), policy); + std::string("updateAppId"), DEFAULT_API_VERSION, policy); ASSERT_EQ(RET_SUCCESS, ret); GTEST_LOG_(INFO) << "update the hap token"; diff --git a/services/common/database/BUILD.gn b/services/common/database/BUILD.gn index 99beae0ed953f50e1d07186968c238b3e6bf47cb..a30e43a00d3a94edfde8cc765e266e5c1621222d 100644 --- a/services/common/database/BUILD.gn +++ b/services/common/database/BUILD.gn @@ -17,7 +17,10 @@ ohos_shared_library("accesstoken_database_cxx") { subsystem_name = "security" part_name = "access_token" - include_dirs = [ "include" ] + include_dirs = [ + "include", + "//base/security/access_token/frameworks/common/include", + ] sources = [ "src/generic_values.cpp", @@ -27,11 +30,9 @@ ohos_shared_library("accesstoken_database_cxx") { ] cflags_cc = [ "-DHILOG_ENABLE" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] - deps = [ - "//base/security/access_token/frameworks/common:accesstoken_common_cxx", - "//third_party/sqlite:sqlite", - ] + deps = [ "//third_party/sqlite:sqlite" ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] if (build_selinux) { diff --git a/services/common/database/include/field_const.h b/services/common/database/include/field_const.h index 7689a5272b191c530d2a77bf076645317bb10e8b..aaa185f0463d7ce07c0fa9025ddce5ef8eb8c43c 100644 --- a/services/common/database/include/field_const.h +++ b/services/common/database/include/field_const.h @@ -47,10 +47,6 @@ const std::string FIELD_GRANT_STATE = "grant_state"; const std::string FIELD_GRANT_FLAG = "grant_flag"; const std::string FIELD_GRANT_IS_GENERAL = "is_general"; -const std::string FIELD_ID = "id"; -const std::string FIELD_IS_REMOTE_DEVICE = "is_remote_device"; - -const std::string FIELD_VISITOR_ID = "visitor_id"; const std::string FIELD_OP_CODE = "op_code"; const std::string FIELD_STATUS = "status"; const std::string FIELD_TIMESTAMP = "timestamp"; @@ -61,6 +57,8 @@ const std::string FIELD_REJECT_COUNT = "reject_count"; const std::string FIELD_TIMESTAMP_BEGIN = "timestamp_begin"; const std::string FIELD_TIMESTAMP_END = "timestamp_end"; const std::string FIELD_FLAG = "flag"; + +const std::string FIELD_API_VERSION = "api_version"; } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/services/privacymanager/BUILD.gn b/services/privacymanager/BUILD.gn index bd0ccba5b19d5fb9a159ec6a428e846c4aa7ed47..f0587d915f3de4db822f5f72cae80782d3530ef4 100644 --- a/services/privacymanager/BUILD.gn +++ b/services/privacymanager/BUILD.gn @@ -37,6 +37,7 @@ if (is_standard_system) { "//base/security/access_token/interfaces/innerkits/privacy/include", "//base/security/access_token/services/common/database/include", "//third_party/json/include", + "//third_party/sqlite/include/", ] sources = [ @@ -53,13 +54,13 @@ if (is_standard_system) { "src/record/permission_record.cpp", "src/record/permission_record_manager.cpp", "src/record/permission_record_repository.cpp", - "src/record/permission_visitor.cpp", - "src/record/permission_visitor_repository.cpp", + "src/record/permission_used_record_cache.cpp", "src/service/privacy_manager_service.cpp", "src/service/privacy_manager_stub.cpp", ] cflags_cc = [ "-DHILOG_ENABLE" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] deps = [ "//base/security/access_token/frameworks/common:accesstoken_common_cxx", @@ -67,16 +68,13 @@ if (is_standard_system) { "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/services/common/database:accesstoken_database_cxx", "//base/security/access_token/services/privacymanager:privacy.rc", - "//third_party/sqlite:sqlite", ] external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", - "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr:samgr_proxy", ] } } diff --git a/services/privacymanager/include/active/active_status_callback_manager.h b/services/privacymanager/include/active/active_status_callback_manager.h index 853e91d3ed3b48e87baae9654e94e94dc2c66f0b..df6d801ae67a1b9e5c5f3488715a66fe9a9b06bd 100644 --- a/services/privacymanager/include/active/active_status_callback_manager.h +++ b/services/privacymanager/include/active/active_status_callback_manager.h @@ -49,7 +49,7 @@ public: int32_t RemoveCallback(const sptr& callback); bool NeedCalled(const std::vector& permList, const std::string& permName); void ExecuteCallbackAsync( - AccessTokenID tokenID, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType); + AccessTokenID tokenId, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType); private: std::mutex mutex_; diff --git a/services/privacymanager/include/database/data_translator.h b/services/privacymanager/include/database/data_translator.h index 60e07037ecad190e5b41d746ccaeaf8905ac67f6..488d887fff8c95759488ded9784fc850cb4939f5 100644 --- a/services/privacymanager/include/database/data_translator.h +++ b/services/privacymanager/include/database/data_translator.h @@ -28,7 +28,7 @@ namespace AccessToken { class DataTranslator final { public: static int32_t TranslationIntoGenericValues(const PermissionUsedRequest& request, - GenericValues& visitorGenericValues, GenericValues& andGenericValues, GenericValues& orGenericValues); + GenericValues& andGenericValues, GenericValues& orGenericValues); static int32_t TranslationGenericValuesIntoPermissionUsedRecord( const GenericValues& inGenericValues, PermissionUsedRecord& permissionRecord); }; diff --git a/services/privacymanager/include/database/permission_used_record_db.h b/services/privacymanager/include/database/permission_used_record_db.h index 059e0082aac7277038e93678e9b64272f580eb33..3ae7d5bb5db1838987d7717ac55b5a3cb56b3502 100644 --- a/services/privacymanager/include/database/permission_used_record_db.h +++ b/services/privacymanager/include/database/permission_used_record_db.h @@ -33,7 +33,6 @@ public: class PermissionUsedRecordDb : public SqliteHelper { public: enum DataType { - PERMISSION_VISITOR = 0, PERMISSION_RECORD, }; enum ExecuteResult { FAILURE = -1, SUCCESS }; @@ -41,13 +40,15 @@ public: ~PermissionUsedRecordDb() override; - int32_t Add(const DataType type, const std::vector& values); - int32_t Remove(const DataType type, const GenericValues& conditions); - int32_t Find(const DataType type, std::vector& results); - int32_t FindByConditions(const DataType type, const GenericValues& andConditions, + int32_t Add(DataType type, const std::vector& values); + int32_t Remove(DataType type, const GenericValues& conditions); + int32_t FindByConditions(DataType type, const GenericValues& andConditions, const GenericValues& orConditions, std::vector& results); - int32_t Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions); - int32_t RefreshAll(const DataType type, const std::vector& values); + int32_t Modify(DataType type, const GenericValues& modifyValues, const GenericValues& conditions); + void Count(DataType type, GenericValues& result); + int32_t DeleteExpireRecords(DataType type, const GenericValues& andConditions); + int32_t DeleteExcessiveRecords(DataType type, uint32_t excessiveSize); + int32_t GetDistinctValue(DataType type, const std::string& condition, std::vector& results); void OnCreate() override; void OnUpdate() override; @@ -59,20 +60,22 @@ private: std::map dataTypeToSqlTable_; OHOS::Utils::RWLock rwLock_; - int32_t CreatePermissionVisitorTable() const; int32_t CreatePermissionRecordTable() const; - std::string CreateInsertPrepareSqlCmd(const DataType type) const; + std::string CreateInsertPrepareSqlCmd(DataType type) const; std::string CreateDeletePrepareSqlCmd( - const DataType type, const std::vector& columnNames = std::vector()) const; - std::string CreateSelectPrepareSqlCmd(const DataType type) const; - std::string CreateSelectByConditionPrepareSqlCmd(const DataType type, + DataType type, const std::vector& columnNames = std::vector()) const; + std::string CreateSelectByConditionPrepareSqlCmd(DataType type, const std::vector& andColumns, const std::vector& orColumns) const; - std::string CreateUpdatePrepareSqlCmd(const DataType type, const std::vector& modifyColumns, + std::string CreateUpdatePrepareSqlCmd(DataType type, const std::vector& modifyColumns, const std::vector& conditionColumns) const; + std::string CreateCountPrepareSqlCmd(DataType type) const; + std::string CreateDeleteExpireRecordsPrepareSqlCmd(DataType type, + const std::vector& andColumns) const; + std::string CreateDeleteExcessiveRecordsPrepareSqlCmd(DataType type, uint32_t excessiveSize) const; + std::string CreateGetDistinctValue(DataType type, const std::string conditionColumns) const; private: - inline static const std::string PERMISSION_VISITOR_TABLE = "permission_visitor_table"; inline static const std::string PERMISSION_RECORD_TABLE = "permission_record_table"; inline static const std::string DATABASE_NAME = "permission_used_record.db"; inline static const std::string DATABASE_PATH = "/data/service/el1/public/access_token/"; diff --git a/services/privacymanager/include/record/permission_record.h b/services/privacymanager/include/record/permission_record.h index 3c61287dd8a03e461edb5d2f33384431055b9e98..f2c0abb0731e3b70c4b03e8408a1eeb80ba12f3c 100644 --- a/services/privacymanager/include/record/permission_record.h +++ b/services/privacymanager/include/record/permission_record.h @@ -22,7 +22,7 @@ namespace OHOS { namespace Security { namespace AccessToken { struct PermissionRecord { - int32_t visitorId = 0; + uint32_t tokenId = 0; int32_t opCode = 0; int32_t status = 0; int64_t timestamp = 0L; diff --git a/services/privacymanager/include/record/permission_record_manager.h b/services/privacymanager/include/record/permission_record_manager.h index bc8b417b278e29f23114e188d2935cdcfeb56921..ae3c6706768fa26b4d2a7577b61ca28a88ed94a2 100644 --- a/services/privacymanager/include/record/permission_record_manager.h +++ b/services/privacymanager/include/record/permission_record_manager.h @@ -17,15 +17,17 @@ #define PERMISSION_RECORD_MANAGER_H #include +#include #include #include "access_token.h" +#include "active_change_response_info.h" +#include "hap_token_info.h" #include "nocopyable.h" #include "on_permission_used_record_callback.h" #include "permission_record.h" #include "permission_used_request.h" #include "permission_used_result.h" -#include "permission_visitor.h" #include "rwlock.h" #include "thread_pool.h" @@ -40,40 +42,49 @@ public: void Init(); int32_t AddPermissionUsedRecord( - AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount); - void RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID); + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount); + void RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID); int32_t GetPermissionUsedRecords(const PermissionUsedRequest& request, PermissionUsedResult& result); int32_t GetPermissionUsedRecordsAsync( const PermissionUsedRequest& request, const sptr& callback); - std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName); - int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName); - int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName); + std::string DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName); + int32_t StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName); + int32_t StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName); int32_t RegisterPermActiveStatusCallback( std::vector& permList, const sptr& callback); int32_t UnRegisterPermActiveStatusCallback(const sptr& callback); - bool GetPermissionVisitor(AccessTokenID tokenID, PermissionVisitor& visitor); + + void CallbackExecute(AccessTokenID tokenId, const std::string& permissionName, int32_t status); private: PermissionRecordManager(); DISALLOW_COPY_AND_MOVE(PermissionRecordManager); - bool AddVisitor(AccessTokenID tokenID, int32_t& visitorId); - bool AddRecord(int32_t visitorId, const std::string& permissionName, int32_t successCount, int32_t failCount); - bool GetPermissionsRecord(int32_t visitorId, const std::string& permissionName, + bool GetLocalRecordTokenIdList(std::set& tokenIdList); + void AddRecord(const PermissionRecord& record); + bool GetPermissionRecord(AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount, PermissionRecord& record); - + bool CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord); void ExecuteDeletePermissionRecordTask(); int32_t DeletePermissionRecord(int32_t days); - bool GetRecordsFromDB(const PermissionUsedRequest& request, PermissionUsedResult& result); + bool GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result); bool GetRecords(int32_t flag, std::vector recordValues, BundleUsedRecord& bundleRecord, PermissionUsedResult& result); void UpdateRecords(int32_t flag, const PermissionUsedRecord& inBundleRecord, PermissionUsedRecord& outBundleRecord); - bool IsLocalDevice(const std::string& deviceId); + void AddRecordToStartList(const PermissionRecord& record); + bool GetRecordFromStartList(uint32_t tokenId, int32_t opCode, PermissionRecord& record); + void ResetRecord(PermissionRecord& record, int32_t status); + bool HasStarted(const PermissionRecord& record); + std::vector GetRecordsAndReset(uint32_t tokenId, int32_t status); + + std::string GetDeviceId(AccessTokenID tokenId); OHOS::ThreadPool deleteTaskWorker_; bool hasInited_; OHOS::Utils::RWLock rwLock_; + OHOS::Utils::RWLock startRecordListRWLock_; + std::vector startRecordList_; }; } // namespace AccessToken } // namespace Security diff --git a/services/privacymanager/include/record/permission_visitor_repository.h b/services/privacymanager/include/record/permission_record_node.h similarity index 53% rename from services/privacymanager/include/record/permission_visitor_repository.h rename to services/privacymanager/include/record/permission_record_node.h index 3fdc41159395fabb2b2c03614117bdeb94a4d94e..d56b3d80083cd0c2f0b297aad08ef2a5b9cbe9e0 100644 --- a/services/privacymanager/include/record/permission_visitor_repository.h +++ b/services/privacymanager/include/record/permission_record_node.h @@ -13,28 +13,23 @@ * limitations under the License. */ -#ifndef PERMISSION_VISITOR_REPOSITORY_H -#define PERMISSION_VISITOR_REPOSITORY_H - -#include -#include "generic_values.h" +#ifndef PERMISSION_UESD_RECORD_NODE_H +#define PERMISSION_UESD_RECORD_NODE_H +#include +#include "permission_record.h" +#include "rwlock.h" namespace OHOS { namespace Security { namespace AccessToken { -class PermissionVisitorRepository final { -public: - virtual ~PermissionVisitorRepository(); - PermissionVisitorRepository(); - - static PermissionVisitorRepository& GetInstance(); - - bool AddVisitorValues(const GenericValues& visitorValues); - bool FindVisitorValues(const GenericValues& andConditionValues, - const GenericValues& orConditionValues, std::vector& visitorValues); - bool RemoveVisitorValues(const GenericValues& conditionValues); +struct PermissionUsedRecordNode { + std::weak_ptr pre; + std::shared_ptr next; + PermissionRecord record; + + PermissionUsedRecordNode() = default; }; } // namespace AccessToken } // namespace Security } // namespace OHOS -#endif // PERMISSION_VISITOR_REPOSITORY_H +#endif // PERMISSION_UESD_RECORD_NODE_H diff --git a/services/privacymanager/include/record/permission_record_repository.h b/services/privacymanager/include/record/permission_record_repository.h index ffda94fb527f1ed4164f39216d641c3ff16bbaa9..1ca8caee907aa98710b5b9b1e38da2516c8b2542 100644 --- a/services/privacymanager/include/record/permission_record_repository.h +++ b/services/privacymanager/include/record/permission_record_repository.h @@ -33,6 +33,10 @@ public: bool FindRecordValues(const GenericValues& andConditionValues, const GenericValues& orConditionValues, std::vector& recordValues); bool RemoveRecordValues(const GenericValues& conditionValues); + bool GetAllRecordValuesByKey(const std::string& condition, std::vector& resultValues); + void CountRecordValues(GenericValues& resultValues); + bool DeleteExpireRecordsValues(const GenericValues& andConditions); + bool DeleteExcessiveSizeRecordValues(uint32_t excessiveSize); }; } // namespace AccessToken } // namespace Security diff --git a/services/privacymanager/include/record/permission_used_record_cache.h b/services/privacymanager/include/record/permission_used_record_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..272bef4716fc953a84c376292c4e21fbcf296d72 --- /dev/null +++ b/services/privacymanager/include/record/permission_used_record_cache.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PERMISSION_USED_RECORD_CACHE_H +#define PERMISSION_USED_RECORD_CACHE_H + +#include +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "nocopyable.h" +#include "permission_record.h" +#include "permission_record_node.h" +#include "rwlock.h" +#include "thread_pool.h" +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermissionUsedRecordCache { +public: + static PermissionUsedRecordCache& GetInstance(); + void AddRecordToBuffer(PermissionRecord& record); + void MergeRecord(PermissionRecord& record, std::shared_ptr curFindMergePos); + void AddToPersistQueue(const std::shared_ptr persistPendingBufferHead); + void ExecuteReadRecordBufferTask(); + int32_t PersistPendingRecords(); + void GetPersistPendingRecordsAndReset(); + int32_t RemoveRecords(const AccessTokenID tokenId); + void RemoveRecordsFromPersistPendingBufferQueue(const AccessTokenID tokenId, + std::shared_ptr persistPendingBufferHead, + std::shared_ptr persistPendingBufferEnd); + void GetRecords(const std::vector& permissionList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues); + void GetRecordsFromPersistPendingBufferQueue(const std::set& opCodeList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues); + bool RecordCompare(const AccessTokenID tokenId, const std::set& opCodeList, + const GenericValues& andConditionValues, const PermissionRecord& record); + void FindTokenIdList(std::set& tokenIdList); + void TransferToOpcode(std::set& opCodeList, + const std::vector& permissionList); + void ResetRecordBuffer(const int32_t remainCount, + std::shared_ptr& persistPendingBufferEnd); + void AddRecordNode(const PermissionRecord& record); + void DeleteRecordNode(std::shared_ptr deleteRecordNode); + +private: + int32_t readableSize_ = 0; + std::shared_ptr recordBufferHead_ = std::make_shared(); + std::shared_ptr curRecordBufferPos_ = recordBufferHead_; + std::vector> persistPendingBufferQueue_; + int64_t nextPersistTimestamp_ = 0L; + const static int32_t INTERVAL = 60 * 15; + const static int32_t MAX_PERSIST_SIZE = 100; + int32_t persistIsRunning_ = 0; + OHOS::Utils::RWLock cacheLock_; + OHOS::ThreadPool readRecordBufferTaskWorker_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PERMISSION_USED_RECORD_CACHE_H diff --git a/services/privacymanager/include/service/privacy_manager_service.h b/services/privacymanager/include/service/privacy_manager_service.h index 116249c7fb4b76e13dea65d9f943ed16bb40d170..ce276d297ecefa5984f0e7b0cedd97a9d6908e6a 100644 --- a/services/privacymanager/include/service/privacy_manager_service.h +++ b/services/privacymanager/include/service/privacy_manager_service.h @@ -37,15 +37,15 @@ public: void OnStop() override; int32_t AddPermissionUsedRecord( - AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) override; - int32_t StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) override; - int32_t StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) override; - int32_t RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) override; + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount) override; + int32_t StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; + int32_t StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) override; + int32_t RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) override; int32_t GetPermissionUsedRecords( const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) override; int32_t GetPermissionUsedRecords( const PermissionUsedRequestParcel& request, const sptr& callback) override; - std::string DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) override; + std::string DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) override; int32_t RegisterPermActiveStatusCallback( std::vector& permList, const sptr& callback) override; int32_t UnRegisterPermActiveStatusCallback(const sptr& callback) override; diff --git a/services/privacymanager/src/active/active_status_callback_manager.cpp b/services/privacymanager/src/active/active_status_callback_manager.cpp index abaa1dbb325e1573226a32d63b69e970f47afdeb..b14bcd6e249557823696e4d66e9926cdad95368d 100644 --- a/services/privacymanager/src/active/active_status_callback_manager.cpp +++ b/services/privacymanager/src/active/active_status_callback_manager.cpp @@ -112,7 +112,7 @@ bool ActiveStatusCallbackManager::NeedCalled(const std::vector& per } void ActiveStatusCallbackManager::ExecuteCallbackAsync( - AccessTokenID tokenID, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType) + AccessTokenID tokenId, const std::string& permName, const std::string& deviceId, ActiveChangeType changeType) { ACCESSTOKEN_LOG_INFO(LABEL, "entry"); @@ -122,7 +122,7 @@ void ActiveStatusCallbackManager::ExecuteCallbackAsync( for (auto it = callbackDataList_.begin(); it != callbackDataList_.end(); ++it) { std::vector permList = (*it).permList_; if (!NeedCalled(permList, permName)) { - ACCESSTOKEN_LOG_INFO(LABEL, "tokenID %{public}u, permName %{public}s", tokenID, permName.c_str()); + ACCESSTOKEN_LOG_INFO(LABEL, "tokenId %{public}u, permName %{public}s", tokenId, permName.c_str()); continue; } auto callback = iface_cast((*it).callbackObject_); @@ -130,7 +130,7 @@ void ActiveStatusCallbackManager::ExecuteCallbackAsync( ActiveChangeResponse resInfo; resInfo.type = changeType; resInfo.permissionName = permName; - resInfo.tokenID = tokenID; + resInfo.tokenID = tokenId; resInfo.deviceId = deviceId; ACCESSTOKEN_LOG_INFO(LABEL, "callback excute changeType %{public}d", changeType); callback->ActiveStatusChangeCallback(resInfo); diff --git a/services/privacymanager/src/database/data_translator.cpp b/services/privacymanager/src/database/data_translator.cpp index 514fbe3146521253aae0544d79496bd5346fd0a4..27753200fbf65e5bedc50cfe939a1f340f8d5d21 100644 --- a/services/privacymanager/src/database/data_translator.cpp +++ b/services/privacymanager/src/database/data_translator.cpp @@ -23,7 +23,7 @@ namespace OHOS { namespace Security { namespace AccessToken { int32_t DataTranslator::TranslationIntoGenericValues(const PermissionUsedRequest& request, - GenericValues& visitorGenericValues, GenericValues& andGenericValues, GenericValues& orGenericValues) + GenericValues& andGenericValues, GenericValues& orGenericValues) { int64_t begin = request.beginTimeMillis; int64_t end = request.endTimeMillis; @@ -48,17 +48,6 @@ int32_t DataTranslator::TranslationIntoGenericValues(const PermissionUsedRequest andGenericValues.Put(FIELD_TIMESTAMP_END, end); } - if (!request.deviceId.empty()) { - visitorGenericValues.Put(FIELD_DEVICE_ID, request.deviceId); - } - if (!request.bundleName.empty()) { - visitorGenericValues.Put(FIELD_BUNDLE_NAME, request.bundleName); - } - - if (request.tokenId != 0) { - visitorGenericValues.Put(FIELD_TOKEN_ID, (int32_t)request.tokenId); - } - for (const auto& perm : request.permissionList) { int32_t opCode; if (Constant::TransferPermissionToOpcode(perm, opCode)) { diff --git a/services/privacymanager/src/database/permission_used_record_db.cpp b/services/privacymanager/src/database/permission_used_record_db.cpp index 60b82be4b1912f29cf22533fb71733ab3e29d17c..1e216b7a5f085f75af83268494ee0ede684bee33 100644 --- a/services/privacymanager/src/database/permission_used_record_db.cpp +++ b/services/privacymanager/src/database/permission_used_record_db.cpp @@ -16,6 +16,7 @@ #include "permission_used_record_db.h" #include "accesstoken_log.h" +#include "constant.h" #include "field_const.h" namespace OHOS { @@ -25,6 +26,7 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionUsedRecordDb" }; +static const std::string FIELD_COUNT_NUMBER = "count"; } PermissionUsedRecordDb& PermissionUsedRecordDb::GetInstance() @@ -41,7 +43,6 @@ PermissionUsedRecordDb::~PermissionUsedRecordDb() void PermissionUsedRecordDb::OnCreate() { ACCESSTOKEN_LOG_INFO(LABEL, "Entry"); - CreatePermissionVisitorTable(); CreatePermissionRecordTable(); } @@ -52,21 +53,10 @@ void PermissionUsedRecordDb::OnUpdate() PermissionUsedRecordDb::PermissionUsedRecordDb() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATABASE_VERSION) { - SqliteTable permissionVisorTable; - permissionVisorTable.tableName_ = PERMISSION_VISITOR_TABLE; - permissionVisorTable.tableColumnNames_ = { - FIELD_ID, - FIELD_TOKEN_ID, - FIELD_IS_REMOTE_DEVICE, - FIELD_DEVICE_ID, - FIELD_USER_ID, - FIELD_BUNDLE_NAME - }; - SqliteTable permissionRecordTable; permissionRecordTable.tableName_ = PERMISSION_RECORD_TABLE; permissionRecordTable.tableColumnNames_ = { - FIELD_VISITOR_ID, + FIELD_TOKEN_ID, FIELD_OP_CODE, FIELD_STATUS, FIELD_TIMESTAMP, @@ -76,13 +66,12 @@ PermissionUsedRecordDb::PermissionUsedRecordDb() : SqliteHelper(DATABASE_NAME, D }; dataTypeToSqlTable_ = { - {PERMISSION_VISITOR, permissionVisorTable}, {PERMISSION_RECORD, permissionRecordTable}, }; Open(); } -int32_t PermissionUsedRecordDb::Add(const DataType type, const std::vector& values) +int32_t PermissionUsedRecordDb::Add(DataType type, const std::vector& values) { OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); std::string prepareSql = CreateInsertPrepareSqlCmd(type); @@ -111,7 +100,7 @@ int32_t PermissionUsedRecordDb::Add(const DataType type, const std::vector lock(this->rwLock_); std::vector columnNames = conditions.GetAllKeys(); @@ -125,7 +114,7 @@ int32_t PermissionUsedRecordDb::Remove(const DataType type, const GenericValues& } int32_t PermissionUsedRecordDb::Modify( - const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) + DataType type, const GenericValues& modifyValues, const GenericValues& conditions) { OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); std::vector modifyColumns = modifyValues.GetAllKeys(); @@ -142,11 +131,22 @@ int32_t PermissionUsedRecordDb::Modify( return (ret == Statement::State::DONE) ? SUCCESS : FAILURE; } -int32_t PermissionUsedRecordDb::Find(const DataType type, std::vector& results) +int32_t PermissionUsedRecordDb::FindByConditions(DataType type, const GenericValues& andConditions, + const GenericValues& orConditions, std::vector& results) { OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); - std::string prepareSql = CreateSelectPrepareSqlCmd(type); + std::vector andColumns = andConditions.GetAllKeys(); + std::vector orColumns = orConditions.GetAllKeys(); + std::string prepareSql = CreateSelectByConditionPrepareSqlCmd(type, andColumns, orColumns); auto statement = Prepare(prepareSql); + + for (const auto& columnName : andColumns) { + statement.Bind(columnName, andConditions.Get(columnName)); + } + for (const auto& columnName : orColumns) { + statement.Bind(columnName, orConditions.Get(columnName)); + } + while (statement.Step() == Statement::State::ROW) { int32_t columnCount = statement.GetColumnCount(); GenericValues value; @@ -162,30 +162,20 @@ int32_t PermissionUsedRecordDb::Find(const DataType type, std::vector& results) +int32_t PermissionUsedRecordDb::GetDistinctValue(DataType type, + const std::string& condition, std::vector& results) { OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); - std::vector andColumns = andConditions.GetAllKeys(); - std::vector orColumns = orConditions.GetAllKeys(); - std::string prepareSql = CreateSelectByConditionPrepareSqlCmd(type, andColumns, orColumns); - auto statement = Prepare(prepareSql); - - for (const auto& columnName : andColumns) { - statement.Bind(columnName, andConditions.Get(columnName)); - } - for (const auto& columnName : orColumns) { - statement.Bind(columnName, orConditions.Get(columnName)); - } - + std::string getDistinctValueSql = CreateGetDistinctValue(type, condition); + auto statement = Prepare(getDistinctValueSql); while (statement.Step() == Statement::State::ROW) { int32_t columnCount = statement.GetColumnCount(); GenericValues value; for (int32_t i = 0; i < columnCount; i++) { - if (statement.GetColumnName(i) == FIELD_TIMESTAMP || statement.GetColumnName(i) == FIELD_ACCESS_DURATION) { - value.Put(statement.GetColumnName(i), statement.GetValue(i, true)); - } else { + if (statement.GetColumnName(i) == FIELD_TOKEN_ID) { value.Put(statement.GetColumnName(i), statement.GetValue(i, false)); + } else if (statement.GetColumnName(i) == FIELD_DEVICE_ID) { + value.Put(statement.GetColumnName(i), statement.GetColumnString(i)); } } results.emplace_back(value); @@ -193,39 +183,47 @@ int32_t PermissionUsedRecordDb::FindByConditions(const DataType type, const Gene return SUCCESS; } -int32_t PermissionUsedRecordDb::RefreshAll(const DataType type, const std::vector& values) +void PermissionUsedRecordDb::Count(DataType type, GenericValues& result) { OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); - std::string deleteSql = CreateDeletePrepareSqlCmd(type); - std::string insertSql = CreateInsertPrepareSqlCmd(type); - auto deleteStatement = Prepare(deleteSql); - auto insertStatement = Prepare(insertSql); - BeginTransaction(); - bool canCommit = deleteStatement.Step() == Statement::State::DONE; - for (const auto& value : values) { - std::vector columnNames = value.GetAllKeys(); - for (const auto& columnName : columnNames) { - insertStatement.Bind(columnName, value.Get(columnName)); + std::string countSql = CreateCountPrepareSqlCmd(type); + auto countStatement = Prepare(countSql); + if (countStatement.Step() == Statement::State::ROW) { + int32_t column = 0; + result.Put(FIELD_COUNT_NUMBER, countStatement.GetValue(column, true)); + } +} + +int32_t PermissionUsedRecordDb::DeleteExpireRecords(DataType type, + const GenericValues& andConditions) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::vector andColumns = andConditions.GetAllKeys(); + if (!andColumns.empty()) { + std::string deleteExpireSql = CreateDeleteExpireRecordsPrepareSqlCmd(type, andColumns); + auto deleteExpireStatement = Prepare(deleteExpireSql); + for (const auto& columnName : andColumns) { + deleteExpireStatement.Bind(columnName, andConditions.Get(columnName)); } - int32_t ret = insertStatement.Step(); - if (ret != Statement::State::DONE) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "insert failed, errorMsg: %{public}s", SpitError().c_str()); - canCommit = false; + if (deleteExpireStatement.Step() != Statement::State::DONE) { + return FAILURE; } - insertStatement.Reset(); } - if (!canCommit) { - ACCESSTOKEN_LOG_ERROR(LABEL, "rollback transaction."); - RollbackTransaction(); + return SUCCESS; +} + +int32_t PermissionUsedRecordDb::DeleteExcessiveRecords(DataType type, uint32_t excessiveSize) +{ + OHOS::Utils::UniqueWriteGuard lock(this->rwLock_); + std::string deleteExcessiveSql = CreateDeleteExcessiveRecordsPrepareSqlCmd(type, excessiveSize); + auto deleteExcessiveStatement = Prepare(deleteExcessiveSql); + if (deleteExcessiveStatement.Step() != Statement::State::DONE) { return FAILURE; } - ACCESSTOKEN_LOG_INFO(LABEL, "commit transaction."); - CommitTransaction(); return SUCCESS; } -std::string PermissionUsedRecordDb::CreateInsertPrepareSqlCmd(const DataType type) const +std::string PermissionUsedRecordDb::CreateInsertPrepareSqlCmd(DataType type) const { auto it = dataTypeToSqlTable_.find(type); if (it == dataTypeToSqlTable_.end()) { @@ -245,7 +243,7 @@ std::string PermissionUsedRecordDb::CreateInsertPrepareSqlCmd(const DataType typ } std::string PermissionUsedRecordDb::CreateDeletePrepareSqlCmd( - const DataType type, const std::vector& columnNames) const + DataType type, const std::vector& columnNames) const { auto it = dataTypeToSqlTable_.find(type); if (it == dataTypeToSqlTable_.end()) { @@ -259,7 +257,7 @@ std::string PermissionUsedRecordDb::CreateDeletePrepareSqlCmd( return sql; } -std::string PermissionUsedRecordDb::CreateUpdatePrepareSqlCmd(const DataType type, +std::string PermissionUsedRecordDb::CreateUpdatePrepareSqlCmd(DataType type, const std::vector& modifyColumns, const std::vector& conditionColumns) const { if (modifyColumns.empty()) { @@ -291,17 +289,7 @@ std::string PermissionUsedRecordDb::CreateUpdatePrepareSqlCmd(const DataType typ return sql; } -std::string PermissionUsedRecordDb::CreateSelectPrepareSqlCmd(const DataType type) const -{ - auto it = dataTypeToSqlTable_.find(type); - if (it == dataTypeToSqlTable_.end()) { - return std::string(); - } - std::string sql = "select * from " + it->second.tableName_; - return sql; -} - -std::string PermissionUsedRecordDb::CreateSelectByConditionPrepareSqlCmd(const DataType type, +std::string PermissionUsedRecordDb::CreateSelectByConditionPrepareSqlCmd(DataType type, const std::vector& andColumns, const std::vector& orColumns) const { auto it = dataTypeToSqlTable_.find(type); @@ -322,7 +310,7 @@ std::string PermissionUsedRecordDb::CreateSelectByConditionPrepareSqlCmd(const D sql.append(andColName + "=:" + andColName); } } - if (orColumns.size() > 0) { + if (!orColumns.empty()) { sql.append(" and ("); for (const auto& orColName : orColumns) { if (orColName.find(FIELD_OP_CODE) != std::string::npos) { @@ -335,22 +323,67 @@ std::string PermissionUsedRecordDb::CreateSelectByConditionPrepareSqlCmd(const D return sql; } -int32_t PermissionUsedRecordDb::CreatePermissionVisitorTable() const +std::string PermissionUsedRecordDb::CreateCountPrepareSqlCmd(DataType type) const { - auto it = dataTypeToSqlTable_.find(DataType::PERMISSION_VISITOR); + auto it = dataTypeToSqlTable_.find(type); if (it == dataTypeToSqlTable_.end()) { - return FAILURE; + return std::string(); } - std::string sql = "create table if not exists "; - sql.append(it->second.tableName_ + " (") - .append(FIELD_ID + " integer PRIMARY KEY autoincrement not null,") - .append(FIELD_TOKEN_ID + " integer not null,") - .append(FIELD_IS_REMOTE_DEVICE + " integer not null,") - .append(FIELD_DEVICE_ID + " text not null,") - .append(FIELD_USER_ID + " integer not null,") - .append(FIELD_BUNDLE_NAME + " text not null") - .append(")"); - return ExecuteSql(sql); + std::string sql = "select count(*) from " + it->second.tableName_; + return sql; +} + +std::string PermissionUsedRecordDb::CreateDeleteExpireRecordsPrepareSqlCmd(DataType type, + const std::vector& andColumns) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where "; + sql.append(FIELD_TIMESTAMP + " in (select "); + sql.append(FIELD_TIMESTAMP + " from " + it->second.tableName_ + " where 1 = 1"); + for (const auto& andColName : andColumns) { + if (andColName == FIELD_TIMESTAMP_BEGIN) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " >=:" + andColName); + } else if (andColName == FIELD_TIMESTAMP_END) { + sql.append(" and "); + sql.append(FIELD_TIMESTAMP + " <=:" + andColName); + } else { + sql.append(" and "); + sql.append(andColName + "=:" + andColName); + } + } + sql.append(" )"); + return sql; +} + +std::string PermissionUsedRecordDb::CreateDeleteExcessiveRecordsPrepareSqlCmd(DataType type, + uint32_t excessiveSize) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "delete from " + it->second.tableName_ + " where "; + sql.append(FIELD_TIMESTAMP + " in (select "); + sql.append(FIELD_TIMESTAMP + " from " + it->second.tableName_ + " order by "); + sql.append(FIELD_TIMESTAMP + " limit "); + sql.append(std::to_string(excessiveSize) + " )"); + return sql; +} + +std::string PermissionUsedRecordDb::CreateGetDistinctValue(DataType type, + const std::string conditionColumns) const +{ + auto it = dataTypeToSqlTable_.find(type); + if (it == dataTypeToSqlTable_.end()) { + return std::string(); + } + std::string sql = "select distinct "; + sql.append(conditionColumns + " from "+ it->second.tableName_); + return sql; } int32_t PermissionUsedRecordDb::CreatePermissionRecordTable() const @@ -361,14 +394,14 @@ int32_t PermissionUsedRecordDb::CreatePermissionRecordTable() const } std::string sql = "create table if not exists "; sql.append(it->second.tableName_ + " (") - .append(FIELD_VISITOR_ID + " integer not null,") + .append(FIELD_TOKEN_ID + " integer not null,") .append(FIELD_OP_CODE + " integer not null,") .append(FIELD_STATUS + " integer not null,") .append(FIELD_TIMESTAMP + " integer not null,") .append(FIELD_ACCESS_DURATION + " integer not null,") .append(FIELD_ACCESS_COUNT + " integer not null,") .append(FIELD_REJECT_COUNT + " integer not null,") - .append("primary key(" + FIELD_VISITOR_ID) + .append("primary key(" + FIELD_TOKEN_ID) .append("," + FIELD_OP_CODE) .append("," + FIELD_STATUS) .append("," + FIELD_TIMESTAMP) diff --git a/services/privacymanager/src/record/permission_record.cpp b/services/privacymanager/src/record/permission_record.cpp index 48906ef039a886205b5e75cfe238ebb30bb0ea8c..643ec0f84f5bd7c8e4a511bf56158d821aa9a760 100644 --- a/services/privacymanager/src/record/permission_record.cpp +++ b/services/privacymanager/src/record/permission_record.cpp @@ -21,7 +21,7 @@ namespace Security { namespace AccessToken { void PermissionRecord::TranslationIntoGenericValues(const PermissionRecord& record, GenericValues& values) { - values.Put(FIELD_VISITOR_ID, record.visitorId); + values.Put(FIELD_TOKEN_ID, (int32_t)record.tokenId); values.Put(FIELD_OP_CODE, record.opCode); values.Put(FIELD_STATUS, record.status); values.Put(FIELD_TIMESTAMP, record.timestamp); @@ -32,7 +32,7 @@ void PermissionRecord::TranslationIntoGenericValues(const PermissionRecord& reco void PermissionRecord::TranslationIntoPermissionRecord(const GenericValues& values, PermissionRecord& record) { - record.visitorId = values.GetInt(FIELD_VISITOR_ID); + record.tokenId = values.GetInt(FIELD_TOKEN_ID); record.opCode = values.GetInt(FIELD_OP_CODE); record.status = values.GetInt(FIELD_STATUS); record.timestamp = values.GetInt64(FIELD_TIMESTAMP); diff --git a/services/privacymanager/src/record/permission_record_manager.cpp b/services/privacymanager/src/record/permission_record_manager.cpp index 59a4036c938a70911bd614ea856655d103a88401..37514e9f5700b7eae12d3405ef18d2ddc47c53a2 100644 --- a/services/privacymanager/src/record/permission_record_manager.cpp +++ b/services/privacymanager/src/record/permission_record_manager.cpp @@ -17,13 +17,13 @@ #include "accesstoken_kit.h" #include "accesstoken_log.h" +#include "active_status_callback_manager.h" #include "constant.h" #include "constant_common.h" #include "data_translator.h" #include "field_const.h" #include "permission_record_repository.h" -#include "permission_visitor_repository.h" -#include "active_status_callback_manager.h" +#include "permission_used_record_cache.h" #include "time_util.h" #include "to_string.h" @@ -34,6 +34,8 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionRecordManager" }; +static const std::string DEFAULT_DEVICEID = "0"; +static const std::string FIELD_COUNT_NUMBER = "count"; } PermissionRecordManager& PermissionRecordManager::GetInstance() { @@ -52,188 +54,88 @@ PermissionRecordManager::~PermissionRecordManager() hasInited_ = false; } -bool PermissionRecordManager::AddVisitor(AccessTokenID tokenID, int32_t& visitorId) +void PermissionRecordManager::AddRecord(const PermissionRecord& record) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); - PermissionVisitor visitor; - if (!GetPermissionVisitor(tokenID, visitor)) { - return false; - } - - GenericValues visitorValues; - GenericValues nullValues; - std::vector resultValues; - PermissionVisitor::TranslationIntoGenericValues(visitor, visitorValues); - if (!PermissionVisitorRepository::GetInstance().FindVisitorValues(visitorValues, nullValues, resultValues)) { - return false; - } - if (resultValues.empty()) { - if (!PermissionVisitorRepository::GetInstance().AddVisitorValues(visitorValues)) { - return false; - } - if (!PermissionVisitorRepository::GetInstance().FindVisitorValues(visitorValues, nullValues, resultValues)) { - return false; - } - } - PermissionVisitor::TranslationIntoPermissionVisitor(resultValues[0], visitor); - visitorId = visitor.id; - return true; + Utils::UniqueWriteGuard lk(this->rwLock_); + PermissionUsedRecordCache::GetInstance().AddRecordToBuffer(const_cast(record)); } -bool PermissionRecordManager::GetPermissionVisitor(AccessTokenID tokenID, PermissionVisitor& visitor) +bool PermissionRecordManager::GetPermissionRecord(AccessTokenID tokenId, const std::string& permissionName, + int32_t successCount, int32_t failCount, PermissionRecord& record) { HapTokenInfo tokenInfo; - if (AccessTokenKit::GetHapTokenInfo(tokenID, tokenInfo) != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "GetHapTokenInfo fail"); + if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId); return false; } - visitor.isRemoteDevice = true; - visitor.userId = tokenInfo.userID; - visitor.bundleName = tokenInfo.bundleName; - if (IsLocalDevice(tokenInfo.deviceID)) { - visitor.deviceId = ConstantCommon::GetLocalDeviceId(); - visitor.isRemoteDevice = false; - visitor.tokenId = tokenID; - } - return true; -} - -bool PermissionRecordManager::AddRecord( - int32_t visitorId, const std::string& permissionName, int32_t successCount, int32_t failCount) -{ - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); - PermissionRecord record; - if (!GetPermissionsRecord(visitorId, permissionName, successCount, failCount, record)) { - return false; - } - - GenericValues nullValues; - GenericValues recordValues; - std::vector insertValues; - std::vector findValues; - PermissionRecord::TranslationIntoGenericValues(record, recordValues); - - int64_t insertTimestamp = record.timestamp; - int64_t insertAccessDuration = record.accessDuration; - int32_t insertAccessCount = record.accessCount; - int32_t insertRejectCount = record.rejectCount; - recordValues.Remove(FIELD_TIMESTAMP); - recordValues.Remove(FIELD_ACCESS_DURATION); - recordValues.Remove(FIELD_ACCESS_COUNT); - recordValues.Remove(FIELD_REJECT_COUNT); - if (!PermissionRecordRepository::GetInstance().FindRecordValues(recordValues, nullValues, findValues)) { - return false; - } - - recordValues.Put(FIELD_TIMESTAMP, insertTimestamp); - recordValues.Put(FIELD_ACCESS_DURATION, insertAccessDuration); - recordValues.Put(FIELD_ACCESS_COUNT, insertAccessCount); - recordValues.Put(FIELD_REJECT_COUNT, insertRejectCount); - for (const auto& rec : findValues) { - if (insertTimestamp - rec.GetInt64(FIELD_TIMESTAMP) < Constant::PRECISE) { - insertAccessDuration += rec.GetInt64(FIELD_ACCESS_DURATION); - insertAccessCount += rec.GetInt(FIELD_ACCESS_COUNT); - insertRejectCount += rec.GetInt(FIELD_REJECT_COUNT); - recordValues.Remove(FIELD_ACCESS_DURATION); - recordValues.Remove(FIELD_ACCESS_COUNT); - recordValues.Remove(FIELD_REJECT_COUNT); - - recordValues.Put(FIELD_ACCESS_DURATION, insertAccessDuration); - recordValues.Put(FIELD_ACCESS_COUNT, insertAccessCount); - recordValues.Put(FIELD_REJECT_COUNT, insertRejectCount); - - if (!PermissionRecordRepository::GetInstance().RemoveRecordValues(rec)) { - return false; - } - break; - } - } - insertValues.emplace_back(recordValues); - return PermissionRecordRepository::GetInstance().AddRecordValues(insertValues); -} - -bool PermissionRecordManager::GetPermissionsRecord(int32_t visitorId, const std::string& permissionName, - int32_t successCount, int32_t failCount, PermissionRecord& record) -{ int32_t opCode; if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to TransferPermissionToOpcode"); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission(%{public}s)", permissionName.c_str()); return false; } if (successCount == 0 && failCount == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "successCount and failCount are both zero"); - return false; + record.status = PERM_INACTIVE; + } else { + record.status = PERM_ACTIVE_IN_FOREGROUND; } - record.visitorId = visitorId; + record.tokenId = tokenId; record.accessCount = successCount; record.rejectCount = failCount; record.opCode = opCode; - record.status = 0; // get isForeground by uid lockscreen record.timestamp = TimeUtil::GetCurrentTimestamp(); record.accessDuration = 0; + ACCESSTOKEN_LOG_DEBUG(LABEL, "record status: %{public}d", record.status); return true; } -int32_t PermissionRecordManager::AddPermissionUsedRecord(AccessTokenID tokenID, const std::string& permissionName, +int32_t PermissionRecordManager::AddPermissionUsedRecord(AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenId: %{public}x, permissionName: %{public}s", - tokenID, permissionName.c_str()); ExecuteDeletePermissionRecordTask(); - if (AccessTokenKit::GetTokenTypeFlag(tokenID) != TOKEN_HAP) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Invalid token type"); - return Constant::SUCCESS; - } - - Utils::UniqueWriteGuard lk(this->rwLock_); - int32_t visitorId; - if (!AddVisitor(tokenID, visitorId)) { + PermissionRecord record; + if (!GetPermissionRecord(tokenId, permissionName, successCount, failCount, record)) { return Constant::FAILURE; } - if (!AddRecord(visitorId, permissionName, successCount, failCount)) { + + if (record.status == PERM_INACTIVE) { return Constant::FAILURE; } + + AddRecord(record); return Constant::SUCCESS; } -void PermissionRecordManager::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) +void PermissionRecordManager::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenId: %{public}x", tokenID); - - Utils::UniqueWriteGuard lk(this->rwLock_); - PermissionVisitor visitor; - if (!GetPermissionVisitor(tokenID, visitor) && deviceID.empty()) { + if (tokenId == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId is 0"); return; } - if (!deviceID.empty()) { - visitor.deviceId = deviceID; - } - GenericValues nullValues; - GenericValues visitorValues; - std::vector findVisitorValues; - PermissionVisitor::TranslationIntoGenericValues(visitor, visitorValues); - if (!PermissionVisitorRepository::GetInstance().FindVisitorValues(visitorValues, nullValues, findVisitorValues)) { + // only support remove by tokenId(local) + std::string device = GetDeviceId(tokenId); + if (device.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId = %{public}d", tokenId); return; } - for (const auto& visitor : findVisitorValues) { - GenericValues record; - record.Put(FIELD_VISITOR_ID, visitor.GetInt(FIELD_ID)); - PermissionRecordRepository::GetInstance().RemoveRecordValues(record); + if (!deviceID.empty() && device != deviceID) { + ACCESSTOKEN_LOG_ERROR(LABEL, "deviceID mismatch"); + return; } - PermissionVisitorRepository::GetInstance().RemoveVisitorValues(visitorValues); + + Utils::UniqueWriteGuard lk(this->rwLock_); + PermissionUsedRecordCache::GetInstance().RemoveRecords(tokenId); // remove from cache and database } int32_t PermissionRecordManager::GetPermissionUsedRecords( const PermissionUsedRequest& request, PermissionUsedResult& result) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); ExecuteDeletePermissionRecordTask(); - if (!GetRecordsFromDB(request, result)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to GetRecordsFromDB"); + if (!request.isRemote && !GetRecordsFromLocalDB(request, result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to GetRecordsFromLocalDB"); return Constant::FAILURE; } return Constant::SUCCESS; @@ -242,7 +144,6 @@ int32_t PermissionRecordManager::GetPermissionUsedRecords( int32_t PermissionRecordManager::GetPermissionUsedRecordsAsync( const PermissionUsedRequest& request, const sptr& callback) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); auto task = [request, callback]() { ACCESSTOKEN_LOG_INFO(LABEL, "GetPermissionUsedRecordsAsync task called"); PermissionUsedResult result; @@ -254,41 +155,48 @@ int32_t PermissionRecordManager::GetPermissionUsedRecordsAsync( return Constant::SUCCESS; } -bool PermissionRecordManager::GetRecordsFromDB(const PermissionUsedRequest& request, PermissionUsedResult& result) +bool PermissionRecordManager::GetLocalRecordTokenIdList(std::set& tokenIdList) +{ + std::vector results; + { + Utils::UniqueWriteGuard lk(this->rwLock_); + // find tokenId from cache + PermissionUsedRecordCache::GetInstance().FindTokenIdList(tokenIdList); + // find tokenId from database + PermissionRecordRepository::GetInstance().GetAllRecordValuesByKey(FIELD_TOKEN_ID, results); + } + for (const auto& res : results) { + tokenIdList.emplace(res.GetInt(FIELD_TOKEN_ID)); + } + return true; +} + +bool PermissionRecordManager::GetRecordsFromLocalDB(const PermissionUsedRequest& request, PermissionUsedResult& result) { - GenericValues visitorValues; GenericValues andConditionValues; GenericValues orConditionValues; - if (DataTranslator::TranslationIntoGenericValues(request, visitorValues, andConditionValues, - orConditionValues) != Constant::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "query time is invalid"); + if (DataTranslator::TranslationIntoGenericValues(request, andConditionValues, orConditionValues) + != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "query time or flag is invalid"); return false; } - GenericValues nullValues; - std::vector findVisitorValues; - if (!PermissionVisitorRepository::GetInstance().FindVisitorValues(visitorValues, nullValues, findVisitorValues)) { - return false; + std::set tokenIdList; + if (request.tokenId == 0) { + GetLocalRecordTokenIdList(tokenIdList); + } else { + tokenIdList.emplace(request.tokenId); } - if (findVisitorValues.empty()) { - ACCESSTOKEN_LOG_INFO(LABEL, "no visitor"); - return true; - } - - for (const auto& visitor : findVisitorValues) { - andConditionValues.Put(FIELD_VISITOR_ID, visitor.GetInt(FIELD_ID)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetLocalRecordTokenIdList.size = %{public}zu", tokenIdList.size()); + Utils::UniqueWriteGuard lk(this->rwLock_); + for (const auto& tokenId : tokenIdList) { + andConditionValues.Put(FIELD_TOKEN_ID, (int32_t)tokenId); std::vector findRecordsValues; + PermissionUsedRecordCache::GetInstance().GetRecords(request.permissionList, + andConditionValues, orConditionValues, findRecordsValues); // find records from cache and database + andConditionValues.Remove(FIELD_TOKEN_ID); BundleUsedRecord bundleRecord; - if (!PermissionRecordRepository::GetInstance().FindRecordValues( - andConditionValues, orConditionValues, findRecordsValues)) { - return false; - } - andConditionValues.Remove(FIELD_VISITOR_ID); - bundleRecord.tokenId = (AccessTokenID)visitor.GetInt(FIELD_TOKEN_ID); - bundleRecord.isRemote = visitor.GetInt(FIELD_IS_REMOTE_DEVICE); - bundleRecord.deviceId = visitor.GetString(FIELD_DEVICE_ID); - bundleRecord.bundleName = visitor.GetString(FIELD_BUNDLE_NAME); - + CreateBundleUsedRecord(tokenId, bundleRecord); if (!findRecordsValues.empty()) { if (!GetRecords(request.flag, findRecordsValues, bundleRecord, result)) { return false; @@ -302,6 +210,20 @@ bool PermissionRecordManager::GetRecordsFromDB(const PermissionUsedRequest& requ return true; } +bool PermissionRecordManager::CreateBundleUsedRecord(const AccessTokenID tokenId, BundleUsedRecord& bundleRecord) +{ + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo) != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetHapTokenInfo failed"); + return false; + } + bundleRecord.tokenId = tokenId; + bundleRecord.isRemote = false; + bundleRecord.deviceId = GetDeviceId(tokenId); + bundleRecord.bundleName = tokenInfo.bundleName; + return true; +} + bool PermissionRecordManager::GetRecords( int32_t flag, std::vector recordValues, BundleUsedRecord& bundleRecord, PermissionUsedResult& result) { @@ -317,7 +239,8 @@ bool PermissionRecordManager::GetRecords( record.Put(FIELD_FLAG, flag); if (DataTranslator::TranslationGenericValuesIntoPermissionUsedRecord(record, tmpPermissionRecord) != Constant::SUCCESS) { - ACCESSTOKEN_LOG_INFO(LABEL, "Failed to transform permission to opcode"); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to transform opcode(%{public}d) into permission", + record.GetInt(FIELD_OP_CODE)); continue; } @@ -375,42 +298,36 @@ void PermissionRecordManager::ExecuteDeletePermissionRecordTask() int32_t PermissionRecordManager::DeletePermissionRecord(int32_t days) { Utils::UniqueWriteGuard lk(this->rwLock_); - GenericValues nullValues; - std::vector deleteRecordValues; - if (!PermissionRecordRepository::GetInstance().FindRecordValues(nullValues, nullValues, deleteRecordValues)) { - return Constant::FAILURE; - } - - size_t deleteSize = 0; - if (deleteRecordValues.size() > Constant::MAX_TOTAL_RECORD) { - deleteSize = deleteRecordValues.size() - Constant::MAX_TOTAL_RECORD; - for (size_t i = 0; i < deleteSize; ++i) { - PermissionRecordRepository::GetInstance().RemoveRecordValues(deleteRecordValues[i]); + GenericValues countValue; + PermissionRecordRepository::GetInstance().CountRecordValues(countValue); + int64_t total = countValue.GetInt64(FIELD_COUNT_NUMBER); + if (total > Constant::MAX_TOTAL_RECORD) { + uint32_t excessiveSize = total - Constant::MAX_TOTAL_RECORD; + if (!PermissionRecordRepository::GetInstance().DeleteExcessiveSizeRecordValues(excessiveSize)) { + return Constant::FAILURE; } } + GenericValues andConditionValues; int64_t deleteTimestamp = TimeUtil::GetCurrentTimestamp() - days; - for (size_t i = deleteSize; i < deleteRecordValues.size(); ++i) { - if (deleteRecordValues[i].GetInt64(FIELD_TIMESTAMP) < deleteTimestamp) { - PermissionRecordRepository::GetInstance().RemoveRecordValues(deleteRecordValues[i]); - } + andConditionValues.Put(FIELD_TIMESTAMP_END, deleteTimestamp); + if (!PermissionRecordRepository::GetInstance().DeleteExpireRecordsValues(andConditionValues)) { + return Constant::FAILURE; } return Constant::SUCCESS; } -std::string PermissionRecordManager::DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) +std::string PermissionRecordManager::DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, bundleName=%{public}s, permissionName=%{public}s", - bundleName.c_str(), permissionName.c_str()); PermissionUsedRequest request; - request.bundleName = bundleName; + request.tokenId = tokenId; request.flag = FLAG_PERMISSION_USAGE_DETAIL; if (!permissionName.empty()) { request.permissionList.emplace_back(permissionName); } PermissionUsedResult result; - if (!GetRecordsFromDB(request, result)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "failed to GetRecordsFromDB"); + if (!GetRecordsFromLocalDB(request, result)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to GetRecordsFromLocalDB"); return ""; } @@ -423,28 +340,115 @@ std::string PermissionRecordManager::DumpRecordInfo(const std::string& bundleNam return dumpInfo; } -int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +bool PermissionRecordManager::HasStarted(const PermissionRecord& record) { - // to do - PermissionVisitor visitor; - if (!GetPermissionVisitor(tokenID, visitor)) { - return Constant::FAILURE; + Utils::UniqueWriteGuard lk(this->startRecordListRWLock_); + for (const auto& rec : startRecordList_) { + if ((rec.opCode == record.opCode) && (rec.tokenId == record.tokenId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId(%{public}d), opCode(%{public}d) has been started.", + record.tokenId, record.opCode); + return true; + } + } + return false; +} + +void PermissionRecordManager::AddRecordToStartList(const PermissionRecord& record) +{ + Utils::UniqueWriteGuard lk(this->startRecordListRWLock_); + startRecordList_.emplace_back(record); +} + +bool PermissionRecordManager::GetRecordFromStartList(uint32_t tokenId, int32_t opCode, PermissionRecord& record) +{ + Utils::UniqueWriteGuard lk(this->startRecordListRWLock_); + for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) { + if ((it->opCode == opCode) && (tokenId == (it->tokenId))) { + record = *it; + record.accessDuration = TimeUtil::GetCurrentTimestamp() - record.timestamp; + startRecordList_.erase(it); + return true; + } + } + return false; +} + +void PermissionRecordManager::ResetRecord(PermissionRecord& record, int32_t status) +{ + record.status = status; + record.accessDuration = 0; + record.timestamp = TimeUtil::GetCurrentTimestamp(); +} + +std::vector PermissionRecordManager::GetRecordsAndReset(uint32_t tokenId, int32_t status) +{ + std::vector recordList; + Utils::UniqueWriteGuard lk(this->startRecordListRWLock_); + for (auto it = startRecordList_.begin(); it != startRecordList_.end(); ++it) { + if ((it->tokenId == tokenId) && status != (it->status)) { + PermissionRecord record = *it; + record.accessDuration = TimeUtil::GetCurrentTimestamp() - record.timestamp; + recordList.emplace_back(record); + ResetRecord(*it, status); + } } + return recordList; +} + +void PermissionRecordManager::CallbackExecute( + AccessTokenID tokenId, const std::string& permissionName, int32_t status) +{ ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync( - tokenID, permissionName, visitor.deviceId, PERM_ACTIVE_IN_FOREGROUND); + tokenId, permissionName, GetDeviceId(tokenId), (ActiveChangeType)status); +} + +int32_t PermissionRecordManager::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) +{ + int32_t accessCount = 1; + int32_t failCount = 0; + + PermissionRecord record = { 0 }; + if (!GetPermissionRecord(tokenId, permissionName, accessCount, failCount, record)) { + return Constant::FAILURE; + } + + if (HasStarted(record)) { + return Constant::FAILURE; + } + + AddRecordToStartList(record); + if (record.status != PERM_INACTIVE) { + CallbackExecute(tokenId, permissionName, record.status); + } return Constant::SUCCESS; } -int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +int32_t PermissionRecordManager::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) { - // to do - PermissionVisitor visitor; - if (!GetPermissionVisitor(tokenID, visitor)) { + ExecuteDeletePermissionRecordTask(); + + if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid tokenId(%{public}d)", tokenId); return Constant::FAILURE; } - ActiveStatusCallbackManager::GetInstance().ExecuteCallbackAsync( - tokenID, permissionName, visitor.deviceId, PERM_INACTIVE); + int32_t opCode; + if (!Constant::TransferPermissionToOpcode(permissionName, opCode)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid permission(%{public}s)", permissionName.c_str()); + return Constant::FAILURE; + } + + PermissionRecord record; + if (!GetRecordFromStartList(tokenId, opCode, record)) { + return Constant::FAILURE; + } + + if (record.status != PERM_INACTIVE) { + ACCESSTOKEN_LOG_INFO(LABEL, "AddRecord(tokenId: %{public}d, opCode: %{public}d, status: %{public}d)", + record.tokenId, record.opCode, record.status); + AddRecord(record); + CallbackExecute(tokenId, permissionName, PERM_INACTIVE); + } return Constant::SUCCESS; } @@ -459,12 +463,16 @@ int32_t PermissionRecordManager::UnRegisterPermActiveStatusCallback(const sptr& resultValues) +{ + if (PermissionUsedRecordDb::GetInstance().GetDistinctValue(PermissionUsedRecordDb::PERMISSION_RECORD, + condition, resultValues) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD table add fail"); + return false; + } + return true; +} + +void PermissionRecordRepository::CountRecordValues(GenericValues& resultValues) +{ + PermissionUsedRecordDb::GetInstance().Count(PermissionUsedRecordDb::PERMISSION_RECORD, resultValues); +} + +bool PermissionRecordRepository::DeleteExpireRecordsValues(const GenericValues& andConditions) +{ + if (PermissionUsedRecordDb::GetInstance().DeleteExpireRecords(PermissionUsedRecordDb::PERMISSION_RECORD, + andConditions) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD delete fail"); + return false; + } + return true; +} + +bool PermissionRecordRepository::DeleteExcessiveSizeRecordValues(uint32_t excessiveSize) +{ + if (PermissionUsedRecordDb::GetInstance().DeleteExcessiveRecords(PermissionUsedRecordDb::PERMISSION_RECORD, + excessiveSize) != PermissionUsedRecordDb::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_RECORD delete fail"); + return false; + } + return true; +} } // namespace AccessToken } // namespace Security } // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/src/record/permission_used_record_cache.cpp b/services/privacymanager/src/record/permission_used_record_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..038595fc592171fa11737f450703516e4776ad1e --- /dev/null +++ b/services/privacymanager/src/record/permission_used_record_cache.cpp @@ -0,0 +1,415 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_used_record_cache.h" +#include "accesstoken_log.h" +#include "constant.h" +#include "field_const.h" +#include "generic_values.h" +#include "permission_record.h" +#include "permission_record_manager.h" +#include "permission_record_node.h" +#include "permission_record_repository.h" +#include "permission_used_record_db.h" +#include "time_util.h" +#include "to_string.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionUsedRecordCache" +}; +} + +PermissionUsedRecordCache& PermissionUsedRecordCache::GetInstance() +{ + static PermissionUsedRecordCache instance; + return instance; +} + +void PermissionUsedRecordCache::AddRecordToBuffer(PermissionRecord& record) +{ + if (nextPersistTimestamp_ == 0) { + nextPersistTimestamp_ = record.timestamp + INTERVAL; + } + std::shared_ptr curFindMergePos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindMergePos = curRecordBufferPos_; + persistPendingBufferHead = recordBufferHead_; + int32_t remainCount = 0; + while (curFindMergePos != recordBufferHead_) { + auto pre = curFindMergePos->pre.lock(); + if ((record.timestamp - curFindMergePos->record.timestamp) >= INTERVAL) { + persistPendingBufferEnd = curFindMergePos; + break; + } else if (curFindMergePos->record.tokenId == record.tokenId && + record.opCode == curFindMergePos->record.opCode && + record.status == curFindMergePos->record.status && + (record.timestamp - curFindMergePos->record.timestamp) <= Constant::PRECISE) { + MergeRecord(record, curFindMergePos); + } else { + remainCount++; + } + curFindMergePos = pre; + } + AddRecordNode(record); // refresh curRecordBUfferPos and readableSize + remainCount++; + if (persistPendingBufferEnd != nullptr) { + ResetRecordBuffer(remainCount, persistPendingBufferEnd); + } + } + if (persistPendingBufferEnd != nullptr) { + AddToPersistQueue(persistPendingBufferHead); + } +} + +void PermissionUsedRecordCache::MergeRecord(PermissionRecord& record, + std::shared_ptr curFindMergePos) +{ + record.accessDuration += curFindMergePos->record.accessDuration; + record.accessCount += curFindMergePos->record.accessCount; + record.rejectCount += curFindMergePos->record.rejectCount; + if (curRecordBufferPos_ == curFindMergePos) { + curRecordBufferPos_ = curRecordBufferPos_->pre.lock(); + } + DeleteRecordNode(curFindMergePos); // delete old same node + readableSize_--; +} + +void PermissionUsedRecordCache::AddToPersistQueue( + const std::shared_ptr persistPendingBufferHead) +{ + bool startPersist = false; + { + Utils::UniqueWriteGuard lock2(this->cacheLock_); + persistPendingBufferQueue_.emplace_back(persistPendingBufferHead); + if ((TimeUtil::GetCurrentTimestamp() >= nextPersistTimestamp_ || + readableSize_ >= MAX_PERSIST_SIZE) && persistIsRunning_ == 0) { + startPersist = true; + } + } + if (startPersist) { + ExecuteReadRecordBufferTask(); + } +} + +void PermissionUsedRecordCache::ExecuteReadRecordBufferTask() +{ + if (readRecordBufferTaskWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, "Already has read record buffer task!"); + return; + } + auto readRecordBufferTask = [this]() { + ACCESSTOKEN_LOG_INFO(LABEL, "ReadRecordBuffer task called"); + PersistPendingRecords(); + }; + readRecordBufferTaskWorker_.AddTask(readRecordBufferTask); +} + +int32_t PermissionUsedRecordCache::PersistPendingRecords() +{ + std::shared_ptr persistPendingBufferHead; + bool isEmpty; + std::vector insertValues; + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + isEmpty = persistPendingBufferQueue_.empty(); + persistIsRunning_ = 1; + nextPersistTimestamp_ = 0; + } + while (!isEmpty) { + { + Utils::UniqueWriteGuard lock2(this->cacheLock_); + persistPendingBufferHead = persistPendingBufferQueue_[0]; + persistPendingBufferQueue_.erase(persistPendingBufferQueue_.begin()); + } + std::shared_ptr curPendingRecordNode = + persistPendingBufferHead->next; + while (curPendingRecordNode != nullptr) { + auto next = curPendingRecordNode->next; + GenericValues tmpRecordValues; + PermissionRecord tmpRecord = curPendingRecordNode->record; + PermissionRecord::TranslationIntoGenericValues(tmpRecord, tmpRecordValues); + insertValues.emplace_back(tmpRecordValues); + DeleteRecordNode(curPendingRecordNode); + curPendingRecordNode = next; + } + if (!insertValues.empty() && !PermissionRecordRepository::GetInstance().AddRecordValues(insertValues)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to persist pending records"); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "Persist pending records successful"); + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + isEmpty = persistPendingBufferQueue_.empty(); + } + } + { + Utils::UniqueReadGuard lock2(this->cacheLock_); + if (isEmpty) { // free persistPendingBufferQueue + std::vector> tmpPersistPendingBufferQueue; + std::swap(tmpPersistPendingBufferQueue, persistPendingBufferQueue_); + } + persistIsRunning_ = 0; + } + return true; +} + +int32_t PermissionUsedRecordCache::RemoveRecords(const AccessTokenID tokenId) +{ + std::shared_ptr curFindDeletePos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + int32_t countPersistPendingNode = 0; + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindDeletePos = recordBufferHead_->next; + persistPendingBufferHead = recordBufferHead_; + while (curFindDeletePos != nullptr) { + auto next = curFindDeletePos->next; + if (curFindDeletePos->record.tokenId == tokenId) { + if (curRecordBufferPos_ == curFindDeletePos) { + curRecordBufferPos_ = curFindDeletePos->pre.lock(); + } + DeleteRecordNode(curFindDeletePos); + readableSize_--; + } else if (TimeUtil::GetCurrentTimestamp() - + curFindDeletePos->record.timestamp >= INTERVAL) { + persistPendingBufferEnd = curFindDeletePos; + countPersistPendingNode++; + } + curFindDeletePos = next; + } + if (countPersistPendingNode != 0) { // refresh recordBufferHead + int32_t remainCount = readableSize_ - countPersistPendingNode; + ResetRecordBuffer(remainCount, persistPendingBufferEnd); + } + } + RemoveRecordsFromPersistPendingBufferQueue(tokenId, persistPendingBufferHead, persistPendingBufferEnd); + return Constant::SUCCESS; +} + +void PermissionUsedRecordCache::RemoveRecordsFromPersistPendingBufferQueue(const AccessTokenID tokenId, + std::shared_ptr persistPendingBufferHead, + std::shared_ptr persistPendingBufferEnd) +{ + { + std::shared_ptr curFindDeletePos; + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto& persistHead : persistPendingBufferQueue_) { + curFindDeletePos = persistHead->next; + while (curFindDeletePos != nullptr) { + auto next = curFindDeletePos->next; + if (curFindDeletePos->record.tokenId == tokenId) { + DeleteRecordNode(curFindDeletePos); + } + curFindDeletePos = next; + } + } + } + } + GenericValues record; + record.Put(FIELD_TOKEN_ID, (int32_t)tokenId); + PermissionRecordRepository::GetInstance().RemoveRecordValues(record); // remove from database + if (persistPendingBufferEnd != nullptr) { // add to queue + AddToPersistQueue(persistPendingBufferHead); + } +} + +void PermissionUsedRecordCache::GetRecords(const std::vector& permissionList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues) +{ + std::set opCodeList; + std::shared_ptr curFindPos; + std::shared_ptr persistPendingBufferHead; + std::shared_ptr persistPendingBufferEnd = nullptr; + int32_t countPersistPendingNode = 0; + AccessTokenID tokenId = andConditionValues.GetInt(FIELD_TOKEN_ID); + TransferToOpcode(opCodeList, permissionList); + { + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindPos = recordBufferHead_->next; + persistPendingBufferHead = recordBufferHead_; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + if (RecordCompare(tokenId, opCodeList, andConditionValues, curFindPos->record)) { + GenericValues recordValues; + PermissionRecord::TranslationIntoGenericValues(curFindPos->record, recordValues); + findRecordsValues.emplace_back(recordValues); + } + if (TimeUtil::GetCurrentTimestamp() - curFindPos->record.timestamp >= INTERVAL) { + persistPendingBufferEnd = curFindPos; + countPersistPendingNode++; + } + curFindPos = next; + } + if (countPersistPendingNode != 0) { // refresh recordBufferHead + int32_t remainCount = readableSize_ - countPersistPendingNode; + ResetRecordBuffer(remainCount, persistPendingBufferEnd); + } + } + GetRecordsFromPersistPendingBufferQueue(opCodeList, andConditionValues, + orConditionValues, findRecordsValues); + if (countPersistPendingNode != 0) { + AddToPersistQueue(persistPendingBufferHead); + } +} + +void PermissionUsedRecordCache::GetRecordsFromPersistPendingBufferQueue(const std::set& opCodeList, + const GenericValues& andConditionValues, const GenericValues& orConditionValues, + std::vector& findRecordsValues) +{ + AccessTokenID tokenId = andConditionValues.GetInt(FIELD_TOKEN_ID); + std::shared_ptr curFindPos; + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto& persistHead : persistPendingBufferQueue_) { + curFindPos = persistHead->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + if (RecordCompare(tokenId, opCodeList, andConditionValues, curFindPos->record)) { + GenericValues recordValues; + PermissionRecord::TranslationIntoGenericValues(curFindPos->record, recordValues); + findRecordsValues.emplace_back(recordValues); + } + curFindPos = next; + } + } + } + if (!PermissionRecordRepository::GetInstance().FindRecordValues( + andConditionValues, orConditionValues, findRecordsValues)) { // find records from database + ACCESSTOKEN_LOG_ERROR(LABEL, "find records from database failed"); + } +} + +void PermissionUsedRecordCache::ResetRecordBuffer(const int32_t remainCount, + std::shared_ptr& persistPendingBufferEnd) +{ + readableSize_ = remainCount; + // refresh recordBufferHead + std::shared_ptr tmpRecordBufferHead = + std::make_shared(); + tmpRecordBufferHead->next = persistPendingBufferEnd->next; + persistPendingBufferEnd->next.reset(); + recordBufferHead_ = tmpRecordBufferHead; + + if (persistPendingBufferEnd == curRecordBufferPos_) { + // persistPendingBufferEnd == curRecordBufferPos, reset curRecordBufferPos + curRecordBufferPos_ = recordBufferHead_; + } else { + // recordBufferHead_->next->pre = persistPendingBufferEnd, reset recordBufferHead_->next->pre + recordBufferHead_->next->pre = recordBufferHead_; + } +} + +void PermissionUsedRecordCache::TransferToOpcode(std::set& opCodeList, + const std::vector& permissionList) +{ + for (const auto& permission : permissionList) { + int32_t opCode = Constant::OP_INVALID; + Constant::TransferPermissionToOpcode(permission, opCode); + opCodeList.insert(opCode); + } +} + +bool PermissionUsedRecordCache::RecordCompare(const AccessTokenID tokenId, const std::set& opCodeList, + const GenericValues& andConditionValues, const PermissionRecord& record) +{ + // compare tokenId + if (record.tokenId != tokenId) { + return false; + } + // compare opCode + if (!opCodeList.empty() && opCodeList.find(record.opCode) == opCodeList.end()) { + return false; + } + // compare timestamp + std::vector andColumns = andConditionValues.GetAllKeys(); + if (!andColumns.empty()) { + for (auto andColumn : andColumns) { + if (andColumn == FIELD_TIMESTAMP_BEGIN && + record.timestamp < andConditionValues.GetInt64(andColumn)) { + return false; + } else if (andColumn == FIELD_TIMESTAMP_END && + record.timestamp > andConditionValues.GetInt64(andColumn)) { + return false; + } else if (andColumn == FIELD_TIMESTAMP && + record.timestamp != andConditionValues.GetInt64(andColumn)) { + return false; + } + } + } + return true; +} + +void PermissionUsedRecordCache::FindTokenIdList(std::set& tokenIdList) +{ + std::shared_ptr curFindPos; + { + // find tokenIdList from recordBuffer + Utils::UniqueWriteGuard lock1(this->cacheLock_); + curFindPos = recordBufferHead_->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + tokenIdList.emplace((AccessTokenID)curFindPos->record.tokenId); + curFindPos = next; + } + } + { + // find tokenIdList from BufferQueue + Utils::UniqueWriteGuard lock2(this->cacheLock_); + if (!persistPendingBufferQueue_.empty()) { + for (auto persistHead : persistPendingBufferQueue_) { + curFindPos = persistHead->next; + while (curFindPos != nullptr) { + auto next = curFindPos->next; + tokenIdList.emplace((AccessTokenID)curFindPos->record.tokenId); + curFindPos = next; + } + } + } + } +} + +void PermissionUsedRecordCache::AddRecordNode(const PermissionRecord& record) +{ + std::shared_ptr tmpRecordNode = std::make_shared(); + tmpRecordNode->record = record; + tmpRecordNode->pre = curRecordBufferPos_; + curRecordBufferPos_->next = tmpRecordNode; + curRecordBufferPos_ = curRecordBufferPos_->next; + readableSize_++; +} + +void PermissionUsedRecordCache::DeleteRecordNode(std::shared_ptr deleteRecordNode) +{ + std::shared_ptr pre = deleteRecordNode->pre.lock(); + if (deleteRecordNode->next == nullptr) { // End of the linked list + pre->next = nullptr; + } else { + std::shared_ptr next = deleteRecordNode->next; + pre->next = next; + next->pre = pre; + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/src/record/permission_visitor.cpp b/services/privacymanager/src/record/permission_visitor.cpp deleted file mode 100644 index d0b126b13963246cfc31beca5de51c8f6c9b9b1c..0000000000000000000000000000000000000000 --- a/services/privacymanager/src/record/permission_visitor.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "permission_visitor.h" -#include "field_const.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -void PermissionVisitor::TranslationIntoGenericValues(const PermissionVisitor& visitor, GenericValues& values) -{ - values.Put(FIELD_TOKEN_ID, (int32_t)visitor.tokenId); - values.Put(FIELD_IS_REMOTE_DEVICE, visitor.isRemoteDevice ? 1 : 0); - values.Put(FIELD_DEVICE_ID, visitor.deviceId); - values.Put(FIELD_USER_ID, visitor.userId); - values.Put(FIELD_BUNDLE_NAME, visitor.bundleName); -} - -void PermissionVisitor::TranslationIntoPermissionVisitor(const GenericValues& values, PermissionVisitor& visitor) -{ - visitor.id = values.GetInt(FIELD_ID); - visitor.tokenId = (AccessTokenID)values.GetInt(FIELD_TOKEN_ID); - visitor.isRemoteDevice = values.GetInt(FIELD_IS_REMOTE_DEVICE); - visitor.deviceId = values.GetString(FIELD_DEVICE_ID); - visitor.userId = values.GetInt(FIELD_USER_ID); - visitor.bundleName = values.GetString(FIELD_BUNDLE_NAME); -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/src/record/permission_visitor_repository.cpp b/services/privacymanager/src/record/permission_visitor_repository.cpp deleted file mode 100644 index 5df400cad5c5091b8e8d58302ad4e9bcd2831caa..0000000000000000000000000000000000000000 --- a/services/privacymanager/src/record/permission_visitor_repository.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "permission_visitor_repository.h" - -#include "accesstoken_log.h" -#include "permission_used_record_db.h" - -namespace OHOS { -namespace Security { -namespace AccessToken { -namespace { -static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { - LOG_CORE, SECURITY_DOMAIN_PRIVACY, "PermissionVisitorRepository" -}; -} - -PermissionVisitorRepository& PermissionVisitorRepository::GetInstance() -{ - static PermissionVisitorRepository instance; - return instance; -} - -PermissionVisitorRepository::PermissionVisitorRepository() -{ -} - -PermissionVisitorRepository::~PermissionVisitorRepository() -{ -} - -bool PermissionVisitorRepository::AddVisitorValues(const GenericValues& visitorValues) -{ - GenericValues nullValues; - std::vector insertValues; - std::vector resultValues; - if (PermissionUsedRecordDb::GetInstance().FindByConditions(PermissionUsedRecordDb::PERMISSION_VISITOR, - visitorValues, nullValues, resultValues) != PermissionUsedRecordDb::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_VISITOR table find fail"); - return false; - } - if (!resultValues.empty()) { - return true; - } - - insertValues.emplace_back(visitorValues); - if (PermissionUsedRecordDb::GetInstance().Add(PermissionUsedRecordDb::PERMISSION_VISITOR, insertValues) - != PermissionUsedRecordDb::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_VISITOR table add fail"); - return false; - } - return true; -} - -bool PermissionVisitorRepository::FindVisitorValues( - const GenericValues& andValues, const GenericValues& orValues, std::vector& visitorValues) -{ - if (PermissionUsedRecordDb::GetInstance().FindByConditions(PermissionUsedRecordDb::PERMISSION_VISITOR, andValues, - orValues, visitorValues) != PermissionUsedRecordDb::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_VISITOR table find fail"); - return false; - } - return true; -} - -bool PermissionVisitorRepository::RemoveVisitorValues(const GenericValues& conditionValues) -{ - if (PermissionUsedRecordDb::GetInstance().Remove(PermissionUsedRecordDb::PERMISSION_VISITOR, conditionValues) - != PermissionUsedRecordDb::SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "PERMISSION_VISITOR table remove fail"); - return false; - } - return true; -} -} // namespace AccessToken -} // namespace Security -} // namespace OHOS \ No newline at end of file diff --git a/services/privacymanager/src/service/privacy_manager_service.cpp b/services/privacymanager/src/service/privacy_manager_service.cpp index 92e690931b13fa823fba36d359ba1453e58ae60c..41e1087e1458ec3d3c26dbbd9bd694b996245052 100644 --- a/services/privacymanager/src/service/privacy_manager_service.cpp +++ b/services/privacymanager/src/service/privacy_manager_service.cpp @@ -50,7 +50,6 @@ void PrivacyManagerService::OnStart() ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService has already started!"); return; } - ACCESSTOKEN_LOG_INFO(LABEL, "PrivacyManagerService is starting"); if (!Initialize()) { ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to initialize"); return; @@ -71,40 +70,31 @@ void PrivacyManagerService::OnStop() } int32_t PrivacyManagerService::AddPermissionUsedRecord( - AccessTokenID tokenID, const std::string& permissionName, int32_t successCount, int32_t failCount) + AccessTokenID tokenId, const std::string& permissionName, int32_t successCount, int32_t failCount) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, permission: %{public}s", - tokenID, permissionName.c_str()); return PermissionRecordManager::GetInstance().AddPermissionUsedRecord( - tokenID, permissionName, successCount, failCount); + tokenId, permissionName, successCount, failCount); } -int32_t PrivacyManagerService::StartUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +int32_t PrivacyManagerService::StartUsingPermission(AccessTokenID tokenId, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, permission: %{public}s", - tokenID, permissionName.c_str()); - return PermissionRecordManager::GetInstance().StartUsingPermission(tokenID, permissionName); + return PermissionRecordManager::GetInstance().StartUsingPermission(tokenId, permissionName); } -int32_t PrivacyManagerService::StopUsingPermission(AccessTokenID tokenID, const std::string& permissionName) +int32_t PrivacyManagerService::StopUsingPermission(AccessTokenID tokenId, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, permission: %{public}s", - tokenID, permissionName.c_str()); - return PermissionRecordManager::GetInstance().StopUsingPermission(tokenID, permissionName); + return PermissionRecordManager::GetInstance().StopUsingPermission(tokenId, permissionName); } -int32_t PrivacyManagerService::RemovePermissionUsedRecords(AccessTokenID tokenID, const std::string& deviceID) +int32_t PrivacyManagerService::RemovePermissionUsedRecords(AccessTokenID tokenId, const std::string& deviceID) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, tokenID: 0x%{public}x, deviceID: %{public}s", - tokenID, ConstantCommon::EncryptDevId(deviceID).c_str()); - PermissionRecordManager::GetInstance().RemovePermissionUsedRecords(tokenID, deviceID); + PermissionRecordManager::GetInstance().RemovePermissionUsedRecords(tokenId, deviceID); return Constant::SUCCESS; } int32_t PrivacyManagerService::GetPermissionUsedRecords( const PermissionUsedRequestParcel& request, PermissionUsedResultParcel& result) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); PermissionUsedResult permissionRecord; int32_t ret = PermissionRecordManager::GetInstance().GetPermissionUsedRecords(request.request, permissionRecord); result.result = permissionRecord; @@ -114,15 +104,12 @@ int32_t PrivacyManagerService::GetPermissionUsedRecords( int32_t PrivacyManagerService::GetPermissionUsedRecords( const PermissionUsedRequestParcel& request, const sptr& callback) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry"); return PermissionRecordManager::GetInstance().GetPermissionUsedRecordsAsync(request.request, callback); } -std::string PrivacyManagerService::DumpRecordInfo(const std::string& bundleName, const std::string& permissionName) +std::string PrivacyManagerService::DumpRecordInfo(AccessTokenID tokenId, const std::string& permissionName) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "Entry, bundleName: %{public}s, permissionName: %{public}s", - bundleName.c_str(), permissionName.c_str()); - return PermissionRecordManager::GetInstance().DumpRecordInfo(bundleName, permissionName); + return PermissionRecordManager::GetInstance().DumpRecordInfo(tokenId, permissionName); } int32_t PrivacyManagerService::RegisterPermActiveStatusCallback( diff --git a/services/privacymanager/src/service/privacy_manager_stub.cpp b/services/privacymanager/src/service/privacy_manager_stub.cpp index 10a767c8f3bcab9a7bdb50959a8fb8f3e4f641cf..743cd11b595da3882498a7de7ab982255fa3e278 100644 --- a/services/privacymanager/src/service/privacy_manager_stub.cpp +++ b/services/privacymanager/src/service/privacy_manager_stub.cpp @@ -82,27 +82,27 @@ void PrivacyManagerStub::AddPermissionUsedRecordInner(MessageParcel& data, Messa reply.WriteInt32(RET_FAILED); return; } - AccessTokenID tokenID = data.ReadUint32(); + AccessTokenID tokenId = data.ReadUint32(); std::string permissionName = data.ReadString(); int32_t successCount = data.ReadInt32(); int32_t failCount = data.ReadInt32(); - int32_t result = this->AddPermissionUsedRecord(tokenID, permissionName, successCount, failCount); + int32_t result = this->AddPermissionUsedRecord(tokenId, permissionName, successCount, failCount); reply.WriteInt32(result); } void PrivacyManagerStub::StartUsingPermissionInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenID = data.ReadUint32(); + AccessTokenID tokenId = data.ReadUint32(); std::string permissionName = data.ReadString(); - int32_t result = this->StartUsingPermission(tokenID, permissionName); + int32_t result = this->StartUsingPermission(tokenId, permissionName); reply.WriteInt32(result); } void PrivacyManagerStub::StopUsingPermissionInner(MessageParcel& data, MessageParcel& reply) { - AccessTokenID tokenID = data.ReadUint32(); + AccessTokenID tokenId = data.ReadUint32(); std::string permissionName = data.ReadString(); - int32_t result = this->StopUsingPermission(tokenID, permissionName); + int32_t result = this->StopUsingPermission(tokenId, permissionName); reply.WriteInt32(result); } @@ -115,9 +115,9 @@ void PrivacyManagerStub::RemovePermissionUsedRecordsInner(MessageParcel& data, M reply.WriteInt32(RET_FAILED); return; } - AccessTokenID tokenID = data.ReadUint32(); + AccessTokenID tokenId = data.ReadUint32(); std::string deviceID = data.ReadString(); - int32_t result = this->RemovePermissionUsedRecords(tokenID, deviceID); + int32_t result = this->RemovePermissionUsedRecords(tokenId, deviceID); reply.WriteInt32(result); } @@ -159,9 +159,9 @@ void PrivacyManagerStub::GetPermissionUsedRecordsAsyncInner(MessageParcel& data, void PrivacyManagerStub::DumpRecordInfoInner(MessageParcel& data, MessageParcel& reply) { - std::string bundleName = data.ReadString(); + AccessTokenID tokenId = data.ReadUint32(); std::string permissionName = data.ReadString(); - std::string dumpInfo = this->DumpRecordInfo(bundleName, permissionName); + std::string dumpInfo = this->DumpRecordInfo(tokenId, permissionName); reply.WriteString(dumpInfo); } diff --git a/services/tokensyncmanager/BUILD.gn b/services/tokensyncmanager/BUILD.gn index d2a228711e20dad9ac7a30d3814c2a4799ecafb8..5fb7fb4842e45409dfd4bd5f0d2f74488d524347 100644 --- a/services/tokensyncmanager/BUILD.gn +++ b/services/tokensyncmanager/BUILD.gn @@ -75,6 +75,8 @@ ohos_shared_library("token_sync_manager_service") { "-DDEBUG_API_PERFORMANCE", ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + deps = [ "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", "//base/security/access_token/frameworks/common:accesstoken_common_cxx", @@ -88,7 +90,6 @@ ohos_shared_library("token_sync_manager_service") { "dsoftbus:softbus_client", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", - "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", ] diff --git a/services/tokensyncmanager/include/device/device_info_manager.h b/services/tokensyncmanager/include/device/device_info_manager.h index 1008a1b0868a4d23e7ed1c0fd20687130eb573f6..53f7871449266029074ddd436ff55b90e29f0dca 100644 --- a/services/tokensyncmanager/include/device/device_info_manager.h +++ b/services/tokensyncmanager/include/device/device_info_manager.h @@ -22,7 +22,6 @@ #include "data_validator.h" #include "device_info_repository.h" #include "ipc_skeleton.h" -#include "parameter.h" #include "soft_bus_manager.h" namespace OHOS { diff --git a/services/tokensyncmanager/src/command/base_remote_command.cpp b/services/tokensyncmanager/src/command/base_remote_command.cpp index 696eb9bc1e4a722c5b32d43b8546c5326515f76d..35384269a1fcc5755862489bb032c965cbf5ab6e 100644 --- a/services/tokensyncmanager/src/command/base_remote_command.cpp +++ b/services/tokensyncmanager/src/command/base_remote_command.cpp @@ -192,7 +192,7 @@ void BaseRemoteCommand::FromPermStateListJson(const nlohmann::json& hapTokenJson { if (hapTokenJson.find("permState") != hapTokenJson.end() && hapTokenJson.at("permState").is_array() - && hapTokenJson.at("permState").size() > 0) { + && !hapTokenJson.at("permState").empty()) { nlohmann::json permissionsJson = hapTokenJson.at("permState").get(); for (const auto& permissionJson : permissionsJson) { PermissionStateFull permission; @@ -265,11 +265,11 @@ void BaseRemoteCommand::FromNativeTokenInfoJson(const nlohmann::json& nativeToke nativeTokenInfo.baseInfo.tokenAttr = (unsigned)nativeTokenJson.at("tokenAttr").get(); } if (nativeTokenJson.find("dcaps") != nativeTokenJson.end() && nativeTokenJson.at("dcaps").is_array() - && nativeTokenJson.at("dcaps").size() > 0 && (nativeTokenJson.at("dcaps"))[0].is_string()) { + && !nativeTokenJson.at("dcaps").empty() && (nativeTokenJson.at("dcaps"))[0].is_string()) { nativeTokenInfo.baseInfo.dcap = nativeTokenJson.at("dcaps").get>(); } if (nativeTokenJson.find("nativeAcls") != nativeTokenJson.end() && nativeTokenJson.at("nativeAcls").is_array() - && nativeTokenJson.at("nativeAcls").size() > 0 && (nativeTokenJson.at("nativeAcls"))[0].is_string()) { + && !nativeTokenJson.at("nativeAcls").empty() && (nativeTokenJson.at("nativeAcls"))[0].is_string()) { nativeTokenInfo.baseInfo.nativeAcls = nativeTokenJson.at("nativeAcls").get>(); } diff --git a/services/tokensyncmanager/src/common/constant.cpp b/services/tokensyncmanager/src/common/constant.cpp index 7de4ff1875c7b4d030bad6818fd21e8175b1ce24..b5866e34c0efd2cc170a8ee5cdc032fcbe20fcb8 100644 --- a/services/tokensyncmanager/src/common/constant.cpp +++ b/services/tokensyncmanager/src/common/constant.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "constant.h" -#include "parameter.h" namespace OHOS { namespace Security { diff --git a/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/services/tokensyncmanager/src/remote/remote_command_executor.cpp index 050a358739077d9c4aca98d403672ecfb4234fa9..7aa6658043cdd9887a2dcbb2d968f5b7120a9a63 100644 --- a/services/tokensyncmanager/src/remote/remote_command_executor.cpp +++ b/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -16,7 +16,6 @@ #include "remote_command_executor.h" #include "constant_common.h" #include "device_info_manager.h" -#include "parameter.h" #include "singleton.h" #include "soft_bus_channel.h" #include "token_sync_event_handler.h" diff --git a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp index 0531903b4864df6758c03806cb274019a73fc0ab..c1bd1344ab6f3c09501cf11b309fe75e17061881 100644 --- a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp +++ b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp @@ -17,7 +17,6 @@ #include #include "constant_common.h" #include "device_info_manager.h" -#include "parameter.h" #include "softbus_bus_center.h" #include "dm_device_info.h" #include "remote_command_manager.h" diff --git a/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp index 727b2f6c2215f0c26faf4aab33aee97ce527e2db..85ca0d399374195c7c6281a960d0a9e91a7f9001 100644 --- a/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp +++ b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp @@ -56,7 +56,8 @@ int32_t TokenSyncManagerStub::OnRemoteRequest( void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + int type = (reinterpret_cast(&tokenCaller))->type; + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -72,7 +73,8 @@ void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, Messa void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + int type = (reinterpret_cast(&tokenCaller))->type; + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; @@ -86,7 +88,8 @@ void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, Me void TokenSyncManagerStub::UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - if ((reinterpret_cast(&tokenCaller))->type != TOKEN_NATIVE) { + int type = (reinterpret_cast(&tokenCaller))->type; + if ((type != TOKEN_NATIVE) && (type != TOKEN_SHELL)) { ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, permission denied", __func__); reply.WriteInt32(RET_FAILED); return; diff --git a/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp index 42045285b112e705e1c5dfa7b642b8cf8f92e781..94647249557ac360bb7caea0e1a59cc775039ebd 100644 --- a/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp +++ b/services/tokensyncmanager/test/mock/src/soft_bus_center_mock.cpp @@ -26,45 +26,12 @@ static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ static const int REG_COUNT_LIMIT = 10; } // namespace static int regCount_ = -1; -static INodeStateCb *callback_ = nullptr; bool IsRegCountOK() { return regCount_ >= 0 && regCount_ < REG_COUNT_LIMIT; } -int32_t RegNodeDeviceStateCb(const char *pkgName, INodeStateCb *callback) -{ - regCount_++; - // reg:0-9 - if (IsRegCountOK()) { - callback_ = const_cast(callback); - ACCESSTOKEN_LOG_DEBUG(LABEL, "success, pkg:%{public}s, count: %{public}d", pkgName, regCount_); - return Constant::SUCCESS; - } - - // count 10 above alway return failure for retry. - ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); - return Constant::FAILURE; -} - -int32_t UnregNodeDeviceStateCb(INodeStateCb *callback) -{ - // unreg: 0-9 - if (IsRegCountOK()) { - regCount_--; - callback_ = nullptr; - ACCESSTOKEN_LOG_DEBUG(LABEL, "success, count: %{public}d", regCount_); - return Constant::SUCCESS; - } - - if (regCount_ >= 0) { - regCount_--; - } - ACCESSTOKEN_LOG_DEBUG(LABEL, "failure, count: %{public}d", regCount_); - return Constant::SUCCESS; -} - int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) { strcpy_s(info->deviceName, sizeof(info->deviceName), "local"); diff --git a/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn index e452ec6c338dd24b84f619eaf9988772ac082418..9252861a63927f9713e3c454cf970d59e5631982 100644 --- a/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn +++ b/services/tokensyncmanager/test/unittest/token_sync_service/BUILD.gn @@ -83,14 +83,14 @@ ohos_unittest("libtoken_sync_service_sdk_test") { cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] } + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", - "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr:samgr_proxy", ] } diff --git a/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn b/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn index 7f773f0c8783c753227dbe7ac6235611bd08eac6..eea0a71182e22ac289a7ed0c1b0264c4cec0190a 100644 --- a/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/allochaptoken_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("AllocHapTokenFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp b/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp index 094fa5d6e8dd6b6588426bacbb3488f68b7f2148..f8b23b0412cd259b70cca02bdc0418c91c491c0a 100644 --- a/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp +++ b/test/fuzztest/access_token/allochaptoken_fuzzer/allochaptoken_fuzzer.cpp @@ -15,9 +15,10 @@ #include "allochaptoken_fuzzer.h" +#include +#include #include #include -#include #undef private #include "accesstoken_kit.h" @@ -27,40 +28,38 @@ using namespace OHOS::Security::AccessToken; namespace OHOS { bool AllocHapTokenFuzzTest(const uint8_t* data, size_t size) { - bool result = false; - std::string testdata; AccessTokenIDEx tokenIdEx = {0}; if ((data == nullptr) || (size <= 0)) { - return result; + return tokenIdEx.tokenIdExStruct.tokenID != 0; } if (size > 0) { - testdata = reinterpret_cast(data); + std::string testName(reinterpret_cast(data), size); PermissionDef TestPermDef = { - .permissionName = testdata, - .bundleName = testdata, + .permissionName = testName, + .bundleName = testName, .grantMode = 1, .availableLevel = APL_NORMAL, - .label = testdata, + .label = testName, .labelId = 1, - .description = testdata, + .description = testName, .descriptionId = 1 }; PermissionStateFull TestState = { - .permissionName = testdata, + .permissionName = testName, .isGeneral = true, - .resDeviceID = {testdata}, + .resDeviceID = {testName}, .grantStatus = {PermissionState::PERMISSION_GRANTED}, .grantFlags = {1}, }; HapInfoParams TestInfoParms = { .userID = 1, - .bundleName = testdata, + .bundleName = testName, .instIndex = 0, - .appIDDesc = testdata + .appIDDesc = testName }; HapPolicyParams TestPolicyPrams = { .apl = APL_NORMAL, - .domain = testdata, + .domain = testName, .permList = {TestPermDef}, .permStateList = {TestState} }; diff --git a/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn b/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn index 87ddbd2a1ba111d741b878cf65b7f3db550671f0..bba4ac9d9c18ebd92f9c00b959db47426e00005f 100644 --- a/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/alloclocaltokenid_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("AllocLocalTokenIDFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp b/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp index 993f3a07938bbae6ef1bdab63c4ccaec2e23436f..7a834474d955d777be7ba9637a2bdd5682ceca28 100644 --- a/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp +++ b/test/fuzztest/access_token/alloclocaltokenid_fuzzer/alloclocaltokenid_fuzzer.cpp @@ -27,14 +27,11 @@ using namespace OHOS::Security::AccessToken; namespace OHOS { bool AllocLocalTokenIDFuzzTest(const uint8_t* data, size_t size) { - bool result = false; AccessTokenID TOKENID = 0; - if ((data == nullptr) || (size <= 0)) { - return result; - } if (size > 0) { + std::string testName(reinterpret_cast(data), size); AccessTokenID REMOTETOKENID = static_cast(size); - TOKENID = AccessTokenKit::AllocLocalTokenID(reinterpret_cast(data), REMOTETOKENID); + TOKENID = AccessTokenKit::AllocLocalTokenID(testName, REMOTETOKENID); } return TOKENID != 0; } diff --git a/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn b/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn index 38d3c84257250af93ecddfbe6de09264c7797797..c0603ac4df1be1ccc39d60c870aec10723bb3616 100644 --- a/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/checknativedcap_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("CheckNativeDCapFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp b/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp index 7b22eff366e08c8fe672982153d7381f79c3e6a7..f3403797a977cf26c2ee34ea7f7684a93999700f 100644 --- a/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp +++ b/test/fuzztest/access_token/checknativedcap_fuzzer/checknativedcap_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::CheckNativeDCap(TOKENID, reinterpret_cast(data)); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::CheckNativeDCap(TOKENID, testName); } return result; } diff --git a/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn b/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn index 32f153f3fc6b6b8b93f2d345bf837a709092e599..6ca4b44af8ea737896f498ccefddbb2feadc851e 100644 --- a/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/clearusergrantedpermissionstate_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("ClearUserGrantedPermissionStateFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn b/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn index 6d69bec7578736595543f4b7b00eea1503394314..50a9e6c8387504043bb3f46a3dce522b0d5e2620 100644 --- a/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("DeleteRemoteDeviceTokensFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp b/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp index 3350c7640ad7b6e7298d5745323369c6e5abd0ec..e3960666a535dfbeb9b58b936309c0000dbfb1b9 100644 --- a/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp +++ b/test/fuzztest/access_token/deleteremotedevicetokens_fuzzer/deleteremotedevicetokens_fuzzer.cpp @@ -36,7 +36,8 @@ namespace OHOS { return result; } if (size > 0) { - result = AccessTokenKit::DeleteRemoteDeviceTokens(reinterpret_cast(data)); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::DeleteRemoteDeviceTokens(testName); } #endif diff --git a/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn b/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn index 5b686f792b3c90db14caf6cf5615c491a2636b93..351f2897c2bcd278ff58c92cf273f8d2398052f3 100644 --- a/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/deleteremotetoken_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("DeleteRemoteTokenFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp b/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp index bcd031a6b9b30fb70605e526d33b19fa692ed059..d422a42a5d0248c7510ba8c8f4af5fe9db86f281 100644 --- a/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp +++ b/test/fuzztest/access_token/deleteremotetoken_fuzzer/deleteremotetoken_fuzzer.cpp @@ -36,7 +36,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::DeleteRemoteToken(reinterpret_cast(data), TOKENID); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::DeleteRemoteToken(testName, TOKENID); } #endif diff --git a/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn b/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn index f37c047465f08512de0205367db15f9c64e9328a..b8717e87efb9e155e386b79230ca5c8e10ff420a 100644 --- a/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/deletetoken_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("DeleteTokenFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn b/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn index 9252021015ee050df1214e70abf658f939dda9ec..40080752abe798ffb7fd76923bc5655044f72903 100644 --- a/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/getdefpermission_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("GetDefPermissionFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp b/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp index 38fbe3a3ddc46e595bc1ac7e530a02c15ea8d463..558976a63cabf1d8f740a42d6c991f8c896441a0 100644 --- a/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp +++ b/test/fuzztest/access_token/getdefpermission_fuzzer/getdefpermission_fuzzer.cpp @@ -30,23 +30,22 @@ namespace OHOS { bool GetDefPermissionFuzzTest(const uint8_t* data, size_t size) { bool result = false; - std::string testdata; if ((data == nullptr) || (size <= 0)) { return result; } if (size > 0) { - testdata = reinterpret_cast(data); + std::string testName(reinterpret_cast(data), size); PermissionDef PERMISSIONDEF = { - .permissionName = testdata, - .bundleName = testdata, + .permissionName = testName, + .bundleName = testName, .grantMode = 1, - .label = testdata, + .label = testName, .labelId = 1, - .description = testdata, + .description = testName, .availableLevel = APL_NORMAL, .descriptionId = 1 }; - result = AccessTokenKit::GetDefPermission(testdata, PERMISSIONDEF); + result = AccessTokenKit::GetDefPermission(testName, PERMISSIONDEF); } return result; } diff --git a/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn b/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn index 328246ace4697bb6c57f53431b05530f77ff5468..295fa1fd7b5345c8c8d842b6b261a687ea224cf7 100644 --- a/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/getpermissionflags_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("GetPermissionFlagsFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp b/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp index 9175d62dd4c63ebcaf8b08ee0c5ef42639fdd93a..644f266153bcfdbf889ed700b16aa0773f1932bc 100644 --- a/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp +++ b/test/fuzztest/access_token/getpermissionflags_fuzzer/getpermissionflags_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::GetPermissionFlag(TOKENID, reinterpret_cast(data)); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::GetPermissionFlag(TOKENID, testName); } return result; } diff --git a/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn b/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn index bb588f85f353625a963923da27ed0c838459fd7b..ef01da2bbf27a677e53a23a755a2c6f06e3edcc2 100644 --- a/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/grantpermission_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("GrantPermissionFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp b/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp index b821ba9744ec018eb45bb31217aea99ec792b8ec..c0ededf133a9fdfc08b26beabf013fdfe38c3551 100644 --- a/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp +++ b/test/fuzztest/access_token/grantpermission_fuzzer/grantpermission_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::GrantPermission(TOKENID, reinterpret_cast(data), 0); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::GrantPermission(TOKENID, testName, 0); } return result; } diff --git a/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn b/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn index 94f45a4198179b274bd451cc6ffeceec43ae6b56..6284e99e2a06e48060ace0d511fe113bd72a0cee 100644 --- a/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("RevokeUserGrantedPermissionFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp b/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp index c2a1dc550d10526de2c9cc44bbac700a3e70ff93..7dcc443c7815703d9af3b52e54475cc07de9cd3d 100644 --- a/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp +++ b/test/fuzztest/access_token/revokeusergrantedpermission_fuzzer/revokeusergrantedpermission_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::RevokePermission(TOKENID, reinterpret_cast(data), 0); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::RevokePermission(TOKENID, testName, 0); } return result; } diff --git a/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn b/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn index d9591910a650268a960d17402879b6574ca80057..a601c5e5b1304ff34882552fa24f9bac4f5e1550 100644 --- a/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("SetRemoteHapTokenInfoFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp b/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp index b4b69c86f24236a6ac91dd1280f76f0d2a58e8cc..4c2a41b19022803bfa825b98fbbf7f253c96872e 100644 --- a/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp +++ b/test/fuzztest/access_token/setremotehaptokeninfo_fuzzer/setremotehaptokeninfo_fuzzer.cpp @@ -29,21 +29,20 @@ namespace OHOS { { bool result = false; #ifdef TOKEN_SYNC_ENABLE - std::string testdata; if ((data == nullptr) || (size <= 0)) { return result; } if (size > 0) { - testdata = reinterpret_cast(data); + std::string testName(reinterpret_cast(data), size); AccessTokenID TOKENID = static_cast(size); HapTokenInfo baseInfo = { .apl = APL_NORMAL, .ver = 1, .userID = 1, - .bundleName = testdata, + .bundleName = testName, .instIndex = 1, - .appID = testdata, - .deviceID = testdata, + .appID = testName, + .deviceID = testName, .tokenID = TOKENID, .tokenAttr = 0 }; @@ -51,8 +50,8 @@ namespace OHOS { .grantFlags = {PermissionFlag::PERMISSION_SYSTEM_FIXED}, .grantStatus = {PermissionState::PERMISSION_GRANTED}, .isGeneral = true, - .permissionName = testdata, - .resDeviceID = {testdata}}; + .permissionName = testName, + .resDeviceID = {testName}}; std::vector permStateList; permStateList.emplace_back(infoManagerTestState); HapTokenInfoForSync remoteTokenInfo = { @@ -60,7 +59,7 @@ namespace OHOS { .permStateList = permStateList }; - result = AccessTokenKit::SetRemoteHapTokenInfo(reinterpret_cast(data), remoteTokenInfo); + result = AccessTokenKit::SetRemoteHapTokenInfo(testName, remoteTokenInfo); } #endif return result; diff --git a/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn b/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn index fbfdebf50ae9cd6223c102b80eaf064b5059caec..72eafe673e0f2efac92d963d2927a17fca7b4580 100644 --- a/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("SetRemoteNativeTokenInfoFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp b/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp index 60f33a71144027afb6122c3a324c2bd77cc758a0..73aaf6003ab6dbaffb448feae16f5fa28455e783 100644 --- a/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp +++ b/test/fuzztest/access_token/setremotenativetokeninfo_fuzzer/setremotenativetokeninfo_fuzzer.cpp @@ -31,27 +31,26 @@ namespace OHOS { #ifdef TOKEN_SYNC_ENABLE - std::string testdata; if ((data == nullptr) || (size <= 0)) { return result; } if (size > 0) { - testdata = reinterpret_cast(data); + std::string testName(reinterpret_cast(data), size); AccessTokenID TOKENID = static_cast(size); NativeTokenInfoForSync native1 = { .baseInfo.apl = APL_NORMAL, .baseInfo.ver = 1, - .baseInfo.processName = testdata, - .baseInfo.dcap = {testdata, testdata}, + .baseInfo.processName = testName, + .baseInfo.dcap = {testName, testName}, .baseInfo.tokenID = TOKENID, .baseInfo.tokenAttr = 0, - .baseInfo.nativeAcls = {testdata}, + .baseInfo.nativeAcls = {testName}, }; std::vector nativeTokenInfoList; nativeTokenInfoList.emplace_back(native1); - result = AccessTokenKit::SetRemoteNativeTokenInfo(reinterpret_cast(data), nativeTokenInfoList); + result = AccessTokenKit::SetRemoteNativeTokenInfo(testName, nativeTokenInfoList); } #endif diff --git a/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn b/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn index 2ae1796e744ff1822440024ce7581ab3c6b2b9f9..e3cf9b7acb0aca66305ffb4e7a38ab75c7443437 100644 --- a/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/updatehaptoken_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("UpdateHapTokenFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp b/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp index 4fcdd1c352671d7f0e66154459457980e20e3a42..030d7fe1345db33944058fa1da14b3b5b867543e 100644 --- a/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp +++ b/test/fuzztest/access_token/updatehaptoken_fuzzer/updatehaptoken_fuzzer.cpp @@ -28,38 +28,37 @@ namespace OHOS { bool UpdateHapTokenFuzzTest(const uint8_t* data, size_t size) { bool result = false; - std::string testdata; if ((data == nullptr) || (size <= 0)) { return result; } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - testdata = reinterpret_cast(data); + std::string testName(reinterpret_cast(data), size); PermissionDef TestPermDef = { - .permissionName = testdata, - .bundleName = testdata, + .permissionName = testName, + .bundleName = testName, .grantMode = 1, .availableLevel = APL_NORMAL, - .label = testdata, + .label = testName, .labelId = 1, - .description = testdata, + .description = testName, .descriptionId = 1 }; PermissionStateFull TestState = { - .permissionName = testdata, + .permissionName = testName, .isGeneral = true, - .resDeviceID = {testdata}, + .resDeviceID = {testName}, .grantStatus = {PermissionState::PERMISSION_GRANTED}, .grantFlags = {1}, }; HapPolicyParams TestPolicyPrams = { .apl = APL_NORMAL, - .domain = testdata, + .domain = testName, .permList = {TestPermDef}, .permStateList = {TestState} }; - - result = AccessTokenKit::UpdateHapToken(TOKENID, testdata, TestPolicyPrams); + constexpr int32_t DEFAULT_API_VERSION = 8; + result = AccessTokenKit::UpdateHapToken(TOKENID, testName, DEFAULT_API_VERSION, TestPolicyPrams); } return result; } diff --git a/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn b/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn index d373c815713442263d787b034b55b3e7a31393c0..6d34b2970e4029dedd162ae2720cd0f84bf0ad3d 100644 --- a/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("VerifyAccessToken001FuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp b/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp index ec6ff93689895931158108758bef7fe98290192e..659df6dcbb7a08d6275b16ba33e8c7613dc7b33d 100644 --- a/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp +++ b/test/fuzztest/access_token/verifyaccesstoken001_fuzzer/verifyaccesstoken001_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::VerifyAccessToken(TOKENID, TOKENID, reinterpret_cast(data)); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::VerifyAccessToken(TOKENID, TOKENID, testName); } return result; } diff --git a/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn b/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn index 96160481713587bbcef647043bfb2ab642f657ba..89dadedb29760f980be6670110342bd7d63ee35c 100644 --- a/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn +++ b/test/fuzztest/access_token/verifyaccesstoken_fuzzer/BUILD.gn @@ -34,13 +34,10 @@ ohos_fuzztest("VerifyAccessTokenFuzzTest") { deps = [ "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk" ] + configs = [ "//base/security/access_token/config:coverage_flags" ] + external_deps = [ "c_utils:utils", "hiviewdfx_hilog_native:libhilog", ] - - defines = [ - "ACCOUNT_LOG_TAG = \"AccessTokenFuzzTest\"", - "LOG_DOMAIN = 0xD001B00", - ] } diff --git a/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp b/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp index de192b189201ad65264335e22dc077c2acc86a1a..34ef0098adbea1f7ab6a5264b361e932a4d05b7e 100644 --- a/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp +++ b/test/fuzztest/access_token/verifyaccesstoken_fuzzer/verifyaccesstoken_fuzzer.cpp @@ -33,7 +33,8 @@ namespace OHOS { } if (size > 0) { AccessTokenID TOKENID = static_cast(size); - result = AccessTokenKit::VerifyAccessToken(TOKENID, reinterpret_cast(data)); + std::string testName(reinterpret_cast(data), size); + result = AccessTokenKit::VerifyAccessToken(TOKENID, testName); } return result; } diff --git a/tools/accesstoken/BUILD.gn b/tools/accesstoken/BUILD.gn index d5ef0095d6a3f6d16fed5006e7f8f255002a6b2b..e571b7a6bb9cf5b97a15989c683fe05124a06be0 100644 --- a/tools/accesstoken/BUILD.gn +++ b/tools/accesstoken/BUILD.gn @@ -21,6 +21,8 @@ ohos_source_set("tools_atm_source_set") { "${ability_runtime_path}/tools/aa/include", "//base/security/access_token/interfaces/innerkits/accesstoken/main/cpp/include", "//base/security/access_token/interfaces/innerkits/privacy/include", + "//foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/bundlemgr", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "${ability_runtime_services_path}/common/include", ] @@ -44,10 +46,8 @@ ohos_source_set("tools_atm_source_set") { } external_deps = [ - "bundle_framework:appexecfwk_core", "c_utils:utils", "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", ] subsystem_name = "security" diff --git a/tools/accesstoken/include/atm_command.h b/tools/accesstoken/include/atm_command.h index 7ff2ec3192af7ef326ab49666e5c8237a0f5d92f..ad69570c616f71414a4e0d91d2d541b750ecf289 100644 --- a/tools/accesstoken/include/atm_command.h +++ b/tools/accesstoken/include/atm_command.h @@ -21,18 +21,34 @@ namespace OHOS { namespace Security { namespace AccessToken { +typedef enum TypeOptType { + DEFAULT = 0, + DUMP_TOKEN, + DUMP_RECORD, + PERM_GRANT, + PERM_REVOKE, +} OptType; + const std::string TOOLS_NAME = "atm"; const std::string HELP_MSG = "usage: atm