diff --git a/bundle.json b/bundle.json index 9a569db586553ce268493299cd781be24b951201..963dbf16eabf95258f270eb69072ab265d35d99c 100644 --- a/bundle.json +++ b/bundle.json @@ -59,7 +59,8 @@ "selinux_adapter", "sqlite", "window_manager", - "zlib" + "zlib", + "runtime_core" ], "third_party": [] }, @@ -71,7 +72,8 @@ "fwk_group": [ "//base/security/access_token/interfaces/kits/capi:capi_packages", "//base/security/access_token/interfaces/kits/cj:cj_packages", - "//base/security/access_token/frameworks/js/napi:napi_packages" + "//base/security/access_token/frameworks/js/napi:napi_packages", + "//base/security/access_token/frameworks/ets/ani:arkts_package" ], "service_group": [ "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", diff --git a/frameworks/ets/ani/BUILD.gn b/frameworks/ets/ani/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..213648161dc7989669c4c318d24bfc577b7cf158 --- /dev/null +++ b/frameworks/ets/ani/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright (c) 2025 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("//base/security/access_token/access_token.gni") + +group("arkts_package") { + deps = [] + if (support_jsapi) { + deps += [ + "accesstoken:accesstoken_ets", + "common:common_ets", + "privacy:privacy_ets", + ] + } +} diff --git a/frameworks/ets/ani/accesstoken/BUILD.gn b/frameworks/ets/ani/accesstoken/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6fe0a656122a59623b4de891af30a7b0119da6af --- /dev/null +++ b/frameworks/ets/ani/accesstoken/BUILD.gn @@ -0,0 +1,92 @@ +# Copyright (c) 2025 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("//base/security/access_token/access_token.gni") +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/ace/ace.gni") + +ohos_shared_library("accesstoken_ani") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + cflags_cc = [ "-DHILOG_ENABLE" ] + include_dirs = [ + "${access_token_path}/frameworks/common/include", + "${access_token_path}/interfaces/innerkits/accesstoken/include", + "./include", + "${access_token_path}/interfaces/innerkits/token_setproc/include", + "${access_token_path}/interfaces/innerkits/token_callback/include", + "${access_token_path}/frameworks/ets/ani/common/include", + ] + sources = [ "src/ability_access_ctrl.cpp" ] + + deps = [ + "${access_token_path}/frameworks/ets/ani/common:libani_common", + "${access_token_path}/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "${access_token_path}/interfaces/innerkits/token_callback:libtoken_callback_sdk", + "${access_token_path}/interfaces/innerkits/token_setproc:libtokensetproc_shared", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:ani_base_context", + "ability_runtime:appkit_native", + "ability_runtime:ui_extension", + "ace_engine:ace_uicontent", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_single", + "napi:ace_napi", + "runtime_core:ani", + "runtime_core:libarkruntime", + ] + + if (eventhandler_enable == true) { + cflags_cc += [ "-DEVENTHANDLER_ENABLE" ] + external_deps += [ "eventhandler:libeventhandler" ] + } + + part_name = "access_token" + subsystem_name = "security" +} + +generate_static_abc("ability_access_ctrl") { + base_url = "./ets" + files = [ "./ets/@ohos.abilityAccessCtrl.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_access_ctrl.abc" +} + +ohos_prebuilt_etc("ability_access_ctrl_etc") { + source = "$target_out_dir/ability_access_ctrl.abc" + deps = [ ":ability_access_ctrl" ] + module_install_dir = "framework" + part_name = "access_token" + subsystem_name = "security" +} + +group("accesstoken_ets") { + deps = [ + ":ability_access_ctrl_etc", + ":accesstoken_ani", + ] +} diff --git a/frameworks/ets/ani/accesstoken/ets/@ohos.abilityAccessCtrl.ets b/frameworks/ets/ani/accesstoken/ets/@ohos.abilityAccessCtrl.ets new file mode 100644 index 0000000000000000000000000000000000000000..abf473cca852dadbb8f356595bde68d1daa8e71d --- /dev/null +++ b/frameworks/ets/ani/accesstoken/ets/@ohos.abilityAccessCtrl.ets @@ -0,0 +1,403 @@ +/* + * Copyright (c) 2025 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 { AsyncCallback, Callback, BusinessError } from '@ohos.base'; +import { Permissions } from 'permissions'; +import type _PermissionRequestResult from 'security.PermissionRequestResult'; +import Context from 'application.Context' +import hilog from '@ohos.hilog'; + +function PARAM_ERROR_MSG(param: string, type: string): string { + return `Parameter Error. The type of "${param}" must be ${type}.`; +} + +export { Permissions }; + +export type PermissionRequestResult = _PermissionRequestResult; + +export default namespace abilityAccessCtrl { + + loadLibrary("accesstoken_ani.z"); + export enum GrantStatus { + PERMISSION_DENIED = -1, + PERMISSION_GRANTED = 0 + } + + export enum PermissionRequestToggleStatus { + CLOSED = 0, + OPEN = 1, + } + + export enum PermissionStatus { + DENIED = -1, + GRANTED = 0, + NOT_DETERMINED = 1, + INVALID = 2, + RESTRICTED = 3 + } + + interface PermissionStateChangeInfo { + change: PermissionStateChangeType; + tokenID: int; + permissionName: Permissions; + } + + export enum PermissionStateChangeType { + PERMISSION_REVOKED_OPER = 0, + PERMISSION_GRANTED_OPER = 1 + } + + export enum SwitchType { + CAMERA = 0, + MICROPHONE = 1, + LOCATION = 2, + } + + enum STSErrorCode { + STS_OK = 0, + STS_ERROR_PERMISSION_DENIED = 201, + STS_ERROR_NOT_SYSTEM_APP = 202, + STS_ERROR_PARAM_ILLEGAL = 401, + STS_ERROR_SYSTEM_CAPABILITY_NOT_SUPPORT = 801, + } ; + function validateRequestParams(context: Context, permissionList: Array): void { + if (typeof context === "undefined" || context == null) { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("context", "UIAbility or UIExtension Context"); + throw err; + } + if (typeof permissionList !== "object" || !Array.isArray(permissionList) || + permissionList.length == 0 || typeof permissionList[0] !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionList", "Array"); + throw err; + } + } + + native function createAtManager(): AtManager; + interface AtManager { + checkAccessTokenExecute(tokenID: int, permissionName: Permissions): int; + requestPermissionsFromUserExecute( + context: Context, permissionList: Array): PermissionRequestResult; + requestPermissionOnSettingExecute(context: Context, permissionList: Array): Array; + revokeUserGrantedPermissionExecute(tokenID: int, permissionName: Permissions, permissionFlags: int): void; + getPermissionsStatusExecute(tokenID: int, permissionList: Array): Array; + getVersionExecute(): int; + getPermissionFlagsExecute(tokenID: int, permissionName: Permissions): int; + setPermissionRequestToggleStatusExecute(permissionName: Permissions, status: int): void; + getPermissionRequestToggleStatusExecute(permissionName: Permissions): int; + checkAccessTokenSync(tokenID: int, permissionName: Permissions): GrantStatus; + verifyAccessTokenSync(tokenID: int, permissionName: Permissions): GrantStatus; + checkAccessToken(tokenID: int, permissionName: Permissions): Promise; + verifyAccessToken(tokenID: int, permissionName: Permissions): Promise; + + requestPermissionsFromUser( + context: Context, permissionList: Array, + requestCallback: AsyncCallback): void; + + requestPermissionsFromUser( + context: Context, permissionList: Array): Promise; + + requestPermissionOnSetting( + context: Context, + permissionList: Array): Promise>; + + grantUserGrantedPermission( + tokenID: int, + permissionName: Permissions, + permissionFlags: int, + callback: AsyncCallback): void; + + grantUserGrantedPermission( + tokenID: int, + permissionName: Permissions, + permissionFlags: int): Promise; + + revokeUserGrantedPermission(tokenID: int, permissionName: Permissions, permissionFlags: int): Promise; + + revokeUserGrantedPermission( + tokenID: int, permissionName: Permissions, permissionFlags: int, callback: AsyncCallback): void; + + getVersion(): Promise; + + getPermissionsStatus(tokenID: int, permissionList: Array): Promise>; + + getPermissionFlags(tokenID: int, permissionName: Permissions): Promise; + + setPermissionRequestToggleStatus( + permissionName: Permissions, status: PermissionRequestToggleStatus): Promise; + + getPermissionRequestToggleStatus(permissionName: Permissions): Promise; + } + + class AtManagerInner implements AtManager { + native checkAccessTokenExecute(tokenID: int, permissionName: Permissions): int; + native requestPermissionsFromUserExecute( + context: Context, permissionList: Array): PermissionRequestResult; + native requestPermissionOnSettingExecute( + context: Context, permissionList: Array): Array; + native grantUserGrantedPermissionExecute(tokenID: int, permissionName: Permissions, permissionFlags: int): void; + native revokeUserGrantedPermissionExecute( + tokenID: int, permissionName: Permissions, permissionFlags: int): void; + native getPermissionsStatusExecute(tokenID: int, permissionList: Array): Array; + native getVersionExecute(): int; + native getPermissionFlagsExecute(tokenID: int, permissionName: Permissions): int; + native setPermissionRequestToggleStatusExecute(permissionName: Permissions, status: int): void; + native getPermissionRequestToggleStatusExecute(permissionName: Permissions): int; + + verifyAccessTokenSync(tokenID: int, permissionName: Permissions): GrantStatus { + let result = this.checkAccessTokenExecute(tokenID, permissionName); + return result as GrantStatus; + } + + checkAccessTokenSync(tokenID: int, permissionName: Permissions): GrantStatus { + let result = this.checkAccessTokenExecute(tokenID, permissionName); + return result as GrantStatus; + } + + checkAccessToken(tokenID: int, permissionName: Permissions): Promise { + let p = new Promise(( + resolve: (v: GrantStatus) => void, reject: (error: BusinessError) => void) => { + let p1 = taskpool.execute((): GrantStatus => { + return new AtManagerInner().checkAccessTokenExecute(tokenID, permissionName) as GrantStatus; + }); + p1.then((e: NullishType) => { + resolve(e as GrantStatus); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + verifyAccessToken(tokenID: int, permissionName: Permissions): Promise { + let p = new Promise(( + resolve: (v: GrantStatus) => void, reject: (error: BusinessError) => void) => { + let p1 = taskpool.execute((): GrantStatus => { + return new AtManagerInner().checkAccessTokenExecute(tokenID, permissionName) as GrantStatus; + }); + p1.then((e: NullishType) => { + resolve(e as GrantStatus); + }).catch((err: Error): void => { + resolve(GrantStatus.PERMISSION_DENIED); + }); + }); + return p; + } + + requestPermissionsFromUser(context: Context, permissionList: Array, + callback:AsyncCallback): void { + validateRequestParams(context, permissionList); + let fun = async() => { + let work = new EAWorker(); + try { + let job = work.run(() : PermissionRequestResult => { + return new AtManagerInner().requestPermissionsFromUserExecute(context, permissionList); + }) + let result = job.Await(); + work.join(); + let retError = new BusinessError(); + callback(retError, result as PermissionRequestResult); + } catch (err: BusinessError) { + work.join(); + const defaultResult: PermissionRequestResult = {}; + callback(err, defaultResult); + } + }; + fun(); + } + + requestPermissionsFromUser(context: Context, permissionList: Array): + Promise { + validateRequestParams(context, permissionList); + + let p = new Promise(( + resolve: (v: PermissionRequestResult) => void, reject: (error: BusinessError) => void) => { + let fun = async() => { + let work = new EAWorker(); + try { + let job = work.run((): PermissionRequestResult => { + return new AtManagerInner().requestPermissionsFromUserExecute(context, permissionList); + }); + let result = job.Await(); + work.join(); + resolve(result as PermissionRequestResult); + } catch (err: BusinessError) { + work.join(); + reject(err); + } + }; + fun(); + }); + return p; + } + + requestPermissionOnSetting(context: Context, permissionList: Array): Promise> { + validateRequestParams(context, permissionList); + let p = new Promise>(( + resolve: (v: Array) => void, reject: (error: BusinessError) => void) => { + let func = async() => { + let work = new EAWorker(); + try { + let job = work.run>((): Array => { + return new AtManagerInner().requestPermissionOnSettingExecute(context, permissionList); + }); + let result = job.Await(); + work.join(); + resolve(result as Array); + } catch (err: BusinessError) { + work.join(); + reject(err); + } + }; + func(); + }); + return p; + } + + grantUserGrantedPermission(tokenID: int, permissionName: Permissions, permissionFlags: int, + callback: AsyncCallback): void { + let p1 = taskpool.execute((): void => { + new AtManagerInner().grantUserGrantedPermissionExecute(tokenID, permissionName, permissionFlags);}); + p1.then(() => { + let err = new BusinessError(); + callback(err, undefined); + }, (err: Error): void => { + callback(err as BusinessError, undefined); + }) + } + + grantUserGrantedPermission(tokenID: int, permissionName: Permissions, permissionFlags: int): Promise { + return new Promise( + (resolve: (v: undefined) => void, reject: (error: BusinessError) => void) : void => { + let p = taskpool.execute(() : void => { + new AtManagerInner().grantUserGrantedPermissionExecute(tokenID, permissionName, permissionFlags); + }); + p.then((e: NullishType) : void => { + resolve(undefined); + }).catch((err: Error) : void => { + reject(err as BusinessError); + }) + }); + } + + revokeUserGrantedPermission(tokenID: int, permissionName: Permissions, permissionFlags: int): Promise { + return new Promise( + (resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p = taskpool.execute((): void => { + new AtManagerInner().revokeUserGrantedPermissionExecute(tokenID, permissionName, permissionFlags); + }); + p.then((e: NullishType): void => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }) + }); + } + + revokeUserGrantedPermission(tokenID: int, permissionName: Permissions, + permissionFlags: int, callback: AsyncCallback): void { + let job = taskpool.execute((): void => { + new AtManagerInner().revokeUserGrantedPermissionExecute(tokenID, permissionName, permissionFlags); + }); + job.then(()=>{ + let err = new BusinessError(); + callback(err, undefined); + }, (err: Error): void=> { + callback(err as BusinessError, undefined); + }) + } + + getVersion(): Promise { + let p = new Promise(( + resolve: (v: int) => void, reject: (error: BusinessError) => void) =>{ + let p1 = taskpool.execute((): int => { + return new AtManagerInner().getVersionExecute() as int; + }); + p1.then((e: NullishType) => { + resolve(e as int); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + getPermissionsStatus( + tokenID: int, permissionList: Array): Promise> { + let p = new Promise>(( + resolve: (v: Array) => void, reject: (error: BusinessError) => void) => { + let p1 = taskpool.execute((): Array => { + return new AtManagerInner().getPermissionsStatusExecute( + tokenID, permissionList) as Array; + }); + p1.then((e: NullishType) => { + resolve(e as Array); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + getPermissionFlags(tokenID: int, permissionName: Permissions): Promise { + let p = new Promise( + (resolve: (v: int) => void, reject: (err: BusinessError) => void): int => { + let p1 = taskpool.execute((): int => { + return new AtManagerInner().getPermissionFlagsExecute(tokenID, permissionName); + }); + p1.then((e: NullishType): void => { + resolve(e as int); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }) + return p; + } + + setPermissionRequestToggleStatus(permissionName: Permissions, status: PermissionRequestToggleStatus): Promise { + let p = new Promise( + (resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p = taskpool.execute((): void => { + new AtManagerInner().setPermissionRequestToggleStatusExecute(permissionName, status); + }); + p.then((e: NullishType): void => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }) + }); + return p; + } + + getPermissionRequestToggleStatus(permissionName: Permissions): Promise { + let p = new Promise( + (resolve: (v: PermissionRequestToggleStatus) => void, + reject: (err: BusinessError) => void): PermissionRequestToggleStatus => { + let p1 = taskpool.execute((): PermissionRequestToggleStatus => { + return new AtManagerInner().getPermissionRequestToggleStatusExecute(permissionName) as PermissionRequestToggleStatus; + }); + p1.then((e: NullishType): void => { + resolve(e as PermissionRequestToggleStatus); + }).catch((err: Error): void => { + reject(err as BusinessError); + }) + }); + return p; + } + } +} diff --git a/frameworks/ets/ani/accesstoken/include/ability_access_ctrl.h b/frameworks/ets/ani/accesstoken/include/ability_access_ctrl.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ac10ad3ae2979840ef2c2b40e5e86137b04f23 --- /dev/null +++ b/frameworks/ets/ani/accesstoken/include/ability_access_ctrl.h @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2025 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 ABILITY_ACCESS_CTRL_H +#define ABILITY_ACCESS_CTRL_H + +#include +#include +#include +#include + +#include "ability.h" +#include "ability_manager_client.h" +#include "access_token.h" +#include "ani.h" +#include "ani_error.h" +#include "permission_grant_info.h" +#include "token_callback_stub.h" +#include "ui_content.h" +#include "ui_extension_context.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +const int32_t PARAM_DEFAULT_VALUE = -1; +struct AtManagerAsyncContext { + AccessTokenID tokenId = 0; + std::string permissionName; + union { + uint32_t flag = 0; + uint32_t status; + }; + int32_t grantStatus = PERMISSION_DENIED; + AtmResult result; +}; + +class AniContextCommon { +public: + static constexpr int32_t MAX_PARAMS_ONE = 1; + static constexpr int32_t MAX_PARAMS_TWO = 2; + static constexpr int32_t MAX_PARAMS_THREE = 3; + static constexpr int32_t MAX_PARAMS_FOUR = 4; + static constexpr int32_t MAX_LENGTH = 256; + static constexpr int32_t MAX_WAIT_TIME = 1000; + static constexpr int32_t VALUE_MAX_LEN = 32; +}; + +struct PermissionParamCache { + long long sysCommitIdCache = PARAM_DEFAULT_VALUE; + int32_t commitIdCache = PARAM_DEFAULT_VALUE; + int32_t handle = PARAM_DEFAULT_VALUE; + std::string sysParamCache; +}; + +struct PermissionStatusCache { + int32_t status; + std::string paramValue; +}; + +static PermissionParamCache g_paramCache; +std::map g_cache; + +struct RequestAsyncContext { + AccessTokenID tokenId = 0; + std::string bundleName; + bool needDynamicRequest = true; + AtmResult result; + int32_t instanceId = -1; + std::vector permissionList; + std::vector grantResults; + std::vector permissionsState; + ani_object requestResult = nullptr; + std::vector dialogShownResults; + std::vector permissionQueryResults; + std::vector errorReasons; + Security::AccessToken::PermissionGrantInfo info; + std::shared_ptr abilityContext; + std::shared_ptr uiExtensionContext; + bool uiAbilityFlag = false; + bool uiExtensionFlag = false; + bool uiContentFlag = false; + bool releaseFlag = false; + std::mutex loadlock; +#ifdef EVENTHANDLER_ENABLE + std::shared_ptr handler_ = nullptr; +#endif +}; + +class UIExtensionCallback { +public: + explicit UIExtensionCallback(const std::shared_ptr& reqContext); + ~UIExtensionCallback(); + void SetSessionId(int32_t sessionId); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string& message); + void OnRemoteReady(const std::shared_ptr& uiProxy); + void OnDestroy(); + void ReleaseHandler(int32_t code); + +private: + int32_t sessionId_ = 0; + std::shared_ptr reqContext_ = nullptr; +}; + +class AuthorizationResult : public Security::AccessToken::TokenCallbackStub { +public: + AuthorizationResult(std::shared_ptr& data) : data_(data) {} + virtual ~AuthorizationResult() override = default; + + virtual void GrantResultsCallback( + const std::vector& permissionList, const std::vector& grantResults) override; + virtual void WindowShownCallback() override; + +private: + std::shared_ptr data_ = nullptr; +}; + +class RequestAsyncInstanceControl { +public: + static bool AddCallbackByInstanceId(std::shared_ptr& asyncContext); + static void ExecCallback(int32_t id); + static void CheckDynamicRequest(std::shared_ptr& asyncContext, bool& isDynamic); + +private: + static std::map>> instanceIdMap_; + static std::mutex instanceIdMutex_; +}; + +struct ResultCallback { + std::vector permissions; + std::vector grantResults; + std::vector dialogShownResults; + std::shared_ptr data = nullptr; +}; + +struct RequestPermOnSettingAsyncContext { + AccessTokenID tokenId = 0; + AtmResult result; + PermissionGrantInfo info; + + std::vector permissionList; + napi_value requestResult = nullptr; + std::vector stateList; + + std::shared_ptr abilityContext; + std::shared_ptr uiExtensionContext; + bool uiAbilityFlag = false; + std::mutex loadlock; + +#ifdef EVENTHANDLER_ENABLE + std::shared_ptr handler_ = + std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); +#endif +}; + +class PermissonOnSettingUICallback { +public: + explicit PermissonOnSettingUICallback(ani_env* env, + const std::shared_ptr& reqContext); + ~PermissonOnSettingUICallback(); + void SetSessionId(int32_t sessionId); + void ReleaseHandler(int32_t code); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string& message); + void OnRemoteReady(const std::shared_ptr& uiProxy); + void OnDestroy(); + +private: + ani_env* env_; + std::shared_ptr reqContext_ = nullptr; + int32_t sessionId_ = 0; + + std::mutex lockReleaseFlag; + bool releaseFlag = false; +}; + +struct PermissonOnSettingResultCallback { + int32_t jsCode; + std::vector stateList; + std::shared_ptr data = nullptr; +}; + +std::map>> RequestAsyncInstanceControl::instanceIdMap_; +std::mutex RequestAsyncInstanceControl::instanceIdMutex_; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // ABILITY_ACCESS_CTRL_H \ No newline at end of file diff --git a/frameworks/ets/ani/accesstoken/src/ability_access_ctrl.cpp b/frameworks/ets/ani/accesstoken/src/ability_access_ctrl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41be0f49ac00133eeb714b12e87440bf635fbc0e --- /dev/null +++ b/frameworks/ets/ani/accesstoken/src/ability_access_ctrl.cpp @@ -0,0 +1,1605 @@ +/* + * Copyright (c) 2025 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 "ability_access_ctrl.h" + +#include +#include + +#include "access_token.h" +#include "access_token_error.h" +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "ani_base_context.h" +#include "ani_error.h" +#include "ani_utils.h" +#include "hisysevent.h" +#include "parameter.h" +#include "permission_list_state.h" +#include "permission_map.h" +#include "token_setproc.h" +#include "want.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +std::mutex g_lockFlag; +std::mutex g_lockWindowFlag; +bool g_windowFlag = false; +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AniAbilityAccessCtrl" }; +constexpr int32_t MAX_LENGTH = 256; +constexpr int32_t REQUEST_REALDY_EXIST = 1; +const int32_t PERM_NOT_BELONG_TO_SAME_GROUP = 2; +const int32_t PERM_IS_NOT_DECLARE = 3; +const int32_t ALL_PERM_GRANTED = 4; +const int32_t PERM_REVOKE_BY_USER = 5; +std::condition_variable g_loadedCond; +std::mutex g_lockCache; + +static constexpr const char* PERMISSION_STATUS_CHANGE_KEY = "accesstoken.permission.change"; + +const std::string PERMISSION_KEY = "ohos.user.grant.permission"; +const std::string PERMISSION_SETTING_KEY = "ohos.user.setting.permission"; +const std::string STATE_KEY = "ohos.user.grant.permission.state"; +const std::string RESULT_KEY = "ohos.user.grant.permission.result"; +const std::string EXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType"; +const std::string UI_EXTENSION_TYPE = "sys/commonUI"; +const std::string ORI_PERMISSION_MANAGER_BUNDLE_NAME = "com.ohos.permissionmanager"; +const std::string TOKEN_KEY = "ohos.ability.params.token"; +const std::string CALLBACK_KEY = "ohos.ability.params.callback"; +const std::string WINDOW_RECTANGLE_LEFT_KEY = "ohos.ability.params.request.left"; +const std::string WINDOW_RECTANGLE_TOP_KEY = "ohos.ability.params.request.top"; +const std::string WINDOW_RECTANGLE_HEIGHT_KEY = "ohos.ability.params.request.height"; +const std::string WINDOW_RECTANGLE_WIDTH_KEY = "ohos.ability.params.request.width"; +const std::string REQUEST_TOKEN_KEY = "ohos.ability.params.request.token"; +const std::string RESULT_ERROR_KEY = "ohos.user.setting.error_code"; +const std::string PERMISSION_RESULT_KEY = "ohos.user.setting.permission.result"; + +#define SETTER_METHOD_NAME(property) "" #property +#define ANI_AUTO_SIZE SIZE_MAX + +static void UpdateGrantPermissionResultOnly(const std::vector& permissions, + const std::vector& grantResults, std::shared_ptr& data, std::vector& newGrantResults) +{ + size_t size = permissions.size(); + for (size_t i = 0; i < size; i++) { + int result = static_cast(data->permissionsState[i]); + if (data->permissionsState[i] == AccessToken::DYNAMIC_OPER) { + result = data->result.errorCode == AccessToken::RET_SUCCESS ? grantResults[i] : AccessToken::INVALID_OPER; + } + newGrantResults.emplace_back(result); + } +} + +static bool IsDynamicRequest(std::shared_ptr& asyncContext) +{ + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "asyncContext nullptr"); + return false; + } + std::vector permList; + for (const auto& permission : asyncContext->permissionList) { + AccessToken::PermissionListState permState; + permState.permissionName = permission; + permState.errorReason = SERVICE_ABNORMAL; + permState.state = AccessToken::INVALID_OPER; + permList.emplace_back(permState); + } + auto ret = AccessToken::AccessTokenKit::GetSelfPermissionsState(permList, asyncContext->info); + ACCESSTOKEN_LOG_INFO(LABEL, + "TokenID: %{public}d, bundle: %{public}s, uiExAbility: %{public}s, serExAbility: %{public}s.", + asyncContext->tokenId, asyncContext->info.grantBundleName.c_str(), asyncContext->info.grantAbilityName.c_str(), + asyncContext->info.grantServiceAbilityName.c_str()); + if (ret == AccessToken::FORBIDDEN_OPER) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FORBIDDEN_OPER"); + for (auto& perm : permList) { + perm.state = AccessToken::INVALID_OPER; + perm.errorReason = PRIVACY_STATEMENT_NOT_AGREED; + } + } + for (const auto& permState : permList) { + ACCESSTOKEN_LOG_INFO(LABEL, "Permission: %{public}s: state: %{public}d, errorReason: %{public}d", + permState.permissionName.c_str(), permState.state, permState.errorReason); + asyncContext->permissionsState.emplace_back(permState.state); + asyncContext->dialogShownResults.emplace_back(permState.state == AccessToken::TypePermissionOper::DYNAMIC_OPER); + asyncContext->errorReasons.emplace_back(permState.errorReason); + } + if (permList.size() != asyncContext->permissionList.size()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permList.size: %{public}zu, permissionList.size: %{public}zu", permList.size(), + asyncContext->permissionList.size()); + return false; + } + return ret == AccessToken::TypePermissionOper::DYNAMIC_OPER; +} + +static OHOS::Ace::UIContent* GetUIContent(const std::shared_ptr& abilityContext, + std::shared_ptr& uiExtensionContext, bool uiAbilityFlag) +{ + OHOS::Ace::UIContent* uiContent = nullptr; + if (uiAbilityFlag) { + if (abilityContext == nullptr) { + return nullptr; + } + uiContent = abilityContext->GetUIContent(); + } else { + if (uiExtensionContext == nullptr) { + return nullptr; + } + uiContent = uiExtensionContext->GetUIContent(); + } + return uiContent; +} + +static void CreateUIExtensionMainThread(std::shared_ptr& asyncContext, + const OHOS::AAFwk::Want& want, const OHOS::Ace::ModalUIExtensionCallbacks& uiExtensionCallbacks, + const std::shared_ptr& uiExtCallback) +{ + auto task = [asyncContext, want, uiExtensionCallbacks, uiExtCallback]() { + OHOS::Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if (uiContent == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Get ui content failed!"); + asyncContext->result.errorCode = AccessToken::RET_FAILED; + asyncContext->uiExtensionFlag = false; + asyncContext->loadlock.unlock(); + return; + } + + OHOS::Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + if (sessionId == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Create component failed, sessionId is 0"); + asyncContext->result.errorCode = AccessToken::RET_FAILED; + asyncContext->uiExtensionFlag = false; + asyncContext->loadlock.unlock(); + return; + } + uiExtCallback->SetSessionId(sessionId); + }; +#ifdef EVENTHANDLER_ENABLE + if (asyncContext->handler_ != nullptr) { + asyncContext->handler_->PostSyncTask(task, "AT:CreateUIExtensionMainThread"); + } else { + task(); + } +#else + task(); +#endif +} + +static bool CreateServiceExtension(std::shared_ptr& asyncContext) +{ + if (!asyncContext->uiAbilityFlag) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UIExtension ability can not pop service ablility window!"); + asyncContext->needDynamicRequest = false; + asyncContext->result.errorCode = RET_FAILED; + return false; + } + OHOS::sptr remoteObject = new (std::nothrow) AuthorizationResult(asyncContext); + if (remoteObject == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Create window failed!"); + asyncContext->needDynamicRequest = false; + asyncContext->result.errorCode = RET_FAILED; + return false; + } + OHOS::AAFwk::Want want; + want.SetElementName(asyncContext->info.grantBundleName, asyncContext->info.grantServiceAbilityName); + want.SetParam(PERMISSION_KEY, asyncContext->permissionList); + want.SetParam(STATE_KEY, asyncContext->permissionsState); + want.SetParam(TOKEN_KEY, asyncContext->abilityContext->GetToken()); + want.SetParam(CALLBACK_KEY, remoteObject); + + int32_t left; + int32_t top; + int32_t width; + int32_t height; + asyncContext->abilityContext->GetWindowRect(left, top, width, height); + want.SetParam(WINDOW_RECTANGLE_LEFT_KEY, left); + want.SetParam(WINDOW_RECTANGLE_TOP_KEY, top); + want.SetParam(WINDOW_RECTANGLE_WIDTH_KEY, width); + want.SetParam(WINDOW_RECTANGLE_HEIGHT_KEY, height); + want.SetParam(REQUEST_TOKEN_KEY, asyncContext->abilityContext->GetToken()); + int32_t ret = OHOS::AAFwk::AbilityManagerClient::GetInstance()->RequestDialogService( + want, asyncContext->abilityContext->GetToken()); + ACCESSTOKEN_LOG_INFO(LABEL, "Request end, ret: %{public}d, tokenId: %{public}d, permNum: %{public}zu", ret, + asyncContext->tokenId, asyncContext->permissionList.size()); + return true; +} + +static bool CreateUIExtension(std::shared_ptr& asyncContext) +{ + OHOS::AAFwk::Want want; + want.SetElementName(asyncContext->info.grantBundleName, asyncContext->info.grantAbilityName); + want.SetParam(PERMISSION_KEY, asyncContext->permissionList); + want.SetParam(STATE_KEY, asyncContext->permissionsState); + want.SetParam(EXTENSION_TYPE_KEY, UI_EXTENSION_TYPE); + + auto uiExtCallback = std::make_shared(asyncContext); + OHOS::Ace::ModalUIExtensionCallbacks uiExtensionCallbacks = { + [uiExtCallback](int32_t releaseCode) { uiExtCallback->OnRelease(releaseCode); }, + [uiExtCallback]( + int32_t resultCode, const OHOS::AAFwk::Want& result) { uiExtCallback->OnResult(resultCode, result); }, + [uiExtCallback](const OHOS::AAFwk::WantParams& receive) { uiExtCallback->OnReceive(receive); }, + [uiExtCallback](int32_t code, const std::string& name, [[maybe_unused]] const std::string& message) { + uiExtCallback->OnError(code, name, name); + }, + [uiExtCallback](const std::shared_ptr& uiProxy) { + uiExtCallback->OnRemoteReady(uiProxy); + }, + [uiExtCallback]() { uiExtCallback->OnDestroy(); }, + }; + CreateUIExtensionMainThread(asyncContext, want, uiExtensionCallbacks, uiExtCallback); + return true; +} + +static void GetInstanceId(std::shared_ptr& asyncContext) +{ + auto task = [asyncContext]() { + OHOS::Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if (uiContent == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Get ui content failed!"); + return; + } + asyncContext->uiContentFlag = true; + asyncContext->instanceId = uiContent->GetInstanceId(); + }; +#ifdef EVENTHANDLER_ENABLE + if (asyncContext->handler_ != nullptr) { + asyncContext->handler_->PostSyncTask(task, "AT:GetInstanceId"); + } else { + task(); + } +#else + task(); +#endif +} + +static ani_ref ConvertAniArrayString(ani_env* env, const std::vector& cArray) +{ + ani_size length = cArray.size(); + ani_array_ref aArrayRef = nullptr; + ani_class aStringcls = nullptr; + if (env->FindClass("Lstd/core/String;", &aStringcls) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayString FindClass String failed"); + return nullptr; + } + ani_ref undefinedRef = nullptr; + if (ANI_OK != env->GetUndefined(&undefinedRef)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayString GetUndefined failed"); + return nullptr; + } + if (env->Array_New_Ref(aStringcls, length, undefinedRef, &aArrayRef) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayString Array_New_Ref failed "); + return nullptr; + } + ani_string aString = nullptr; + for (ani_size i = 0; i < length; ++i) { + env->String_NewUTF8(cArray[i].c_str(), cArray[i].size(), &aString); + env->Array_Set_Ref(aArrayRef, i, aString); + } + ani_ref aRef = nullptr; + if (env->GlobalReference_Create(aArrayRef, &aRef) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayString GlobalReference_Create failed "); + return nullptr; + } + return aRef; +} + +static ani_ref ConvertAniArrayInt(ani_env* env, const std::vector& cArray) +{ + ani_size length = cArray.size(); + ani_array_int aArrayInt = nullptr; + if (env->Array_New_Int(length, &aArrayInt) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayInt Array_New_Int failed "); + return nullptr; + } + for (ani_size i = 0; i < length; ++i) { + env->Array_SetRegion_Int(aArrayInt, i, length, &cArray[i]); + } + ani_ref aRef = nullptr; + if (env->GlobalReference_Create(aArrayInt, &aRef) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayInt GlobalReference_Create failed "); + return nullptr; + } + return aRef; +} + +static ani_ref ConvertAniArrayBool(ani_env* env, const std::vector& cArray) +{ + ani_size length = cArray.size(); + ani_array_boolean aArrayBool = nullptr; + if (env->Array_New_Boolean(length, &aArrayBool) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayBool Array_New_Boolean failed "); + return nullptr; + } + std::vector boolArray(length); + for (ani_size i = 0; i < length; ++i) { + boolArray[i] = cArray[i]; + } + for (ani_size i = 0; i < length; ++i) { + env->Array_SetRegion_Boolean(aArrayBool, i, length, &boolArray[i]); + } + ani_ref aRef = nullptr; + if (env->GlobalReference_Create(aArrayBool, &aRef) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertAniArrayBool GlobalReference_Create failed "); + return nullptr; + } + return aRef; +} + +template +static inline bool CallSetter(ani_env* env, ani_class cls, ani_object object, const char* setterName, valueType value) +{ + ani_status status = ANI_ERROR; + ani_field fieldValue; + if (env->Class_FindField(cls, setterName, &fieldValue) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindField Fail %{public}d ", status); + return false; + } + if ((status = env->Object_SetField_Ref(object, fieldValue, value)) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetField_Ref Fail %{public}d ", status); + return false; + } + return true; +} + +std::string ANIUtils_ANIStringToStdString(ani_env* env, ani_string ani_str) +{ + ani_size strSize; + if (env->String_GetUTF8Size(ani_str, &strSize) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_GetUTF8Size error"); + return ""; + } + std::vector buffer(strSize + 1); + char* utf8_buffer = buffer.data(); + + ani_size bytes_written = 0; + if (env->String_GetUTF8(ani_str, utf8_buffer, strSize + 1, &bytes_written) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_GetUTF8 error"); + return ""; + } + utf8_buffer[bytes_written] = '\0'; + std::string content = std::string(utf8_buffer); + return content; +} + +static bool ProcessArrayString([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_array_ref arrayObj, std::vector& permissionList) +{ + ani_size length; + if (ANI_OK != env->Array_GetLength(arrayObj, &length)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Array_GetLength FAILED"); + return false; + } + for (ani_size i = 0; i < length; i++) { + ani_ref stringEntryRef; + if (ANI_OK != env->Object_CallMethodByName_Ref( + arrayObj, "$_get", "I:Lstd/core/Object;", &stringEntryRef, static_cast(i))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_CallMethodByName_Ref _get Failed"); + return false; + } + auto strEntryRef = ANIUtils_ANIStringToStdString(env, static_cast(stringEntryRef)); + if (strEntryRef.empty()) { + return false; + } else { + permissionList.emplace_back(strEntryRef); + } + } + return true; +} + +static ani_object WrapResult(ani_env* env, std::shared_ptr& asyncContext) +{ + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + if ((status = env->FindClass("Lsecurity/PermissionRequestResult/PermissionRequestResult;", &cls)) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass status %{public}d ", static_cast(status)); + return nullptr; + } + if (cls == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "null cls"); + return nullptr; + } + ani_method method = nullptr; + if ((status = env->Class_FindMethod(cls, "", ":V", &method)) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindMethod status %{public}d ", static_cast(status)); + return nullptr; + } + ani_object aObject = nullptr; + if ((status = env->Object_New(cls, method, &aObject)) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_New status %{public}d ", static_cast(status)); + return nullptr; + } + auto state = asyncContext->needDynamicRequest ? asyncContext->grantResults : asyncContext->permissionsState; + ani_ref strPermissions = ConvertAniArrayString(env, asyncContext->permissionList); + ani_ref intAuthResults = ConvertAniArrayInt(env, state); + ani_ref boolDialogShownResults = ConvertAniArrayBool(env, asyncContext->dialogShownResults); + ani_ref intPermissionQueryResults = ConvertAniArrayInt(env, asyncContext->permissionQueryResults); + if (strPermissions == nullptr || intAuthResults == nullptr || boolDialogShownResults == nullptr || + intPermissionQueryResults == nullptr) { + asyncContext->result.errorCode = RET_FAILED; + return nullptr; + } + if (!CallSetter(env, cls, aObject, SETTER_METHOD_NAME(permissions), strPermissions) || + !CallSetter(env, cls, aObject, SETTER_METHOD_NAME(authResults), intAuthResults) || + !CallSetter(env, cls, aObject, SETTER_METHOD_NAME(dialogShownResults), boolDialogShownResults) || + !CallSetter(env, cls, aObject, SETTER_METHOD_NAME(errorReasons), intPermissionQueryResults)) { + asyncContext->result.errorCode = RET_FAILED; + return nullptr; + } + return aObject; +} + +static ani_object DealWithResult(ani_env* env, std::shared_ptr& asyncContext) +{ + ani_object resultObj = nullptr; + if (asyncContext->result.errorCode == RET_SUCCESS) { + resultObj = WrapResult(env, asyncContext); + } + if (asyncContext->result.errorCode != RET_SUCCESS) { + int32_t stsCode = BusinessErrorAni::GetStsErrorCode(asyncContext->result.errorCode); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode, asyncContext->result.errorMsg)); + return nullptr; + } + return resultObj; +} + +static void RequestResultsHandler(const std::vector& permissionList, + const std::vector& permissionStates, std::shared_ptr& data) +{ + if (data->result.errorCode != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Result is: %{public}d", data->result.errorCode); + data->result.errorCode = RET_FAILED; + } + std::vector newGrantResults; + UpdateGrantPermissionResultOnly(permissionList, permissionStates, data, newGrantResults); + if (newGrantResults.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GrantResults empty"); + data->result.errorCode = RET_FAILED; + } + data->grantResults.assign(newGrantResults.begin(), newGrantResults.end()); + data->loadlock.unlock(); + g_loadedCond.notify_all(); +} + +static ani_status ConvertContext( + ani_env* env, const ani_object& aniContext, std::shared_ptr& asyncContext) +{ + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, aniContext); + if (context == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetStageModeContext failed"); + return ANI_ERROR; + } + asyncContext->abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (asyncContext->abilityContext != nullptr) { + auto abilityInfo = asyncContext->abilityContext->GetApplicationInfo(); + if (abilityInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetApplicationInfo failed"); + return ANI_ERROR; + } + asyncContext->uiAbilityFlag = true; + asyncContext->tokenId = abilityInfo->accessTokenId; + asyncContext->bundleName = abilityInfo->bundleName; + } else { + asyncContext->uiExtensionContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (asyncContext->uiExtensionContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertTo UIExtensionContext failed"); + return ANI_ERROR; + } + auto uiExtensionInfo = asyncContext->uiExtensionContext->GetApplicationInfo(); + if (uiExtensionInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetApplicationInfo failed"); + return ANI_ERROR; + } + asyncContext->tokenId = uiExtensionInfo->accessTokenId; + asyncContext->bundleName = uiExtensionInfo->bundleName; + } + return ANI_OK; +} + +static bool ParseRequestPermissionFromUser(ani_env* env, ani_object aniContext, ani_array_ref permissionList, + std::shared_ptr& asyncContext) +{ + if (ConvertContext(env, aniContext, asyncContext) != ANI_OK) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("context", "UIAbility or UIExtension Context")); + return false; + } + if (!ProcessArrayString(env, nullptr, permissionList, asyncContext->permissionList)) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionList", "Array")); + return false; + } + return true; +} + +static bool RequestPermissionsFromUserProcess([[maybe_unused]] ani_env* env, + std::shared_ptr& asyncContext) +{ + if (!IsDynamicRequest(asyncContext)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "It does not need to request permission"); + asyncContext->needDynamicRequest = false; + if ((asyncContext->permissionsState.empty()) && (asyncContext->result.errorCode == RET_SUCCESS)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GrantResults empty"); + asyncContext->result.errorCode = RET_FAILED; + } + return false; + } + GetInstanceId(asyncContext); + asyncContext->loadlock.lock(); + bool lockFlag = false; + if (asyncContext->info.grantBundleName == ORI_PERMISSION_MANAGER_BUNDLE_NAME) { + ACCESSTOKEN_LOG_INFO( + LABEL, "Pop service extension dialog, uiContentFlag=%{public}d", asyncContext->uiContentFlag); + if (asyncContext->uiContentFlag) { + lockFlag = RequestAsyncInstanceControl::AddCallbackByInstanceId(asyncContext); + } else { + lockFlag = CreateServiceExtension(asyncContext); + } + } else if (asyncContext->instanceId == -1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Pop service extension dialog, instanceId is -1."); + lockFlag = CreateServiceExtension(asyncContext); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "REQUEST_PERMISSIONS_FROM_USER", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "BUNDLENAME", asyncContext->bundleName.c_str(), + "UIEXTENSION_FLAG", false); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, "Pop ui extension dialog"); + asyncContext->uiExtensionFlag = true; + lockFlag = RequestAsyncInstanceControl::AddCallbackByInstanceId(asyncContext); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::ACCESS_TOKEN, "REQUEST_PERMISSIONS_FROM_USER", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "BUNDLENAME", asyncContext->bundleName, "UIEXTENSION_FLAG", + false); + if (!asyncContext->uiExtensionFlag) { + ACCESSTOKEN_LOG_WARN(LABEL, "Pop uiextension dialog fail, start to pop service extension dialog."); + lockFlag = RequestAsyncInstanceControl::AddCallbackByInstanceId(asyncContext); + } + } + if (!lockFlag) { + asyncContext->loadlock.unlock(); + } + return true; +} + +static ani_object RequestPermissionsFromUserExecute([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_object aniContext, ani_array_ref permissionList) +{ + if (env == nullptr || permissionList == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionList or env null"); + return nullptr; + } + std::shared_ptr asyncContext = std::make_shared(); + if (!ParseRequestPermissionFromUser(env, aniContext, permissionList, asyncContext)) { + return nullptr; + } +#ifdef EVENTHANDLER_ENABLE + asyncContext->handler_ = std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); +#endif + static AccessTokenID selfTokenID = static_cast(GetSelfTokenID()); + if (selfTokenID != asyncContext->tokenId) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "The context tokenID: %{public}d, selfTokenID: %{public}d.", asyncContext->tokenId, selfTokenID); + std::string errMsg = GetErrorMessage( + STS_ERROR_INNER, "The specified context does not belong to the current application."); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, errMsg); + return nullptr; + } + if (!RequestPermissionsFromUserProcess(env, asyncContext)) { + return DealWithResult(env, asyncContext); + } + ACCESSTOKEN_LOG_INFO(LABEL, "uiExtensionFlag: %{public}d, uiContentFlag: %{public}d, uiAbilityFlag: %{public}d ", + asyncContext->uiExtensionFlag, asyncContext->uiContentFlag, asyncContext->uiAbilityFlag); + asyncContext->loadlock.lock(); + auto resultObj = DealWithResult(env, asyncContext); + asyncContext->loadlock.unlock(); + return resultObj; +} + +static void CloseModalUIExtensionMainThread(std::shared_ptr& asyncContext, int32_t sessionId) +{ + auto task = [asyncContext, sessionId]() { + Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if (uiContent == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Get ui content failed!"); + asyncContext->result.errorCode = RET_FAILED; + return; + } + uiContent->CloseModalUIExtension(sessionId); + ACCESSTOKEN_LOG_INFO(LABEL, "Close end, sessionId: %{public}d", sessionId); + }; +#ifdef EVENTHANDLER_ENABLE + if (asyncContext->handler_ != nullptr) { + asyncContext->handler_->PostSyncTask(task, "AT:CloseModalUIExtensionMainThread"); + } else { + task(); + } +#else + task(); +#endif + ACCESSTOKEN_LOG_INFO(LABEL, "Instance id: %{public}d", asyncContext->instanceId); +} + +void RequestAsyncInstanceControl::ExecCallback(int32_t id) +{ + std::shared_ptr asyncContext = nullptr; + bool isDynamic = false; + { + std::lock_guard lock(instanceIdMutex_); + auto iter = RequestAsyncInstanceControl::instanceIdMap_.find(id); + if (iter == RequestAsyncInstanceControl::instanceIdMap_.end()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "instanceIdMap_ empty"); + return; + } + while (!iter->second.empty()) { + asyncContext = iter->second[0]; + iter->second.erase(iter->second.begin()); + CheckDynamicRequest(asyncContext, isDynamic); + if (isDynamic) { + break; + } + } + if (iter->second.empty()) { + RequestAsyncInstanceControl::instanceIdMap_.erase(id); + } + } + bool lockFlag = true; + if (isDynamic) { + if (asyncContext->uiExtensionFlag) { + lockFlag = CreateUIExtension(asyncContext); + } else { + lockFlag = CreateServiceExtension(asyncContext); + } + } + if (!lockFlag) { + asyncContext->loadlock.unlock(); + } +} + +void RequestAsyncInstanceControl::CheckDynamicRequest( + std::shared_ptr& asyncContext, bool& isDynamic) +{ + asyncContext->permissionsState.clear(); + asyncContext->dialogShownResults.clear(); + if (!IsDynamicRequest(asyncContext)) { + RequestResultsHandler(asyncContext->permissionList, asyncContext->permissionsState, asyncContext); + return; + } + isDynamic = true; +} + +bool RequestAsyncInstanceControl::AddCallbackByInstanceId(std::shared_ptr& asyncContext) +{ + std::lock_guard lock(instanceIdMutex_); + auto iter = RequestAsyncInstanceControl::instanceIdMap_.find(asyncContext->instanceId); + if (iter != RequestAsyncInstanceControl::instanceIdMap_.end()) { + RequestAsyncInstanceControl::instanceIdMap_[asyncContext->instanceId].emplace_back(asyncContext); + return true; + } + RequestAsyncInstanceControl::instanceIdMap_[asyncContext->instanceId] = {}; + bool lockFlag = true; + if (asyncContext->uiExtensionFlag) { + lockFlag = CreateUIExtension(asyncContext); + } else { + lockFlag = CreateServiceExtension(asyncContext); + } + return lockFlag; +} + +UIExtensionCallback::UIExtensionCallback(const std::shared_ptr& reqContext) +{ + this->reqContext_ = reqContext; +} + +UIExtensionCallback::~UIExtensionCallback() {} + +void UIExtensionCallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void UIExtensionCallback::ReleaseHandler(int32_t code) +{ + { + std::lock_guard lock(g_lockFlag); + if (this->reqContext_->releaseFlag) { + ACCESSTOKEN_LOG_WARN(LABEL, "Callback has executed."); + return; + } + this->reqContext_->releaseFlag = true; + } + CloseModalUIExtensionMainThread(this->reqContext_, this->sessionId_); + this->reqContext_->result.errorCode = code; + RequestAsyncInstanceControl::ExecCallback(this->reqContext_->instanceId); + RequestResultsHandler(this->reqContext_->permissionList, this->reqContext_->permissionsState, this->reqContext_); +} + +void UIExtensionCallback::OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "ResultCode is %{public}d", resultCode); + this->reqContext_->permissionList = result.GetStringArrayParam(PERMISSION_KEY); + this->reqContext_->permissionsState = result.GetIntArrayParam(RESULT_KEY); + ReleaseHandler(0); +} + +void UIExtensionCallback::OnReceive(const OHOS::AAFwk::WantParams& receive) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Called!"); +} + +void UIExtensionCallback::OnRelease(int32_t releaseCode) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "ReleaseCode is %{public}d", releaseCode); + ReleaseHandler(-1); +} + +void UIExtensionCallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ACCESSTOKEN_LOG_INFO( + LABEL, "Code is %{public}d, name is %{public}s, message is %{public}s", code, name.c_str(), message.c_str()); + + ReleaseHandler(-1); +} + +void UIExtensionCallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Connect to UIExtensionAbility successfully."); +} + +void UIExtensionCallback::OnDestroy() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "UIExtensionAbility destructed."); + ReleaseHandler(-1); +} + +void AuthorizationResult::GrantResultsCallback( + const std::vector& permissionList, const std::vector& grantResults) +{ + std::shared_ptr asyncContext = data_; + if (asyncContext == nullptr) { + return; + } + RequestResultsHandler(permissionList, grantResults, asyncContext); +} + +void AuthorizationResult::WindowShownCallback() +{ + std::shared_ptr asyncContext = data_; + if (asyncContext == nullptr) { + return; + } + OHOS::Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if ((uiContent == nullptr) || !(asyncContext->uiContentFlag)) { + return; + } + RequestAsyncInstanceControl::ExecCallback(asyncContext->instanceId); +} + +static ani_object CreateAtManager([[maybe_unused]] ani_env* env) +{ + ani_object atManagerObj = {}; + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr env"); + return atManagerObj; + } + + static const char* className = "L@ohos/abilityAccessCtrl/abilityAccessCtrl/AtManagerInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Not found %{public}s", className); + return atManagerObj; + } + + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, "", nullptr, &ctor)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get ctor Failed %{public}s", className); + return atManagerObj; + } + + if (ANI_OK != env->Object_New(cls, ctor, &atManagerObj)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Create Object Failed %{public}s", className); + return atManagerObj; + } + return atManagerObj; +} + +static std::string GetPermParamValue() +{ + long long sysCommitId = GetSystemCommitId(); + if (sysCommitId == g_paramCache.sysCommitIdCache) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "SysCommitId = %{public}lld", sysCommitId); + return g_paramCache.sysParamCache; + } + g_paramCache.sysCommitIdCache = sysCommitId; + if (g_paramCache.handle == PARAM_DEFAULT_VALUE) { + int32_t handle = static_cast(FindParameter(PERMISSION_STATUS_CHANGE_KEY)); + if (handle == PARAM_DEFAULT_VALUE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindParameter failed"); + return "-1"; + } + g_paramCache.handle = handle; + } + + int32_t currCommitId = static_cast(GetParameterCommitId(g_paramCache.handle)); + if (currCommitId != g_paramCache.commitIdCache) { + char value[AniContextCommon::VALUE_MAX_LEN] = { 0 }; + auto ret = GetParameterValue(g_paramCache.handle, value, AniContextCommon::VALUE_MAX_LEN - 1); + if (ret < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Return default value, ret=%{public}d", ret); + return "-1"; + } + std::string resStr(value); + g_paramCache.sysParamCache = resStr; + g_paramCache.commitIdCache = currCommitId; + } + return g_paramCache.sysParamCache; +} + +static void UpdatePermissionCache(AtManagerAsyncContext* asyncContext) +{ + std::lock_guard lock(g_lockCache); + auto iter = g_cache.find(asyncContext->permissionName); + if (iter != g_cache.end()) { + std::string currPara = GetPermParamValue(); + if (currPara != iter->second.paramValue) { + asyncContext->grantStatus = + AccessToken::AccessTokenKit::VerifyAccessToken(asyncContext->tokenId, asyncContext->permissionName); + iter->second.status = asyncContext->grantStatus; + iter->second.paramValue = currPara; + ACCESSTOKEN_LOG_DEBUG(LABEL, "Param changed currPara %{public}s", currPara.c_str()); + } else { + asyncContext->grantStatus = iter->second.status; + } + } else { + asyncContext->grantStatus = + AccessToken::AccessTokenKit::VerifyAccessToken(asyncContext->tokenId, asyncContext->permissionName); + g_cache[asyncContext->permissionName].status = asyncContext->grantStatus; + g_cache[asyncContext->permissionName].paramValue = GetPermParamValue(); + ACCESSTOKEN_LOG_DEBUG( + LABEL, "G_cacheParam set %{public}s", g_cache[asyncContext->permissionName].paramValue.c_str()); + } +} + +static ani_int CheckAccessTokenSync([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_int tokenID, ani_string permissionName) +{ + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr env"); + return AccessToken::PermissionState::PERMISSION_DENIED; + } + if (tokenID == 0) { + std::string errMsg = GetErrorMessage(STS_ERROR_PARAM_INVALID, "The tokenID is 0."); + BusinessErrorAni::ThrowError(env, STS_ERROR_PARAM_INVALID, errMsg); + return AccessToken::PermissionState::PERMISSION_DENIED; + } + std::string stdPermissionName = ANIUtils_ANIStringToStdString(env, static_cast(permissionName)); + if (stdPermissionName.empty() || stdPermissionName.length() > MAX_LENGTH) { + std::string errMsg = GetErrorMessage( + STS_ERROR_PARAM_INVALID, "The permissionName is empty or exceeds 256 characters."); + BusinessErrorAni::ThrowError(env, STS_ERROR_PARAM_INVALID, errMsg); + return AccessToken::PermissionState::PERMISSION_DENIED; + } + auto* asyncContext = new (std::nothrow) AtManagerAsyncContext(); + if (asyncContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "New struct fail."); + return AccessToken::PermissionState::PERMISSION_DENIED; + } + std::unique_ptr context {asyncContext}; + asyncContext->tokenId = static_cast(tokenID); + asyncContext->permissionName = stdPermissionName; + static uint64_t selfTokenId = GetSelfTokenID(); + if (asyncContext->tokenId != static_cast(selfTokenId)) { + asyncContext->grantStatus = AccessToken::AccessTokenKit::VerifyAccessToken(tokenID, stdPermissionName); + return static_cast(asyncContext->grantStatus); + } + UpdatePermissionCache(asyncContext); + ACCESSTOKEN_LOG_INFO(LABEL, "CheckAccessTokenSync result : %{public}d", asyncContext->grantStatus); + return static_cast(asyncContext->grantStatus); +} + +static ani_status GetContext( + ani_env* env, const ani_object& aniContext, std::shared_ptr& asyncContext) +{ + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, aniContext); + if (context == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetStageModeContext failed"); + return ANI_ERROR; + } + asyncContext->abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (asyncContext->abilityContext != nullptr) { + auto abilityInfo = asyncContext->abilityContext->GetApplicationInfo(); + if (abilityInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetApplicationInfo failed"); + return ANI_ERROR; + } + asyncContext->uiAbilityFlag = true; + asyncContext->tokenId = abilityInfo->accessTokenId; + } else { + asyncContext->uiExtensionContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (asyncContext->uiExtensionContext == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertTo UIExtensionContext failed"); + return ANI_ERROR; + } + auto uiExtensionInfo = asyncContext->uiExtensionContext->GetApplicationInfo(); + if (uiExtensionInfo == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetApplicationInfo failed"); + return ANI_ERROR; + } + asyncContext->tokenId = uiExtensionInfo->accessTokenId; + } + return ANI_OK; +} + +static bool ParseRequestPermissionOnSetting(ani_env* env, ani_object& aniContext, ani_array_ref& permissionList, + std::shared_ptr& asyncContext) +{ + if (GetContext(env, aniContext, asyncContext) != ANI_OK) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("context", "UIAbility or UIExtension Context")); + return false; + } + if (!ProcessArrayString(env, nullptr, permissionList, asyncContext->permissionList)) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionList", "Array")); + return false; + } + return true; +} + +static void StateToEnumIndex(int32_t state, ani_size& enumIndex) +{ + if (state == 0) { + enumIndex = 1; + } else { + enumIndex = 0; + } +} + +static ani_ref ReturnResult(ani_env* env, std::shared_ptr& asyncContext) +{ + ani_class arrayCls = nullptr; + if (env->FindClass("Lescompat/Array;", &arrayCls) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass name Lescompat/Array failed!"); + return nullptr; + } + + ani_method arrayCtor; + if (env->Class_FindMethod(arrayCls, "", "I:V", &arrayCtor) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass failed!"); + return nullptr; + } + + ani_object arrayObj; + if (env->Object_New(arrayCls, arrayCtor, &arrayObj, asyncContext->stateList.size()) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object new failed!"); + return nullptr; + } + + const char* enumDescriptor = "L@ohos/abilityAccessCtrl/abilityAccessCtrl/GrantStatus;"; + ani_enum enumType; + if (env->FindEnum(enumDescriptor, &enumType) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass name %{public}s failed!", enumDescriptor); + return nullptr; + } + + ani_size index = 0; + for (const auto& state: asyncContext->stateList) { + ani_enum_item enumItem; + ani_size enumIndex = 0; + StateToEnumIndex(state, enumIndex); + if (env->Enum_GetEnumItemByIndex(enumType, enumIndex, &enumItem) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetEnumItemByIndex value %{public}u failed!", state); + break; + } + + if (env->Object_CallMethodByName_Void(arrayObj, "$_set", "ILstd/core/Object;:V", index, enumItem) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_CallMethodByName_Void $_set failed!"); + break; + } + index++; + } + + return arrayObj; +} + +static int32_t TransferToStsErrorCode(int32_t errorCode) +{ + int32_t stsCode = STS_OK; + switch (errorCode) { + case RET_SUCCESS: + stsCode = STS_OK; + break; + case REQUEST_REALDY_EXIST: + stsCode = STS_ERROR_REQUEST_IS_ALREADY_EXIST; + break; + case PERM_NOT_BELONG_TO_SAME_GROUP: + stsCode = STS_ERROR_PARAM_INVALID; + break; + case PERM_IS_NOT_DECLARE: + stsCode = STS_ERROR_PARAM_INVALID; + break; + case ALL_PERM_GRANTED: + stsCode = STS_ERROR_ALL_PERM_GRANTED; + break; + case PERM_REVOKE_BY_USER: + stsCode = STS_ERROR_PERM_REVOKE_BY_USER; + break; + default: + stsCode = STS_ERROR_INNER; + break; + } + ACCESSTOKEN_LOG_ERROR(LABEL, "Dialog error(%{public}d) stsCode(%{public}d).", errorCode, stsCode); + return stsCode; +} + +static ani_ref RequestPermissionOnSettingComplete( + ani_env* env, std::shared_ptr& asyncContext) +{ + if (asyncContext->result.errorCode == RET_SUCCESS) { + ani_ref result = ReturnResult(env, asyncContext); + if (result != nullptr) { + return result; + } + asyncContext->result.errorCode = RET_FAILED; + } + + int32_t stsCode = TransferToStsErrorCode(asyncContext->result.errorCode); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return nullptr; +} + +PermissonOnSettingUICallback::PermissonOnSettingUICallback(ani_env* env, + const std::shared_ptr& reqContext) +{ + this->env_ = env; + this->reqContext_ = reqContext; +} + +PermissonOnSettingUICallback::~PermissonOnSettingUICallback() +{} + +void PermissonOnSettingUICallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +static void CloseSettingModalUIExtensionMainThread(std::shared_ptr& asyncContext, + int32_t sessionId) +{ + auto task = [asyncContext, sessionId]() { + Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if (uiContent == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Get ui content failed!"); + asyncContext->result.errorCode = RET_FAILED; + return; + } + uiContent->CloseModalUIExtension(sessionId); + ACCESSTOKEN_LOG_INFO(LABEL, "Close end, sessionId: %{public}d", sessionId); + }; +#ifdef EVENTHANDLER_ENABLE + if (asyncContext->handler_ != nullptr) { + asyncContext->handler_->PostSyncTask(task, "AT:CloseModalUIExtensionMainThread"); + } else { + task(); + } +#else + task(); +#endif +} + +void PermissonOnSettingUICallback::ReleaseHandler(int32_t code) +{ + { + std::lock_guard lock(this->lockReleaseFlag); + if (this->releaseFlag) { + ACCESSTOKEN_LOG_WARN(LABEL, "Callback has executed."); + return; + } + this->releaseFlag = true; + } + CloseSettingModalUIExtensionMainThread(this->reqContext_, this->sessionId_); + if (code == -1) { + this->reqContext_->result.errorCode = code; + } + this->reqContext_->loadlock.unlock(); + std::lock_guard lock(g_lockWindowFlag); + g_windowFlag = false; +} + +/* + * when UIExtensionAbility use terminateSelfWithResult + */ +void PermissonOnSettingUICallback::OnResult(int32_t resultCode, const AAFwk::Want& result) +{ + this->reqContext_->result.errorCode = result.GetIntParam(RESULT_ERROR_KEY, 0); + this->reqContext_->stateList = result.GetIntArrayParam(PERMISSION_RESULT_KEY); + ACCESSTOKEN_LOG_INFO(LABEL, "ResultCode is %{public}d, listSize=%{public}zu.", + resultCode, this->reqContext_->stateList.size()); + ReleaseHandler(0); +} + +/* + * when UIExtensionAbility send message to UIExtensionComponent + */ +void PermissonOnSettingUICallback::OnReceive(const AAFwk::WantParams& receive) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Called!"); +} + +/* + * when UIExtensionAbility disconnect or use terminate or process die + * releaseCode is 0 when process normal exit + */ +void PermissonOnSettingUICallback::OnRelease(int32_t releaseCode) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "ReleaseCode is %{public}d", releaseCode); + + ReleaseHandler(-1); +} + +/* + * when UIExtensionComponent init or turn to background or destroy UIExtensionAbility occur error + */ +void PermissonOnSettingUICallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Code is %{public}d, name is %{public}s, message is %{public}s", + code, name.c_str(), message.c_str()); + + ReleaseHandler(-1); +} + +/* + * when UIExtensionComponent connect to UIExtensionAbility, ModalUIExtensionProxy will init, + * UIExtensionComponent can send message to UIExtensionAbility by ModalUIExtensionProxy + */ +void PermissonOnSettingUICallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "Connect to UIExtensionAbility successfully."); +} + +/* + * when UIExtensionComponent destructed + */ +void PermissonOnSettingUICallback::OnDestroy() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "UIExtensionAbility destructed."); + ReleaseHandler(-1); +} + +static void CreateSettingUIExtensionMainThread(std::shared_ptr& asyncContext, + const AAFwk::Want& want, const Ace::ModalUIExtensionCallbacks& uiExtensionCallbacks, + const std::shared_ptr& uiExtCallback) +{ + auto task = [asyncContext, want, uiExtensionCallbacks, uiExtCallback]() { + Ace::UIContent* uiContent = GetUIContent(asyncContext->abilityContext, + asyncContext->uiExtensionContext, asyncContext->uiAbilityFlag); + if (uiContent == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to get ui content!"); + asyncContext->result.errorCode = RET_FAILED; + return; + } + + Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + ACCESSTOKEN_LOG_INFO(LABEL, "Create end, sessionId: %{public}d, tokenId: %{public}d.", + sessionId, asyncContext->tokenId); + if (sessionId == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to create component, sessionId is 0."); + asyncContext->result.errorCode = RET_FAILED; + return; + } + uiExtCallback->SetSessionId(sessionId); + }; +#ifdef EVENTHANDLER_ENABLE + if (asyncContext->handler_ != nullptr) { + asyncContext->handler_->PostSyncTask(task, "AT:CreateUIExtensionMainThread"); + } else { + task(); + } +#else + task(); +#endif +} + +static bool StartUIExtension(ani_env* env, std::shared_ptr& asyncContext) +{ + AccessTokenKit::GetPermissionManagerInfo(asyncContext->info); + + OHOS::AAFwk::Want want; + want.SetElementName(asyncContext->info.grantBundleName, asyncContext->info.permStateAbilityName); + want.SetParam(PERMISSION_SETTING_KEY, asyncContext->permissionList); + want.SetParam(EXTENSION_TYPE_KEY, UI_EXTENSION_TYPE); + + auto uiExtCallback = std::make_shared(env, asyncContext); + Ace::ModalUIExtensionCallbacks uiExtensionCallbacks = { + [uiExtCallback](int32_t releaseCode) { + uiExtCallback->OnRelease(releaseCode); + }, + [uiExtCallback](int32_t resultCode, const AAFwk::Want& result) { + uiExtCallback->OnResult(resultCode, result); + }, + [uiExtCallback](const AAFwk::WantParams& receive) { + uiExtCallback->OnReceive(receive); + }, + [uiExtCallback](int32_t code, const std::string& name, [[maybe_unused]] const std::string& message) { + uiExtCallback->OnError(code, name, name); + }, + [uiExtCallback](const std::shared_ptr& uiProxy) { + uiExtCallback->OnRemoteReady(uiProxy); + }, + [uiExtCallback]() { + uiExtCallback->OnDestroy(); + }, + }; + + { + std::lock_guard lock(g_lockWindowFlag); + if (g_windowFlag) { + ACCESSTOKEN_LOG_WARN(LABEL, "The request already exists."); + asyncContext->result.errorCode = REQUEST_REALDY_EXIST; + asyncContext->result.errorMsg = "The specified context does not belong to the current application."; + return false; + } + g_windowFlag = true; + } + CreateSettingUIExtensionMainThread(asyncContext, want, uiExtensionCallbacks, uiExtCallback); + if (asyncContext->result.errorCode == RET_FAILED) { + { + std::lock_guard lock(g_lockWindowFlag); + g_windowFlag = false; + return false; + } + } + return true; +} + +static ani_ref RequestPermissionOnSettingExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_object aniContext, ani_array_ref permissionList) +{ + if (env == nullptr || permissionList == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionList or env null"); + return nullptr; + } + + std::shared_ptr asyncContext = + std::make_shared(); + if (!ParseRequestPermissionOnSetting(env, aniContext, permissionList, asyncContext)) { + return nullptr; + } + + static AccessTokenID selfTokenID = static_cast(GetSelfTokenID()); + if (selfTokenID != asyncContext->tokenId) { + ACCESSTOKEN_LOG_ERROR(LABEL, "The context tokenID %{public}d is not same with selfTokenID %{public}d.", + asyncContext->tokenId, selfTokenID); + std::string errMsg = GetErrorMessage( + STS_ERROR_INNER, "The specified context does not belong to the current application."); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, errMsg); + return nullptr; + } + asyncContext->loadlock.lock(); + bool flag = StartUIExtension(env, asyncContext); + if (!flag) { + asyncContext->loadlock.unlock(); + } + asyncContext->loadlock.lock(); + ani_ref result = RequestPermissionOnSettingComplete(env, asyncContext); + asyncContext->loadlock.unlock(); + return result; +} + +static bool IsPermissionFlagValid(uint32_t flag) +{ + return (flag == PermissionFlag::PERMISSION_USER_SET) || (flag == PermissionFlag::PERMISSION_USER_FIXED) || + (flag == PermissionFlag::PERMISSION_ALLOW_THIS_TIME); +}; + +static void GrantUserGrantedPermissionExecute([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_object object, + ani_int tokenID, ani_string aniPermissionName, ani_int permissionFlags) +{ + if (env == nullptr) { + return; + } + std::string permissionName; + if (!AniParseString(env, aniPermissionName, permissionName)) { + BusinessErrorAni::ThrowParameterTypeError(env, STSErrorCode::STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return; + } + + if (permissionName.empty() || permissionName.size() > MAX_LENGTH) { + BusinessErrorAni::ThrowError(env, STSErrorCode::STS_ERROR_PARAM_INVALID, + GetErrorMessage(STSErrorCode::STS_ERROR_PARAM_INVALID)); + return; + } + if (!IsPermissionFlagValid(static_cast(permissionFlags))) { + BusinessErrorAni::ThrowError(env, STSErrorCode::STS_ERROR_PARAM_INVALID, + GetErrorMessage(STSErrorCode::STS_ERROR_PARAM_INVALID)); + return; + } + PermissionBriefDef def; + if (!GetPermissionBriefDef(permissionName, def)) { + BusinessErrorAni::ThrowError(env, STSErrorCode::STS_ERROR_PERMISSION_NOT_EXIST, + GetErrorMessage(STSErrorCode::STS_ERROR_PERMISSION_NOT_EXIST)); + return; + } + + if (def.grantMode != USER_GRANT || !GetPermissionBriefDef(permissionName, def)) { + std::string errMsg = GetErrorMessage(STS_ERROR_PERMISSION_NOT_EXIST, + "The specified permission does not exist or is not a user_grant permission."); + BusinessErrorAni::ThrowError( + env, STS_ERROR_PERMISSION_NOT_EXIST, GetErrorMessage(STS_ERROR_PERMISSION_NOT_EXIST)); + return; + } + + int32_t res = AccessTokenKit::GrantPermission(tokenID, permissionName, permissionFlags); + if (res != RET_SUCCESS) { + int32_t stsCode = BusinessErrorAni::GetStsErrorCode(res); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + } +} + +static void RevokeUserGrantedPermissionExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_int tokenID, ani_string permissionName, ani_int permissionFlags) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "RevokeUserGrantedPermission begin."); + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "env null."); + return; + } + + std::string permissionNameString; + if (!AniParseString(env, permissionName, permissionNameString)) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return; + } + + if (!IsPermissionFlagValid(static_cast (permissionFlags))) { + std::string errMsg = GetErrorMessage(STS_ERROR_PARAM_INVALID, "The permissionFlags is invalid."); + BusinessErrorAni::ThrowError(env, STS_ERROR_PARAM_INVALID, errMsg); + return; + } + + if (permissionNameString.empty() || permissionNameString.size() > MAX_LENGTH) { + std::string errMsg = GetErrorMessage( + STS_ERROR_PARAM_INVALID, "The permissionName is empty or exceeds 256 characters."); + BusinessErrorAni::ThrowError(env, STS_ERROR_PARAM_INVALID, errMsg); + return; + } + PermissionBriefDef def; + if (!GetPermissionBriefDef(permissionNameString, def) || def.grantMode != USER_GRANT) { + std::string errMsg = GetErrorMessage(STS_ERROR_PERMISSION_NOT_EXIST, + "The specified permission does not exist or is not a user_grant permission."); + BusinessErrorAni::ThrowError(env, STS_ERROR_PERMISSION_NOT_EXIST, errMsg); + return; + } + + int32_t ret = AccessTokenKit::RevokePermission(tokenID, permissionNameString, permissionFlags); + if (ret != RET_SUCCESS) { + int32_t stsCode = BusinessErrorAni::GetStsErrorCode(ret); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + } +} + +static ani_int GetVersionExecute([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "getVersionExecute begin."); + uint32_t version = -1; + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "env null"); + return version; + } + + int32_t result = AccessTokenKit::GetVersion(version); + if (result != RET_SUCCESS) { + int32_t stsCode = BusinessErrorAni::GetStsErrorCode(result); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return version; + } + return version; +} + +static ani_ref GetPermissionsStatusExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_int tokenID, ani_array_ref permissionList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "GetPermissionsStatusExecute begin."); + if ((env == nullptr) || (permissionList == nullptr)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionList or env null."); + return nullptr; + } + std::vector aniPermissionList; + if (!AniParseStringArray(env, permissionList, aniPermissionList)) { + BusinessErrorAni::ThrowParameterTypeError( + env, STS_ERROR_PARAM_ILLEGAL, GetParamErrorMsg("permissionList", "Array")); + return nullptr; + } + + if (aniPermissionList.empty()) { + std::string errMsg = GetErrorMessage(STS_ERROR_INNER, "The permissionList is empty."); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STS_ERROR_INNER)); + return nullptr; + } + + std::vector permList; + for (const auto& permission : aniPermissionList) { + PermissionListState permState; + permState.permissionName = permission; + permState.state = INVALID_OPER; + permList.emplace_back(permState); + } + + int32_t result = RET_SUCCESS; + std::vector permissionQueryResults; + result = AccessTokenKit::GetPermissionsStatus(tokenID, permList); + if (result != RET_SUCCESS) { + int32_t stsCode = BusinessErrorAni::GetStsErrorCode(result); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return nullptr; + } + for (const auto& permState : permList) { + permissionQueryResults.emplace_back(permState.state); + } + + return ConvertAniArrayInt(env, permissionQueryResults); +} + +static ani_int GetPermissionFlagsExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_int tokenID, ani_string aniPermissionName) +{ + uint32_t flag = PERMISSION_DEFAULT_FLAG; + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Env is null"); + return flag; + } + std::string permissionName; + if (!AniParseString(env, aniPermissionName, permissionName)) { + BusinessErrorAni::ThrowParameterTypeError(env, STSErrorCode::STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return flag; + } + int32_t result = AccessTokenKit::GetPermissionFlag(tokenID, permissionName, flag); + if (result != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "result = %{public}d errcode = %{public}d", + result, BusinessErrorAni::GetStsErrorCode(result)); + BusinessErrorAni::ThrowError(env, BusinessErrorAni::GetStsErrorCode(result), + GetErrorMessage(BusinessErrorAni::GetStsErrorCode(result))); + } + return flag; +} + +static void SetPermissionRequestToggleStatusExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_string aniPermissionName, ani_int status) +{ + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Env is null"); + return; + } + std::string permissionName; + if (!AniParseString(env, aniPermissionName, permissionName)) { + BusinessErrorAni::ThrowParameterTypeError(env, STSErrorCode::STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return; + } + int32_t result = AccessTokenKit::SetPermissionRequestToggleStatus(permissionName, status, 0); + if (result != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "result = %{public}d errcode = %{public}d", + result, BusinessErrorAni::GetStsErrorCode(result)); + BusinessErrorAni::ThrowError(env, BusinessErrorAni::GetStsErrorCode(result), + GetErrorMessage(BusinessErrorAni::GetStsErrorCode(result))); + } + return; +} + +static ani_int GetPermissionRequestToggleStatusExecute([[maybe_unused]] ani_env* env, + [[maybe_unused]] ani_object object, ani_string aniPermissionName) +{ + uint32_t flag = CLOSED; + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Env is null"); + return flag; + } + std::string permissionName; + if (!AniParseString(env, aniPermissionName, permissionName)) { + BusinessErrorAni::ThrowParameterTypeError(env, STSErrorCode::STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return flag; + } + int32_t result = AccessTokenKit::GetPermissionRequestToggleStatus(permissionName, flag, 0); + if (result != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "result = %{public}d errcode = %{public}d", + result, BusinessErrorAni::GetStsErrorCode(result)); + BusinessErrorAni::ThrowError(env, BusinessErrorAni::GetStsErrorCode(result), + GetErrorMessage(BusinessErrorAni::GetStsErrorCode(result))); + } + return flag; +} + +extern "C" { +ANI_EXPORT ani_status ANI_Constructor(ani_vm* vm, uint32_t* result) +{ + if (vm == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr vm"); + return ANI_INVALID_ARGS; + } + ani_env* env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Unsupported ANI_VERSION_1"); + return ANI_OUT_OF_MEMORY; + } + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr env"); + return ANI_NOT_FOUND; + } + const char* spaceName = "L@ohos/abilityAccessCtrl/abilityAccessCtrl;"; + ani_namespace spc; + if (ANI_OK != env->FindNamespace(spaceName, &spc)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Not found %{public}s", spaceName); + return ANI_NOT_FOUND; + } + std::array methods = { + ani_native_function { "createAtManager", nullptr, reinterpret_cast(CreateAtManager) }, + }; + if (ANI_OK != env->Namespace_BindNativeFunctions(spc, methods.data(), methods.size())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind native methods to %{public}s", spaceName); + return ANI_ERROR; + }; + const char* className = "L@ohos/abilityAccessCtrl/abilityAccessCtrl/AtManagerInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Not found %{public}s", className); + return ANI_ERROR; + } + std::array claMethods = { + ani_native_function { + "checkAccessTokenExecute", "ILstd/core/String;:I", reinterpret_cast(CheckAccessTokenSync) }, + ani_native_function { "requestPermissionsFromUserExecute", + "Lapplication/Context/Context;Lescompat/Array;:Lsecurity/PermissionRequestResult/PermissionRequestResult;", + reinterpret_cast(RequestPermissionsFromUserExecute) }, + ani_native_function { "requestPermissionOnSettingExecute", + "Lapplication/Context/Context;Lescompat/Array;:Lescompat/Array;", + reinterpret_cast(RequestPermissionOnSettingExecute) }, + ani_native_function { "grantUserGrantedPermissionExecute", nullptr, + reinterpret_cast(GrantUserGrantedPermissionExecute) }, + ani_native_function { "revokeUserGrantedPermissionExecute", + nullptr, reinterpret_cast(RevokeUserGrantedPermissionExecute) }, + ani_native_function { "getVersionExecute", nullptr, reinterpret_cast(GetVersionExecute) }, + ani_native_function { "getPermissionsStatusExecute", + nullptr, reinterpret_cast(GetPermissionsStatusExecute) }, + ani_native_function{ "getPermissionFlagsExecute", + nullptr, reinterpret_cast(GetPermissionFlagsExecute) }, + ani_native_function{ "setPermissionRequestToggleStatusExecute", + nullptr, reinterpret_cast(SetPermissionRequestToggleStatusExecute) }, + ani_native_function{ "getPermissionRequestToggleStatusExecute", + nullptr, reinterpret_cast(GetPermissionRequestToggleStatusExecute) }, + }; + if (ANI_OK != env->Class_BindNativeMethods(cls, claMethods.data(), claMethods.size())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind native methods to %{public}s", className); + return ANI_ERROR; + }; + *result = ANI_VERSION_1; + return ANI_OK; +} +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ets/ani/common/BUILD.gn b/frameworks/ets/ani/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..66cbbd3aba1c1e0a2c0f6544fffe2b323461bde6 --- /dev/null +++ b/frameworks/ets/ani/common/BUILD.gn @@ -0,0 +1,85 @@ +# Copyright (c) 2022-2023 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("//base/security/access_token/access_token.gni") +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") + +ohos_static_library("libani_common") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + include_dirs = [ + "./include", + "${access_token_path}/interfaces/innerkits/accesstoken/include", + ] + + sources = [ + "src/ani_error.cpp", + "src/ani_utils.cpp" + ] + + deps = [ "${access_token_path}/frameworks/common:accesstoken_common_cxx" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + external_deps = [ + "hilog:libhilog", + "runtime_core:ani", + ] + + subsystem_name = "security" + part_name = "access_token" +} + +generate_static_abc("Permission_Request_Result") { + base_url = "./ets" + files = [ "./ets/security/PermissionRequestResult.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/Permission_Request_Result.abc" +} + +ohos_prebuilt_etc("Permission_Request_Result_etc") { + source = "$target_out_dir/Permission_Request_Result.abc" + deps = [ ":Permission_Request_Result" ] + module_install_dir = "framework" + part_name = "access_token" + subsystem_name = "security" +} + +generate_static_abc("permissions") { + base_url = "./ets" + files = [ "./ets/permissions.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/permissions.abc" +} + +ohos_prebuilt_etc("permissions_etc") { + source = "$target_out_dir/permissions.abc" + deps = [ ":permissions" ] + module_install_dir = "framework" + part_name = "access_token" + subsystem_name = "security" +} + +group("common_ets") { + deps = [ + ":Permission_Request_Result_etc", + ":libani_common", + ":permissions_etc", + ] +} diff --git a/frameworks/ets/ani/common/ets/permissions.ets b/frameworks/ets/ani/common/ets/permissions.ets new file mode 100644 index 0000000000000000000000000000000000000000..c06103b9640f0ebf38d4c86f9e106cb2d5c2d8e5 --- /dev/null +++ b/frameworks/ets/ani/common/ets/permissions.ets @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2025 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. + */ + +/** + * @file Defines all permissions. + * @kit AbilityKit + */ + +/** + * Indicates permissions. + * + * @typedef { string } + * @syscap SystemCapability.Security.AccessToken + * @since 9 + */ + /** + * Indicates permissions. + * + * @typedef { string } + * @syscap SystemCapability.Security.AccessToken + * @atomicservice + * @since 11 + */ +export type Permissions = string; \ No newline at end of file diff --git a/frameworks/ets/ani/common/ets/security/PermissionRequestResult.ets b/frameworks/ets/ani/common/ets/security/PermissionRequestResult.ets new file mode 100644 index 0000000000000000000000000000000000000000..ba08345a99963339afd0fba9f88a734e81d99a4a --- /dev/null +++ b/frameworks/ets/ani/common/ets/security/PermissionRequestResult.ets @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2025 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. + */ + +/** + * @file + * @kit AbilityKit + */ + +/** + * The result of requestPermissionsFromUser with asynchronous callback. + * + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @since 9 + */ +/** + * The result of requestPermissionsFromUser with asynchronous callback. + * + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @since 10 + */ +/** + * The result of requestPermissionsFromUser with asynchronous callback. + * + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @atomicservice + * @since 11 + */ +export default class PermissionRequestResult { + /** + * The permissions passed in by the user. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @since 9 + */ + /** + * The permissions passed in by the user. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @since 10 + */ + /** + * The permissions passed in by the user. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @atomicservice + * @since 11 + */ + permissions: Array = new Array(); + + /** + * The results for the corresponding request permissions. The value 0 indicates that a + * permission is granted, the value -1 indicates not, and the value 2 indicates the request is invalid. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @since 9 + */ + /** + * The results for the corresponding request permissions. The value 0 indicates that a + * permission is granted, the value -1 indicates not, and the value 2 indicates the request is invalid. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @since 10 + */ + /** + * The results for the corresponding request permissions. The value 0 indicates that a + * permission is granted, the value -1 indicates not, and the value 2 indicates the request is invalid. + * + * @type { Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @atomicservice + * @since 11 + */ + authResults: Array = new Array(); + + /** + * Specifies whether a dialog box is shown for each requested permission. + * The value true means that a dialog box is shown, and false means the opposite. + * + * @type { ?Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @atomicservice + * @since 12 + */ + dialogShownResults?: Array; + + /** + * Enumerates the return values of the permission request operation. + * 0 The operation is successful. + * 1 The permission name is invalid. + * 2 The requested permission has not been declared. + * 3 The conditions for requesting the permission are not met. + * 4 The user does not agree to the Privacy Statement. + * 5 The permission cannot be requested in a pop-up window. + * 12 The service is abnormal. + * + * @type { ?Array } + * @syscap SystemCapability.Security.AccessToken + * @stagemodelonly + * @crossplatform + * @atomicservice + * @since 18 + */ + errorReasons?: Array; +} \ No newline at end of file diff --git a/frameworks/ets/ani/common/include/ani_error.h b/frameworks/ets/ani/common/include/ani_error.h new file mode 100644 index 0000000000000000000000000000000000000000..d8fc49028618ba0d1ca37efc131d1f7944ffe3cf --- /dev/null +++ b/frameworks/ets/ani/common/include/ani_error.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 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 INTERFACES_ETS_ANI_COMMON_ANI_ERROR_H +#define INTERFACES_ETS_ANI_COMMON_ANI_ERROR_H + +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef enum { + STS_OK = 0, + STS_ERROR_PERMISSION_DENIED = 201, + STS_ERROR_NOT_SYSTEM_APP = 202, + STS_ERROR_PARAM_ILLEGAL = 401, + STS_ERROR_SYSTEM_CAPABILITY_NOT_SUPPORT = 801, + STS_ERROR_START_ABILITY_FAIL = 1011, + STS_ERROR_BACKGROUND_FAIL = 1012, + STS_ERROR_TERMINATE_FAIL = 1013, + STS_ERROR_PARAM_INVALID = 12100001, + STS_ERROR_TOKENID_NOT_EXIST, + STS_ERROR_PERMISSION_NOT_EXIST, + STS_ERROR_NOT_USE_TOGETHER, + STS_ERROR_REGISTERS_EXCEED_LIMITATION, + STS_ERROR_PERMISSION_OPERATION_NOT_ALLOWED, + STS_ERROR_SERVICE_NOT_RUNNING, + STS_ERROR_OUT_OF_MEMORY, + STS_ERROR_INNER, + STS_ERROR_REQUEST_IS_ALREADY_EXIST = 12100010, + STS_ERROR_ALL_PERM_GRANTED = 12100011, + STS_ERROR_PERM_REVOKE_BY_USER = 12100012, + STS_ERROR_GLOBAL_SWITCH_IS_ALREADY_OPEN = 12100013, +} STSErrorCode; + +struct AtmResult { + int32_t errorCode = 0; + std::string errorMsg = ""; +}; + +std::string GetParamErrorMsg(const std::string& param, const std::string& errMsg); +std::string GetErrorMessage(uint32_t errCode, const std::string& extendMsg = ""); +class BusinessErrorAni { +public: + static ani_object CreateError(ani_env* env, ani_int code, const std::string& msg); + static void ThrowParameterTypeError(ani_env* env, int32_t err, const std::string& errMsg); + static void ThrowError(ani_env* env, int32_t err, const std::string& errMsg = ""); + static int32_t GetStsErrorCode(int32_t errCode); + +private: + static void ThrowError(ani_env* env, ani_object err); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_ETS_ANI_COMMON_ANI_ERROR_H */ diff --git a/frameworks/ets/ani/common/include/ani_utils.h b/frameworks/ets/ani/common/include/ani_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f86989e112f4e8e7ad8a4160c188b8497859da97 --- /dev/null +++ b/frameworks/ets/ani/common/include/ani_utils.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 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 INTERFACES_ETS_ANI_COMMON_ANI_UTILS_H +#define INTERFACES_ETS_ANI_COMMON_ANI_UTILS_H + +#include +#include +#include + +#include "ani.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +bool AniFindNameSpace(ani_env* env, const char* namespaceDescriptor, ani_namespace& out); +bool AniFindClass(ani_env* env, const char* classDescriptor, ani_class& out); +bool AniClassFindMethod(ani_env* env, const ani_class& aniClass, const char* methodDescriptor, const char* signature, + ani_method& out); +bool AniClassFindField(ani_env* env, const ani_class& aniClass, const char *fieldName, ani_field& out); +bool AniFindEnum(ani_env* env, const char *enumDescriptor, ani_enum& out); +bool AniGetEnumItemByIndex(ani_env* env, const ani_enum& aniEnum, ani_size index, ani_enum_item& out); + +bool AniParseString(ani_env* env, const ani_string& ani_str, std::string& out); +bool AniParseStringArray(ani_env* env, const ani_array_ref& ani_str_arr, std::vector& out); +bool AniParseCallback(ani_env* env, const ani_ref& ani_callback, ani_ref& out); +bool AniIsRefUndefined(ani_env* env, const ani_ref& ref, bool& isUndefined); + +bool AniNewString(ani_env* env, const std::string in, ani_string& out); +bool AniNewEnumIteam(ani_env* env, const char* enumDescriptor, ani_size index, ani_enum_item& out); +bool AniNewClassObject(ani_env* env, const ani_class aniClass, const char* methodDescriptor, const char* signature, + ani_object& out); + +bool AniObjectSetFieldInt(ani_env* env, const ani_class& aniClass, ani_object& aniObject, const char* fieldName, + ani_int in); +bool AniObjectSetFieldRef(ani_env* env, const ani_class& aniClass, ani_object& aniObject, const char* fieldName, + const ani_ref& in); +bool AniObjectSetPropertyByNameInt(ani_env* env, ani_object& object, const char *propertyName, int32_t in); +bool AniObjectSetPropertyByNameRef(ani_env* env, ani_object& object, const char *propertyName, ani_ref in); + +bool IsCurrentThread(std::thread::id threadId); +bool AniIsCallbackRefEqual(ani_env* env, const ani_ref& compareRef, const ani_ref& targetRref, std::thread::id threadId, + bool& isEqual); +bool AniFunctionalObjectCall(ani_env *env, const ani_fn_object& fn, ani_size size, ani_ref* argv, ani_ref& result); +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_ETS_ANI_COMMON_ANI_UTILS_H */ diff --git a/frameworks/ets/ani/common/src/ani_error.cpp b/frameworks/ets/ani/common/src/ani_error.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29dfc88f2b297c5887e43e24129508a15d3cffd6 --- /dev/null +++ b/frameworks/ets/ani/common/src/ani_error.cpp @@ -0,0 +1,197 @@ +/* + * 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 "ani_error.h" + +#include + +#include "access_token_error.h" +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_PRIVACY, "CommonAni" }; +} // namespace +constexpr const int32_t RET_SUCCESS = 0; +constexpr const char* BUSINESS_ERROR_CLASS = "L@ohos/base/BusinessError;"; +static const std::unordered_map g_errorStringMap = { + { STS_ERROR_PERMISSION_DENIED, "Permission denied." }, + { STS_ERROR_NOT_SYSTEM_APP, "Not system app." }, + { STS_ERROR_SYSTEM_CAPABILITY_NOT_SUPPORT, "Not support system capability." }, + { STS_ERROR_START_ABILITY_FAIL, "Start grant ability failed." }, + { STS_ERROR_BACKGROUND_FAIL, "UI extension turn background failed." }, + { STS_ERROR_TERMINATE_FAIL, "Ui extension terminate failed." }, + { STS_ERROR_PARAM_INVALID, "Invalid parameter." }, + { STS_ERROR_TOKENID_NOT_EXIST, "The specified token id does not exist." }, + { STS_ERROR_PERMISSION_NOT_EXIST, "The specified permission does not exist." }, + { STS_ERROR_NOT_USE_TOGETHER, "The API is not used in pair with others." }, + { STS_ERROR_REGISTERS_EXCEED_LIMITATION, "The number of registered listeners exceeds limitation." }, + { STS_ERROR_PERMISSION_OPERATION_NOT_ALLOWED, "The operation of specified permission is not allowed." }, + { STS_ERROR_SERVICE_NOT_RUNNING, "The service is abnormal." }, + { STS_ERROR_OUT_OF_MEMORY, "Out of memory." }, + { STS_ERROR_INNER, "Common inner error." }, + { STS_ERROR_REQUEST_IS_ALREADY_EXIST, "The request already exists." }, + { STS_ERROR_ALL_PERM_GRANTED, "All permissions in the permission list have been granted." }, + { STS_ERROR_PERM_REVOKE_BY_USER, + "The permission list contains the permission that has not been revoked by the user." }, + { STS_ERROR_GLOBAL_SWITCH_IS_ALREADY_OPEN, "The specific global switch is already open." }, +}; + +void BusinessErrorAni::ThrowError(ani_env* env, int32_t err, const std::string& errMsg) +{ + if (env == nullptr) { + return; + } + ani_object error = CreateError(env, err, errMsg); + ThrowError(env, error); +} + +ani_object BusinessErrorAni::CreateError(ani_env* env, ani_int code, const std::string& msg) +{ + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "env is nullptr"); + return nullptr; + } + ani_class cls = nullptr; + ani_field field = nullptr; + ani_method method = nullptr; + ani_object obj = nullptr; + + ani_status status = env->FindClass(BUSINESS_ERROR_CLASS, &cls); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass : %{public}d", status); + return nullptr; + } + status = env->Class_FindMethod(cls, "", ":V", &method); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindMethod : %{public}d", status); + return nullptr; + } + status = env->Object_New(cls, method, &obj); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_New : %{public}d", status); + return nullptr; + } + status = env->Class_FindField(cls, "code", &field); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindField : %{public}d", status); + return nullptr; + } + status = env->Object_SetField_Double(obj, field, code); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetField_Double : %{public}d", status); + return nullptr; + } + status = env->Class_FindField(cls, "data", &field); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindField : %{public}d", status); + return nullptr; + } + ani_string string = nullptr; + env->String_NewUTF8(msg.c_str(), msg.size(), &string); + status = env->Object_SetField_Ref(obj, field, static_cast(string)); + if (status != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetField_Ref : %{public}d", status); + return nullptr; + } + return obj; +} + +std::string GetParamErrorMsg(const std::string& param, const std::string& errMsg) +{ + std::string msg = "Parameter Error. The type of \"" + param + "\" must be " + errMsg + "."; + return msg; +} + +std::string GetErrorMessage(uint32_t errCode, const std::string& extendMsg) +{ + auto iter = g_errorStringMap.find(errCode); + if (iter != g_errorStringMap.end()) { + return iter->second + (extendMsg.empty() ? "" : ("" + extendMsg)); + } + std::string errMsg = "Unknown error, errCode " + std::to_string(errCode) + "."; + return errMsg; +} + +void BusinessErrorAni::ThrowParameterTypeError(ani_env* env, int32_t err, const std::string& errMsg) +{ + if (env == nullptr) { + return; + } + ani_object error = CreateError(env, err, errMsg); + ThrowError(env, error); +} + +void BusinessErrorAni::ThrowError(ani_env* env, ani_object err) +{ + if (err == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "err is nullptr"); + return; + } + env->ThrowError(static_cast(err)); +} + +int32_t BusinessErrorAni::GetStsErrorCode(int32_t errCode) +{ + int32_t stsCode; + switch (errCode) { + case RET_SUCCESS: + stsCode = STS_OK; + break; + case ERR_PERMISSION_DENIED: + stsCode = STS_ERROR_PERMISSION_DENIED; + break; + case ERR_NOT_SYSTEM_APP: + stsCode = STS_ERROR_NOT_SYSTEM_APP; + break; + case ERR_PARAM_INVALID: + stsCode = STS_ERROR_PARAM_INVALID; + break; + case ERR_TOKENID_NOT_EXIST: + stsCode = STS_ERROR_TOKENID_NOT_EXIST; + break; + case ERR_PERMISSION_NOT_EXIST: + stsCode = STS_ERROR_PERMISSION_NOT_EXIST; + break; + case ERR_INTERFACE_NOT_USED_TOGETHER: + case ERR_CALLBACK_ALREADY_EXIST: + stsCode = STS_ERROR_NOT_USE_TOGETHER; + break; + case ERR_CALLBACKS_EXCEED_LIMITATION: + stsCode = STS_ERROR_REGISTERS_EXCEED_LIMITATION; + break; + case ERR_IDENTITY_CHECK_FAILED: + stsCode = STS_ERROR_PERMISSION_OPERATION_NOT_ALLOWED; + break; + case ERR_SERVICE_ABNORMAL: + case ERROR_IPC_REQUEST_FAIL: + case ERR_READ_PARCEL_FAILED: + case ERR_WRITE_PARCEL_FAILED: + stsCode = STS_ERROR_SERVICE_NOT_RUNNING; + break; + case ERR_MALLOC_FAILED: + stsCode = STS_ERROR_OUT_OF_MEMORY; + break; + default: + stsCode = STS_ERROR_INNER; + break; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetStsErrorCode nativeCode(%{public}d) stsCode(%{public}d).", errCode, stsCode); + return stsCode; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/ets/ani/common/src/ani_utils.cpp b/frameworks/ets/ani/common/src/ani_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22200802f27bfe0a4c9aa552c2f0dff4cf8c14db --- /dev/null +++ b/frameworks/ets/ani/common/src/ani_utils.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2025 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 "ani_utils.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenAniUtils" }; +} // namespace + +bool AniFindNameSpace(ani_env* env, const char* namespaceDescriptor, ani_namespace& out) +{ + if (env->FindNamespace(namespaceDescriptor, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindNamespace failed!"); + return false; + } + return true; +} + +bool AniFindClass(ani_env* env, const char* classDescriptor, ani_class& out) +{ + if (env->FindClass(classDescriptor, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindClass failed!"); + return false; + } + return true; +} + +bool AniClassFindMethod(ani_env* env, const ani_class& aniClass, const char* methodDescriptor, const char* signature, + ani_method& out) +{ + if (env->Class_FindMethod(aniClass, methodDescriptor, signature, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindMethod failed!"); + return false; + } + return true; +} + +bool AniClassFindField(ani_env* env, const ani_class& aniClass, const char *fieldName, ani_field& out) +{ + if (env->Class_FindField(aniClass, fieldName, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Class_FindField failed!"); + return false; + } + return true; +} + +bool AniFindEnum(ani_env* env, const char *enumDescriptor, ani_enum& out) +{ + if (env->FindEnum(enumDescriptor, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindEnum failed!"); + return false; + } + return true; +} + +bool AniGetEnumItemByIndex(ani_env* env, const ani_enum& aniEnum, ani_size index, ani_enum_item& out) +{ + if (env->Enum_GetEnumItemByIndex(aniEnum, index, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Enum_GetEnumItemByIndex failed!"); + return false; + } + return true; +} + + +bool AniParseString(ani_env* env, const ani_string& ani_str, std::string& out) +{ + ani_size strSize; + if (env->String_GetUTF8Size(ani_str, &strSize) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_GetUTF8Size failed!"); + return false; + } + + std::vector buffer(strSize + 1); // +1 for null terminator + char* utf8Buffer = buffer.data(); + ani_size bytesWritten = 0; + if (env->String_GetUTF8(ani_str, utf8Buffer, strSize + 1, &bytesWritten) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_GetUTF8 failed!"); + return false; + } + if (bytesWritten == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String is empty!"); + return false; + } + utf8Buffer[bytesWritten] = '\0'; + + out = std::string(utf8Buffer); + return true; +} + +bool AniParseStringArray(ani_env* env, const ani_array_ref& ani_str_arr, std::vector& out) +{ + ani_size size = 0; + if (env->Array_GetLength(ani_str_arr, &size) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Array_GetLength failed!"); + return false; + } + + for (ani_size i = 0; i < size; ++i) { + ani_ref aniRef; + if (env->Array_Get_Ref(ani_str_arr, i, &aniRef) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Array_Get_Ref failed!"); + return false; + } + + std::string stdStr; + if (!AniParseString(env, static_cast(aniRef), stdStr)) { + return false; + } + + out.emplace_back(stdStr); + } + return true; +} + +bool AniParseCallback(ani_env* env, const ani_ref& ani_callback, ani_ref& out) +{ + if (env->GlobalReference_Create(ani_callback, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GlobalReference_Create failed!"); + return false; + } + return true; +} + +bool AniIsRefUndefined(ani_env* env, const ani_ref& ref, bool& isUndefined) +{ + ani_boolean isUnd; + if (env->Reference_IsUndefined(ref, &isUnd) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Reference_IsUndefined failed!"); + return false; + } + isUndefined = isUnd ? true : false; + return true; +} + +bool AniNewString(ani_env* env, const std::string in, ani_string& out) +{ + if (env->String_NewUTF8(in.c_str(), in.size(), &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_NewUTF8 failed!"); + return false; + } + return true; +} + +bool AniNewEnumIteam(ani_env* env, const char* enumDescriptor, ani_size index, ani_enum_item& out) +{ + ani_enum aniEnum; + if (!AniFindEnum(env, enumDescriptor, aniEnum)) { + return false; + } + return AniGetEnumItemByIndex(env, aniEnum, index, out); +} + +bool AniNewClassObject(ani_env* env, const ani_class aniClass, const char* methodDescriptor, const char* signature, + ani_object& out) +{ + ani_method aniMethod; + if (!AniClassFindMethod(env, aniClass, methodDescriptor, signature, aniMethod)) { + return false; + } + + if (env->Object_New(aniClass, aniMethod, &out) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_New failed!"); + return false; + } + return true; +} + +bool AniObjectSetFieldInt(ani_env* env, const ani_class& aniClass, ani_object& aniObject, const char* fieldName, + ani_int in) +{ + ani_field aniField; + if (!AniClassFindField(env, aniClass, fieldName, aniField)) { + return false; + } + + if (env->Object_SetField_Int(aniObject, aniField, in) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetField_Int failed!"); + return false; + } + return true; +} + +bool AniObjectSetFieldRef(ani_env* env, const ani_class& aniClass, ani_object& aniObject, const char* fieldName, + const ani_ref& in) +{ + ani_field aniField; + if (!AniClassFindField(env, aniClass, fieldName, aniField)) { + return false; + } + + if (env->Object_SetField_Ref(aniObject, aniField, in) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetField_Ref failed!"); + return false; + } + return true; +} + +bool AniObjectSetPropertyByNameInt(ani_env* env, ani_object& object, const char *propertyName, ani_int in) +{ + if (env->Object_SetPropertyByName_Int(object, propertyName, in) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetPropertyByName_Int failed!"); + return false; + } + return true; +} + +bool AniObjectSetPropertyByNameRef(ani_env* env, ani_object& object, const char *propertyName, ani_ref in) +{ + if (env->Object_SetPropertyByName_Ref(object, propertyName, in) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_SetPropertyByName_Ref failed!"); + return false; + } + return true; +} + +bool IsCurrentThread(std::thread::id threadId) +{ + std::thread::id currentThread = std::this_thread::get_id(); + if (threadId != currentThread) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Ani_ref can not be compared, different threadId."); + return false; + } + return true; +} + +bool AniIsCallbackRefEqual(ani_env* env, const ani_ref& compareRef, const ani_ref& targetRref, std::thread::id threadId, + bool& isEqual) +{ + if (!IsCurrentThread(threadId)) { + return false; + } + + ani_boolean isEq = false; + if (env->Reference_StrictEquals(compareRef, targetRref, &isEq) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Reference_StrictEquals failed."); + return false; + } + isEqual = isEq ? true : false; + return true; +} + +bool AniFunctionalObjectCall(ani_env *env, const ani_fn_object& fn, ani_size size, ani_ref* argv, ani_ref& result) +{ + if (env->FunctionalObject_Call(fn, size, argv, &result) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "AniFunctionalObjectCall failed."); + return false; + } + return true; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/frameworks/ets/ani/privacy/BUILD.gn b/frameworks/ets/ani/privacy/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cb1ddd50250328bff9049eab799990c576ea846d --- /dev/null +++ b/frameworks/ets/ani/privacy/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2025 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("//base/security/access_token/access_token.gni") +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/ace/ace.gni") + +ohos_shared_library("privacy_ani") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags_cc = [ "-DHILOG_ENABLE" ] + include_dirs = [ + "${access_token_path}/frameworks/common/include", + "${access_token_path}/interfaces/innerkits/accesstoken/include", + "${access_token_path}/interfaces/innerkits/privacy/include", + "${access_token_path}/frameworks/ets/ani/common/include", + "${access_token_path}/frameworks/ets/ani/privacy/include", + ] + sources = [ "src/privacy_manager.cpp" ] + + deps = [ + "${access_token_path}/frameworks/ets/ani/common:libani_common", + "${access_token_path}/interfaces/innerkits/privacy:libprivacy_sdk", + ] + + external_deps = [ + "hilog:libhilog", + "runtime_core:ani", + "runtime_core:libarkruntime", + ] + + part_name = "access_token" + subsystem_name = "security" +} + +generate_static_abc("privacy_manager") { + base_url = "./ets" + files = [ "./ets/@ohos.privacyManager.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/privacy_manager.abc" +} + +ohos_prebuilt_etc("privacy_manager_etc") { + source = "$target_out_dir/privacy_manager.abc" + deps = [ ":privacy_manager" ] + module_install_dir = "framework" + + part_name = "access_token" + subsystem_name = "security" +} + +group("privacy_ets") { + deps = [ + ":privacy_ani", + ":privacy_manager_etc", + ] +} diff --git a/frameworks/ets/ani/privacy/ets/@ohos.privacyManager.ets b/frameworks/ets/ani/privacy/ets/@ohos.privacyManager.ets new file mode 100644 index 0000000000000000000000000000000000000000..9b3413d4582d1f2724591a687d7b8480101e0c5f --- /dev/null +++ b/frameworks/ets/ani/privacy/ets/@ohos.privacyManager.ets @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2025 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 { AsyncCallback, Callback, BusinessError} from '@ohos.base'; +import { Permissions } from 'permissions'; + +function PARAM_ERROR_MSG(param: string, type: string): string { + return `Parameter Error. The type of "${param}" must be ${type}.`; +} + +export { Permissions } + +export default namespace privacyManager { + loadLibrary("privacy_ani.z"); + + enum PermissionUsedType { + NORMAL_TYPE = 0, + PICKER_TYPE = 1, + SECURITY_COMPONENT_TYPE = 2 + } + + enum PermissionActiveStatus { + PERM_INACTIVE = 0, + PERM_ACTIVE_IN_FOREGROUND = 1, + PERM_ACTIVE_IN_BACKGROUND = 2 + } + + enum STSErrorCode { + STS_OK = 0, + STS_ERROR_PERMISSION_DENIED = 201, + STS_ERROR_NOT_SYSTEM_APP = 202, + STS_ERROR_PARAM_ILLEGAL = 401, + STS_ERROR_SYSTEM_CAPABILITY_NOT_SUPPORT = 801, + } ; + + interface AddPermissionUsedRecordOptions { + usedType?: PermissionUsedType; + } + + class AddPermissionUsedRecordOptionsInner implements AddPermissionUsedRecordOptions { + usedType: PermissionUsedType|undefined; + } + + class PrivacyManagerInner { + native addPermissionUsedRecordSync(tokenID: int, permissionName: Permissions, successCount: int, failCount: int, + options: AddPermissionUsedRecordOptionsInner): void; + + native stopUsingPermissionExecute(tokenID: int, permissionName: Permissions, pid: int): void; + + native startUsingPermissionExecute(tokenID: int, permissionName: Permissions, pid: int, + usedType: int): void; + + } + + interface UsedRecordDetail { + status: number; + lockScreenStatus?: number; + timestamp: number; + count?: number; + accessDuration: number; + usedType?: PermissionUsedType; + } + + interface PermissionUsedTypeInfo { + tokenId: number; + permissionName: Permissions; + usedType: PermissionUsedType; + } + + interface ActiveChangeResponse { + callingTokenId?: int; + tokenId: int; + permissionName: Permissions; + deviceId: string; + activeStatus: PermissionActiveStatus; + usedType?: PermissionUsedType; + } + + class ActiveChangeResponseInner implements ActiveChangeResponse { + callingTokenId?: int; + tokenId: int; + permissionName: Permissions; + deviceId: string; + activeStatus: PermissionActiveStatus; + usedType?: PermissionUsedType; + } + + function addPermissionUsedRecord(tokenID: int, permissionName: Permissions, successCount: int, + failCount: int, options?: AddPermissionUsedRecordOptions): Promise { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + + let usedTypeTemp : PermissionUsedType|undefined = options ? options.usedType : PermissionUsedType.NORMAL_TYPE; + let optionsLocal: AddPermissionUsedRecordOptionsInner = { usedType: usedTypeTemp }; + let p = new Promise((resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p1 = taskpool.execute((): void => { return new PrivacyManagerInner().addPermissionUsedRecordSync( + tokenID, permissionName, successCount, failCount, optionsLocal) }); + p1.then(() => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + function addPermissionUsedRecord(tokenID: int, permissionName: Permissions, successCount: int, + failCount: int, callback: AsyncCallback): void { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionsLocal: AddPermissionUsedRecordOptionsInner = { usedType: PermissionUsedType.NORMAL_TYPE }; + let p2 = taskpool.execute((): void => { + return new PrivacyManagerInner().addPermissionUsedRecordSync(tokenID, permissionName, + successCount, failCount, optionsLocal)}); + p2.then(() => { + let err = new BusinessError(); + callback(err, undefined); + },(err: Error): void=> { + callback(err as BusinessError, undefined); + }) + } + + function stopUsingPermission(tokenID: int, permissionName: Permissions): Promise { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid = -1; + let p = new Promise((resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p1 = taskpool.execute((): void => { + return new PrivacyManagerInner().stopUsingPermissionExecute(tokenID, permissionName, optionalPid) }); + p1.then(() => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + function stopUsingPermission(tokenID: int, permissionName: Permissions, callback: AsyncCallback): void { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid = -1; + let p2 = taskpool.execute((): void => { + return new PrivacyManagerInner().stopUsingPermissionExecute(tokenID, permissionName, optionalPid) }); + p2.then(() => { + let err = new BusinessError(); + callback(err, undefined); + },(err: Error): void=> { + callback(err as BusinessError, undefined); + }) + } + + function stopUsingPermission(tokenID: int, permissionName: Permissions, pid?: int): Promise { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid: int = pid ?? -1; + let p = new Promise((resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p1 = taskpool.execute((): void => { + return new PrivacyManagerInner().stopUsingPermissionExecute(tokenID, permissionName, optionalPid) }); + p1.then(() => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + function startUsingPermission(tokenID: int, permissionName: Permissions): Promise { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid = -1; + let optionalUsedType = PermissionUsedType.NORMAL_TYPE; + let p = new Promise((resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p1 = taskpool.execute((): void => { + return new PrivacyManagerInner().startUsingPermissionExecute(tokenID, permissionName, + optionalPid, optionalUsedType) }); + p1.then(() => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + function startUsingPermission(tokenID: int, permissionName: Permissions, callback: AsyncCallback): void { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid = -1; + let optionalUsedType = PermissionUsedType.NORMAL_TYPE; + let p2 = taskpool.execute((): void => { + return new PrivacyManagerInner().startUsingPermissionExecute(tokenID, permissionName, + optionalPid, optionalUsedType) }); + p2.then(() => { + let err = new BusinessError(); + callback(err, undefined); + },(err: Error): void => { + callback(err as BusinessError, undefined); + }) + } + + function startUsingPermission(tokenID: int, permissionName: Permissions, pid?: int, + usedType?: PermissionUsedType): Promise { + if (typeof permissionName !== "string") { + let err = new BusinessError(); + err.code = STSErrorCode.STS_ERROR_PARAM_ILLEGAL; + err.data = PARAM_ERROR_MSG("permissionName", "Permissions"); + throw err; + } + let optionalPid: int = pid ?? -1; + let optionalUsedType = usedType ?? PermissionUsedType.NORMAL_TYPE; + let p = new Promise((resolve: (v: undefined) => void, reject: (error: BusinessError) => void): void => { + let p1 = taskpool.execute((): void => { + return new PrivacyManagerInner().startUsingPermissionExecute(tokenID, permissionName, + optionalPid, optionalUsedType) }); + p1.then(() => { + resolve(undefined); + }).catch((err: Error): void => { + reject(err as BusinessError); + }); + }); + return p; + } + + export native function on(type: 'activeStateChange', permissionList: Array, + callback: Callback): void; + + export native function off(type: 'activeStateChange', permissionList: Array, + callback?: Callback): void; +} diff --git a/frameworks/ets/ani/privacy/include/privacy_manager.h b/frameworks/ets/ani/privacy/include/privacy_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4129447bb91a3f0ff2a8f488de250b30bcf30db8 --- /dev/null +++ b/frameworks/ets/ani/privacy/include/privacy_manager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025 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 INTERFACES_ETS_ANI_PRIVACY_MANAGER_H +#define INTERFACES_ETS_ANI_PRIVACY_MANAGER_H + +#include +#include +#include +#include + +#include "ani.h" +#include "perm_active_status_customized_cbk.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class PermActiveStatusPtr : public std::enable_shared_from_this, + public PermActiveStatusCustomizedCbk { +public: + explicit PermActiveStatusPtr(const std::vector& permList); + ~PermActiveStatusPtr() override; + void ActiveStatusChangeCallback(ActiveChangeResponse& result) override; + void SetVm(ani_vm* vm); + void SetEnv(ani_env* env); + void SetCallbackRef(const ani_ref& ref); + void SetThreadId(const std::thread::id threadId); +private: + ani_env* env_ = nullptr; + ani_vm* vm_ = nullptr; + ani_ref ref_ = nullptr; + std::thread::id threadId_; +}; + +struct RegisterPermActiveChangeContext { + ani_env* env = nullptr; + ani_ref callbackRef = nullptr; + std::string type; + std::vector permissionList; + std::shared_ptr subscriber = nullptr; + std::thread::id threadId; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif /* INTERFACES_ETS_ANI_PRIVACY_MANAGER_H */ diff --git a/frameworks/ets/ani/privacy/src/privacy_manager.cpp b/frameworks/ets/ani/privacy/src/privacy_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b2208f522c6e235d53ef4259428c58ab0e5c66f --- /dev/null +++ b/frameworks/ets/ani/privacy/src/privacy_manager.cpp @@ -0,0 +1,788 @@ +/* + * Copyright (c) 2025 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 "privacy_manager.h" + +#include + +#include "accesstoken_log.h" +#include "ani_error.h" +#include "ani_utils.h" +#include "privacy_error.h" +#include "privacy_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_PRIVACY, "AniPrivacyManager" }; +std::mutex g_mutex; +std::vector g_subScribers; +static constexpr size_t MAX_CALLBACK_SIZE = 200; +static constexpr ani_size ACTIVE_CHANGE_TYPE_INDEX_ONE = 1; +static constexpr ani_size ACTIVE_CHANGE_TYPE_INDEX_TWO = 2; +static constexpr ani_size PERMMISSION_USED_TYPE_INDEX_ONE = 1; +static constexpr ani_size PERMMISSION_USED_TYPE_INDEX_TWO = 2; +constexpr const char* ACTIVE_CHANGE_FIELD_CALLING_TOKEN_ID = "callingTokenId"; +constexpr const char* ACTIVE_CHANGE_FIELD_TOKEN_ID = "tokenId"; +constexpr const char* ACTIVE_CHANGE_FIELD_PERMISSION_NAME = "permissionName"; +constexpr const char* ACTIVE_CHANGE_FIELD_DEVICE_ID = "deviceId"; +constexpr const char* ACTIVE_CHANGE_FIELD_ACTIVE_STATUS = "activeStatus"; +constexpr const char* ACTIVE_CHANGE_FIELD_USED_TYPE = "usedType"; +} + +static int32_t GetStsErrorCode(int32_t errCode) +{ + int32_t stsCode; + switch (errCode) { + case RET_SUCCESS: + stsCode = STS_OK; + break; + case ERR_PERMISSION_DENIED: + stsCode = STS_ERROR_PERMISSION_DENIED; + break; + case ERR_NOT_SYSTEM_APP: + stsCode = STS_ERROR_NOT_SYSTEM_APP; + break; + case ERR_PARAM_INVALID: + stsCode = STS_ERROR_PARAM_INVALID; + break; + case ERR_TOKENID_NOT_EXIST: + stsCode = STS_ERROR_TOKENID_NOT_EXIST; + break; + case ERR_PERMISSION_NOT_EXIST: + stsCode = STS_ERROR_PERMISSION_NOT_EXIST; + break; + case ERR_CALLBACK_ALREADY_EXIST: + case ERR_CALLBACK_NOT_EXIST: + case ERR_PERMISSION_ALREADY_START_USING: + case ERR_PERMISSION_NOT_START_USING: + stsCode = STS_ERROR_NOT_USE_TOGETHER; + break; + case ERR_CALLBACKS_EXCEED_LIMITATION: + stsCode = STS_ERROR_REGISTERS_EXCEED_LIMITATION; + break; + case ERR_IDENTITY_CHECK_FAILED: + stsCode = STS_ERROR_PERMISSION_OPERATION_NOT_ALLOWED; + break; + case ERR_SERVICE_ABNORMAL: + case ERROR_IPC_REQUEST_FAIL: + case ERR_READ_PARCEL_FAILED: + case ERR_WRITE_PARCEL_FAILED: + stsCode = STS_ERROR_SERVICE_NOT_RUNNING; + break; + case ERR_MALLOC_FAILED: + stsCode = STS_ERROR_OUT_OF_MEMORY; + break; + default: + stsCode = STS_ERROR_INNER; + break; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetStsErrorCode nativeCode(%{public}d) stsCode(%{public}d).", errCode, stsCode); + return stsCode; +} + +static void AddPermissionUsedRecordSync(ani_env* env, const AddPermParamInfo& info) +{ + auto retCode = PrivacyKit::AddPermissionUsedRecord(info); + if (retCode != RET_SUCCESS) { + int32_t stsCode = GetStsErrorCode(retCode); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return; + } + ACCESSTOKEN_LOG_INFO(LABEL, "call addPermissionUsedRecord retCode : %{public}d", retCode); +} + +static void AddPermissionUsedRecord([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_int tokenID, ani_string permissionName, ani_int successCount, ani_int failCount, ani_object options) +{ + if (env == nullptr) { + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + ani_size strSize; + ani_status status = ANI_ERROR; + if (ANI_OK != (status = env->String_GetUTF8Size(permissionName, &strSize))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "String_GetUTF8Size_Faild status : %{public}d", status); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + std::vector buffer(strSize + 1); + char* utf8Buffer = buffer.data(); + ani_size bytesWritten = 0; + if (ANI_OK != (status = env->String_GetUTF8(permissionName, utf8Buffer, strSize + 1, &bytesWritten))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "get String_GetUTF8 Faild status : %{public}d", status); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + utf8Buffer[bytesWritten] = '\0'; + std::string outputPermissionName = std::string(utf8Buffer); + ani_ref usedTypeRef; + if (ANI_OK != (status = env->Object_GetPropertyByName_Ref(options, "usedType", &usedTypeRef))) { + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + ACCESSTOKEN_LOG_ERROR(LABEL, "Object_GetFieldByName_Ref Faild status : %{public}d", status); + return; + } + ani_int usedType = 0; + ani_boolean isUndefined = true; + if (ANI_OK != (status = env->Reference_IsUndefined(usedTypeRef, &isUndefined))) { + ACCESSTOKEN_LOG_ERROR(LABEL, "status : %{public}d", status); + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + if (!isUndefined) { + ani_enum_item usedTypeEnum = static_cast(usedTypeRef); + if (ANI_OK != env->EnumItem_GetValue_Int(usedTypeEnum, &usedType)) { + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + } + AddPermParamInfo info; + info.tokenId = static_cast(tokenID); + info.permissionName = outputPermissionName; + info.successCount = successCount; + info.failCount = failCount; + info.type = static_cast(usedType); + AddPermissionUsedRecordSync(env, info); +} + +PermActiveStatusPtr::PermActiveStatusPtr(const std::vector& permList) + : PermActiveStatusCustomizedCbk(permList) +{} + +PermActiveStatusPtr::~PermActiveStatusPtr() +{ + if (vm_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "vm is nullptr;"); + return; + } + + bool isSameThread = (threadId_ == std::this_thread::get_id()); + ani_env* env; + if (isSameThread) { + env = env_; + } else { + ani_option interopEnabled {"--interop=disable", nullptr}; + ani_options aniArgs {1, &interopEnabled}; + vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env); + } + + if (ref_ != nullptr) { + env->GlobalReference_Delete(ref_); + ref_ = nullptr; + } + + if (!isSameThread) { + vm_->DetachCurrentThread(); + } +} + +void PermActiveStatusPtr::SetVm(ani_vm* vm) +{ + vm_ = vm; +} + +void PermActiveStatusPtr::SetEnv(ani_env* env) +{ + env_ = env; +} + +void PermActiveStatusPtr::SetCallbackRef(const ani_ref& ref) +{ + ref_ = ref; +} + +void PermActiveStatusPtr::SetThreadId(const std::thread::id threadId) +{ + threadId_ = threadId; +} + +static bool GenerateAniClassAndObject(ani_env* env, ani_class& aniClass, ani_object& aniObject) +{ + const char* classDescriptor = "L@ohos/privacyManager/privacyManager/ActiveChangeResponseInner;"; + if (!AniFindClass(env, classDescriptor, aniClass)) { + return false; + } + + const char* methodDescriptor = ""; + const char* signature = nullptr; + if (!AniNewClassObject(env, aniClass, methodDescriptor, signature, aniObject)) { + return false; + } + + return true; +} + +static bool SetOptionalIntProperty(ani_env* env, ani_object& aniObject, const char* propertyName, const ani_int in) +{ + ani_class aniClass; + const char* classDescriptor = "Lstd/core/Int;"; + if (!AniFindClass(env, classDescriptor, aniClass)) { + return false; + } + + const char* methodDescriptor = ""; // means constructor + const char* signature = "I:V"; // I:V means input is int, return is void + ani_method aniMethod; + if (!AniClassFindMethod(env, aniClass, methodDescriptor, signature, aniMethod)) { + return false; + } + + ani_object intObject; + if (env->Object_New(aniClass, aniMethod, &intObject, in) != ANI_OK) { + return false; + } + + if (!AniObjectSetPropertyByNameRef(env, aniObject, propertyName, intObject)) { + return false; + } + + return true; +} + +static bool SetStringProperty(ani_env* env, ani_object& aniObject, const char* propertyName, const std::string in) +{ + ani_string aniString; + if (!AniNewString(env, in, aniString)) { + return false; + } + + if (!AniObjectSetPropertyByNameRef(env, aniObject, propertyName, aniString)) { + return false; + } + + return true; +} + +static bool SetEnumProperty(ani_env* env, ani_object& aniObject, const char* enumDescription, const char* propertyName, + ani_size index) +{ + ani_enum_item aniEnumItem; + if (!AniNewEnumIteam(env, enumDescription, index, aniEnumItem)) { + return false; + } + + if (!AniObjectSetPropertyByNameRef(env, aniObject, propertyName, aniEnumItem)) { + return false; + } + + return true; +} + +static bool TransFormActiveChangeTypeToIndex(ActiveChangeType type, ani_size& index) +{ + if (type == ActiveChangeType::PERM_INACTIVE) { + index = 0; + } else if (type == ActiveChangeType::PERM_ACTIVE_IN_FOREGROUND) { + index = ACTIVE_CHANGE_TYPE_INDEX_ONE; + } else if (type == ActiveChangeType::PERM_ACTIVE_IN_BACKGROUND) { + index = ACTIVE_CHANGE_TYPE_INDEX_TWO; + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid ActiveChangeType value!"); + return false; + } + return true; +} + +static bool TransFormPermissionUsedTypeToIndex(PermissionUsedType type, ani_size& index) +{ + if (type == PermissionUsedType::NORMAL_TYPE) { + index = 0; + } else if (type == PermissionUsedType::PICKER_TYPE) { + index = PERMMISSION_USED_TYPE_INDEX_ONE; + } else if (type == PermissionUsedType::SECURITY_COMPONENT_TYPE) { + index = PERMMISSION_USED_TYPE_INDEX_TWO; + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "Invalid PermissionUsedType value!"); + return false; + } + return true; +} + +static void ConvertActiveChangeResponse(ani_env* env, const ActiveChangeResponse& result, ani_object& aniObject) +{ + // class implements from interface should use property, independent class use field + ani_class aniClass; + if (!GenerateAniClassAndObject(env, aniClass, aniObject)) { + return; + } + + // set callingTokenID?: int optional parameter callingTokenID need box as a object + if (!SetOptionalIntProperty(env, aniObject, ACTIVE_CHANGE_FIELD_CALLING_TOKEN_ID, + static_cast(result.callingTokenID))) { + return; + } + + // set tokenID: int + if (!AniObjectSetPropertyByNameInt(env, aniObject, ACTIVE_CHANGE_FIELD_TOKEN_ID, + static_cast(result.tokenID))) { + return; + } + + // set permissionName: string + if (!SetStringProperty(env, aniObject, ACTIVE_CHANGE_FIELD_PERMISSION_NAME, result.permissionName)) { + return; + } + + // set deviceId: string + if (!SetStringProperty(env, aniObject, ACTIVE_CHANGE_FIELD_DEVICE_ID, result.deviceId)) { + return; + } + + // set activeStatus: PermissionActiveStatus + ani_size index = 0; + if (!TransFormActiveChangeTypeToIndex(result.type, index)) { + return; + } + const char* activeStatusDes = "L@ohos/privacyManager/privacyManager/PermissionActiveStatus;"; + if (!SetEnumProperty(env, aniObject, activeStatusDes, ACTIVE_CHANGE_FIELD_ACTIVE_STATUS, index)) { + return; + } + + // set usedType?: PermissionUsedType + index = 0; + if (!TransFormPermissionUsedTypeToIndex(result.usedType, index)) { + return; + } + const char* permUsedTypeDes = "L@ohos/privacyManager/privacyManager/PermissionUsedType;"; + if (!SetEnumProperty(env, aniObject, permUsedTypeDes, ACTIVE_CHANGE_FIELD_USED_TYPE, index)) { + return; + } +} + +void PermActiveStatusPtr::ActiveStatusChangeCallback(ActiveChangeResponse& activeChangeResponse) +{ + if (vm_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "vm is nullptr;"); + return; + } + + ani_option interopEnabled {"--interop=disable", nullptr}; + ani_options aniArgs {1, &interopEnabled}; + ani_env* env; + if (vm_->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "AttachCurrentThread failed!"); + return; + } + + ani_fn_object fnObj = reinterpret_cast(ref_); + if (fnObj == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Reinterpret_cast failed!"); + return; + } + + ani_object aniObject; + ConvertActiveChangeResponse(env, activeChangeResponse, aniObject); + + std::vector args; + args.emplace_back(aniObject); + ani_ref result; + if (!AniFunctionalObjectCall(env, fnObj, args.size(), args.data(), result)) { + return; + } + + if (vm_->DetachCurrentThread() != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "DetachCurrentThread failed!"); + return; + } +} + +static bool ParseInputToRegister(const ani_string& aniType, const ani_array_ref& aniArray, + const ani_ref& aniCallback, RegisterPermActiveChangeContext* context, bool isReg) +{ + std::string type; // type: the first parameter is string + if (!AniParseString(context->env, aniType, type)) { + BusinessErrorAni::ThrowError(context->env, STS_ERROR_PARAM_INVALID, GetParamErrorMsg("type", "string")); + return false; + } + + std::vector permList; // permissionList: the second parameter is Array + if (!AniParseStringArray(context->env, aniArray, permList)) { + BusinessErrorAni::ThrowError(context->env, STS_ERROR_PARAM_INVALID, GetParamErrorMsg( + "permissionList", "Array")); + return false; + } + std::sort(permList.begin(), permList.end()); + + bool hasCallback = true; + if (!isReg) { + bool isUndefined = true; + if (!AniIsRefUndefined(context->env, aniCallback, isUndefined)) { + BusinessErrorAni::ThrowError( + context->env, STS_ERROR_PARAM_INVALID, GetErrorMessage(STSErrorCode::STS_ERROR_PARAM_INVALID)); + return false; + } + hasCallback = !isUndefined; + } + + ani_ref callback = nullptr; // callback: the third parameter is function + if (hasCallback) { + if (!AniParseCallback(context->env, aniCallback, callback)) { + BusinessErrorAni::ThrowError(context->env, STS_ERROR_PARAM_INVALID, GetParamErrorMsg( + "callback", "Callback")); + return false; + } + } + + ani_vm* vm; + if (context->env->GetVM(&vm) != ANI_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetVM failed!"); + return false; + } + + context->callbackRef = callback; + context->type = type; + context->permissionList = permList; + context->subscriber = std::make_shared(permList); + context->threadId = std::this_thread::get_id(); + + context->subscriber->SetVm(vm); + context->subscriber->SetEnv(context->env); + context->subscriber->SetCallbackRef(callback); + context->subscriber->SetThreadId(context->threadId); + + return true; +} + +static bool IsExistRegister(const RegisterPermActiveChangeContext* context) +{ + std::vector targetPermList; + context->subscriber->GetPermList(targetPermList); + std::lock_guard lock(g_mutex); + for (const auto& item : g_subScribers) { + std::vector permList; + item->subscriber->GetPermList(permList); + bool hasPermIntersection = false; + // Special cases: + // 1.Have registered full, and then register some + // 2.Have registered some, then register full + if (permList.empty() || targetPermList.empty()) { + hasPermIntersection = true; + } + for (const auto& PermItem : targetPermList) { + if (hasPermIntersection) { + break; + } + auto iter = std::find(permList.begin(), permList.end(), PermItem); + if (iter != permList.end()) { + hasPermIntersection = true; + } + } + bool isEqual = true; + if (!AniIsCallbackRefEqual(context->env, item->callbackRef, context->callbackRef, item->threadId, isEqual)) { + return true; + } + if (hasPermIntersection && isEqual) { + return true; + } + } + return false; +} + +static void RegisterPermActiveStatusCallback([[maybe_unused]] ani_env* env, + ani_string aniType, ani_array_ref aniArray, ani_ref callback) +{ + if (env == nullptr) { + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + + RegisterPermActiveChangeContext* context = new (std::nothrow) RegisterPermActiveChangeContext(); + if (context == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to allocate memory for RegisterPermActiveChangeContext!"); + BusinessErrorAni::ThrowError(env, STS_ERROR_OUT_OF_MEMORY, GetErrorMessage( + STSErrorCode::STS_ERROR_OUT_OF_MEMORY)); + return; + } + context->env = env; + std::unique_ptr callbackPtr {context}; + + if (!ParseInputToRegister(aniType, aniArray, callback, context, true)) { + return; + } + + if (IsExistRegister(context)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "Subscribe failed. The current subscriber has existed or Reference_StrictEquals failed!"); + BusinessErrorAni::ThrowError( + env, STSErrorCode::STS_ERROR_NOT_USE_TOGETHER, GetErrorMessage(STSErrorCode::STS_ERROR_NOT_USE_TOGETHER)); + return; + } + + int32_t result = PrivacyKit::RegisterPermActiveStatusCallback(context->subscriber); + if (result != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "RegisterPermActiveStatusCallback failed, res is %{public}d", result); + int32_t stsCode = GetStsErrorCode(result); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return; + } + + { + std::lock_guard lock(g_mutex); + if (g_subScribers.size() >= MAX_CALLBACK_SIZE) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Subscribers size has reached the max %{public}zu.", MAX_CALLBACK_SIZE); + BusinessErrorAni::ThrowError(env, STSErrorCode::STS_ERROR_REGISTERS_EXCEED_LIMITATION, + GetErrorMessage(STSErrorCode::STS_ERROR_REGISTERS_EXCEED_LIMITATION)); + return; + } + g_subScribers.emplace_back(context); + } + + callbackPtr.release(); + ACCESSTOKEN_LOG_INFO(LABEL, "RegisterPermActiveStatusCallback success!"); + return; +} + +static bool IsRefUndefined(ani_env* env, const ani_ref& ref) +{ + bool isUndef = false; + if (!AniIsRefUndefined(env, ref, isUndef)) { + return false; + } + return isUndef; +} + +static bool FindAndGetSubscriber(const RegisterPermActiveChangeContext* context, + std::vector& batchPermActiveChangeSubscribers) +{ + std::vector targetPermList = context->permissionList; + std::lock_guard lock(g_mutex); + bool callbackEqual; + ani_ref callbackRef = context->callbackRef; + bool isUndef = IsRefUndefined(context->env, context->callbackRef); + for (const auto& item : g_subScribers) { + std::vector permList; + item->subscriber->GetPermList(permList); + // targetCallback == nullptr, Unsubscribe from all callbacks under the same permList + // targetCallback != nullptr, unregister the subscriber with same permList and callback + if (isUndef) { + // batch delete currentThread callback + ACCESSTOKEN_LOG_INFO(LABEL, "Callback is nullptr."); + callbackEqual = IsCurrentThread(item->threadId); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, "Compare callback."); + if (!AniIsCallbackRefEqual(context->env, item->callbackRef, callbackRef, item->threadId, callbackEqual)) { + continue; + } + } + + if (callbackEqual && (permList == targetPermList)) { + batchPermActiveChangeSubscribers.emplace_back(item); + if (!isUndef) { + return true; + } + } + } + if (!batchPermActiveChangeSubscribers.empty()) { + return true; + } + return false; +} + +static void DeleteRegisterInVector(const RegisterPermActiveChangeContext* context) +{ + std::vector targetPermList; + context->subscriber->GetPermList(targetPermList); + std::lock_guard lock(g_mutex); + auto item = g_subScribers.begin(); + while (item != g_subScribers.end()) { + bool isEqual = true; + if (!AniIsCallbackRefEqual( + context->env, (*item)->callbackRef, context->callbackRef, (*item)->threadId, isEqual)) { + continue; + } + if (!isEqual) { + continue; + } + + std::vector permList; + (*item)->subscriber->GetPermList(permList); + if (permList == targetPermList) { + delete *item; + *item = nullptr; + g_subScribers.erase(item); + return; + } else { + ++item; + } + } +} + +static void UnRegisterPermActiveStatusCallback([[maybe_unused]] ani_env* env, + ani_string aniType, ani_array_ref aniArray, ani_ref callback) +{ + if (env == nullptr) { + BusinessErrorAni::ThrowError(env, STS_ERROR_INNER, GetErrorMessage(STSErrorCode::STS_ERROR_INNER)); + return; + } + + RegisterPermActiveChangeContext* context = new (std::nothrow) RegisterPermActiveChangeContext(); + if (context == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to allocate memory for RegisterPermActiveChangeContext!"); + BusinessErrorAni::ThrowError(env, STS_ERROR_OUT_OF_MEMORY, GetErrorMessage( + STSErrorCode::STS_ERROR_OUT_OF_MEMORY)); + return; + } + context->env = env; + std::unique_ptr callbackPtr {context}; + + if (!ParseInputToRegister(aniType, aniArray, callback, context, false)) { + return; + } + + std::vector batchPermActiveChangeSubscribers; + if (!FindAndGetSubscriber(context, batchPermActiveChangeSubscribers)) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "Unsubscribe failed. The current subscriber does not exist or Reference_StrictEquals failed!"); + BusinessErrorAni::ThrowError( + env, STSErrorCode::STS_ERROR_NOT_USE_TOGETHER, GetErrorMessage(STSErrorCode::STS_ERROR_NOT_USE_TOGETHER)); + return; + } + + for (const auto& item : batchPermActiveChangeSubscribers) { + int32_t result = PrivacyKit::UnRegisterPermActiveStatusCallback(item->subscriber); + if (result != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnregisterPermActiveChangeCompleted failed"); + int32_t stsCode = GetStsErrorCode(result); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + return; + } + + DeleteRegisterInVector(item); + } + ACCESSTOKEN_LOG_INFO(LABEL, "UnRegisterPermActiveStatusCallback success!"); + return; +} + +static void StopUsingPermissionExecute([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_int tokenID, ani_string permissionName, ani_int pid) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "StopUsingPermissionExecute begin."); + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "env null"); + return; + } + + std::string permissionNameString; + if (!AniParseString(env, permissionName, permissionNameString)) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, + "PermissionName : %{public}s, tokenID : %{public}u, pid : %{public}d", + permissionNameString.c_str(), tokenID, pid); + + auto retCode = PrivacyKit::StopUsingPermission(tokenID, permissionNameString, pid); + if (retCode != RET_SUCCESS) { + int32_t stsCode = GetStsErrorCode(retCode); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + } +} + +static void StartUsingPermissionExecute([[maybe_unused]] ani_env* env, [[maybe_unused]] ani_object object, + ani_int tokenID, ani_string permissionName, ani_int pid, PermissionUsedType usedType) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "StartUsingPermissionExecute begin."); + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Env null"); + return; + } + + std::string permissionNameString; + if (!AniParseString(env, permissionName, permissionNameString)) { + BusinessErrorAni::ThrowParameterTypeError(env, STS_ERROR_PARAM_ILLEGAL, + GetParamErrorMsg("permissionName", "Permissions")); + return; + } + + ACCESSTOKEN_LOG_INFO(LABEL, + "PermissionName : %{public}s, tokenID : %{public}u, pid : %{public}d, UsedType : %{public}d", + permissionNameString.c_str(), tokenID, pid, usedType); + + auto retCode = PrivacyKit::StartUsingPermission(tokenID, permissionNameString, pid, usedType); + if (retCode != RET_SUCCESS) { + int32_t stsCode = GetStsErrorCode(retCode); + BusinessErrorAni::ThrowError(env, stsCode, GetErrorMessage(stsCode)); + } +} +extern "C" { +ANI_EXPORT ani_status ANI_Constructor(ani_vm* vm, uint32_t* result) +{ + if (vm == nullptr || result == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr vm or result"); + return ANI_INVALID_ARGS; + } + ani_env* env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Unsupported ANI_VERSION_1"); + return ANI_OUT_OF_MEMORY; + } + + if (env == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "nullptr env"); + return ANI_NOT_FOUND; + } + + const char* className = "L@ohos/privacyManager/privacyManager/PrivacyManagerInner;"; + ani_class cls; + if (ANI_OK != env->FindClass(className, &cls)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Not found %{public}s", className); + return ANI_NOT_FOUND; + } + + std::array methods = { + ani_native_function { "addPermissionUsedRecordSync", + "ILstd/core/String;IIL@ohos/privacyManager/privacyManager/AddPermissionUsedRecordOptionsInner;:V", + reinterpret_cast(AddPermissionUsedRecord) }, + ani_native_function { "stopUsingPermissionExecute", + nullptr, + reinterpret_cast(StopUsingPermissionExecute) }, + ani_native_function { "startUsingPermissionExecute", + nullptr, + reinterpret_cast(StartUsingPermissionExecute) }, + }; + + if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Cannot bind native methods to %{public}s", className); + return ANI_ERROR; + }; + + static const char *name = "L@ohos/privacyManager/privacyManager;"; + ani_namespace ns; + if (ANI_OK != env->FindNamespace(name, &ns)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FindNamespace %{public}s failed.", name); + return ANI_ERROR; + } + + // namespace method input param without ani_object + std::array nsMethods = { + ani_native_function { "on", nullptr, reinterpret_cast(RegisterPermActiveStatusCallback) }, + ani_native_function { "off", nullptr, reinterpret_cast(UnRegisterPermActiveStatusCallback) }, + }; + + if (ANI_OK != env->Namespace_BindNativeFunctions(ns, nsMethods.data(), nsMethods.size())) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Namespace_BindNativeFunctions %{public}s failed.", name); + return ANI_ERROR; + }; + + *result = ANI_VERSION_1; + return ANI_OK; +} +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/privacy/src/permission_record_manager_napi.cpp b/frameworks/js/napi/privacy/src/permission_record_manager_napi.cpp index d5f55eb757c857318481da2482064ed82d191f51..931092d6d029be8f7a7bf4529a8de20548bc9e3f 100644 --- a/frameworks/js/napi/privacy/src/permission_record_manager_napi.cpp +++ b/frameworks/js/napi/privacy/src/permission_record_manager_napi.cpp @@ -949,7 +949,7 @@ static bool ParseInputToRegister(const napi_env env, const napi_callback_info cb std::sort(permList.begin(), permList.end()); // 2: the third parameter of argv if (!ParseCallback(env, argv[2], callback)) { - ParamResolveErrorThrow(env, "callback", "AsyncCallback"); + ParamResolveErrorThrow(env, "callback", "Callback"); return false; } registerPermActiveChangeContext.env = env; diff --git a/interfaces/innerkits/accesstoken/test/unittest/BUILD.gn b/interfaces/innerkits/accesstoken/test/unittest/BUILD.gn index 1808c7cde1dcf74a546af5b86da723c837cc7102..1727ef9f3394b47041c7ca9fc760caf7f07d9d2a 100755 --- a/interfaces/innerkits/accesstoken/test/unittest/BUILD.gn +++ b/interfaces/innerkits/accesstoken/test/unittest/BUILD.gn @@ -114,9 +114,6 @@ ohos_unittest("libaccesstoken_sdk_test") { "DlpTest/share_permission_with_sandbox_test.cpp", ] } - if (build_variant == "user") { - cflags_cc += [ "-DATM_BUILD_VARIANT_USER_ENABLE" ] - } } ohos_unittest("accesstoken_mock_test") { @@ -182,7 +179,4 @@ ohos_unittest("accesstoken_mock_test") { if (token_sync_enable == true) { cflags_cc += [ "-DTOKEN_SYNC_ENABLE" ] } - if (build_variant == "user") { - cflags_cc += [ "-DATM_BUILD_VARIANT_USER_ENABLE" ] - } } diff --git a/interfaces/innerkits/accesstoken/test/unittest/Coverage/accesstoken_kit_coverage_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/Coverage/accesstoken_kit_coverage_test.cpp index 1f1c76a04026ffa3af42ba262a4d44c4472dd265..0a225086dfcdb9cccc4358303c53253923fd4af8 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/Coverage/accesstoken_kit_coverage_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/Coverage/accesstoken_kit_coverage_test.cpp @@ -265,18 +265,18 @@ HWTEST_F(AccessTokenCoverageTest, VerifyAccessToken005, TestSize.Level1) // ret = PERMISSION_GRANTED + firstTokenID = 0 std::string permissionName = "ohos.permission.GET_BUNDLE_INFO"; firstTokenID = 0; - ASSERT_EQ(PermissionState::PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken( + EXPECT_EQ(PermissionState::PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken( callerTokenID, firstTokenID, permissionName, false)); firstTokenID = 1; // ret = PERMISSION_GRANTED + firstTokenID != 0 - ASSERT_EQ(PermissionState::PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken( + EXPECT_EQ(PermissionState::PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken( callerTokenID, firstTokenID, permissionName, false)); - TestCommon::DeleteTestHapToken(callerTokenID); + ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(callerTokenID)); callerTokenID = 0; // ret = PERMISSION_DENIED - ASSERT_EQ(PermissionState::PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken( + EXPECT_EQ(PermissionState::PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken( callerTokenID, firstTokenID, permissionName, false)); } diff --git a/interfaces/innerkits/accesstoken/test/unittest/DistributedTest/get_hap_token_info_from_remote_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/DistributedTest/get_hap_token_info_from_remote_test.cpp index a7a1826adbbf244666c05d19c018aafb11c2b295..fe3b10e1102412a1ae2e25c376b263f9003adec1 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/DistributedTest/get_hap_token_info_from_remote_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/DistributedTest/get_hap_token_info_from_remote_test.cpp @@ -155,19 +155,19 @@ HWTEST_F(GetHapTokenInfoFromRemoteTest, GetHapTokenInfoFromRemoteFuncTest001, Te HapTokenInfoForSync infoSync; int ret = AccessTokenKit::GetHapTokenInfoFromRemote(localTokenID, infoSync); - ASSERT_EQ(ret, RET_SUCCESS); - ASSERT_EQ(infoSync.permStateList.size(), static_cast(2)); + EXPECT_EQ(ret, RET_SUCCESS); + EXPECT_EQ(infoSync.permStateList.size(), static_cast(2)); - ASSERT_EQ(infoSync.permStateList[0].permissionName, g_infoManagerTestPolicyPrams.permStateList[0].permissionName); + EXPECT_EQ(infoSync.permStateList[0].permissionName, g_infoManagerTestPolicyPrams.permStateList[0].permissionName); - ASSERT_EQ(infoSync.permStateList[1].permissionName, g_infoManagerTestPolicyPrams.permStateList[1].permissionName); + EXPECT_EQ(infoSync.permStateList[1].permissionName, g_infoManagerTestPolicyPrams.permStateList[1].permissionName); - ASSERT_EQ(infoSync.baseInfo.bundleName, g_infoManagerTestInfoParms.bundleName); - ASSERT_EQ(infoSync.baseInfo.userID, g_infoManagerTestInfoParms.userID); - ASSERT_EQ(infoSync.baseInfo.instIndex, g_infoManagerTestInfoParms.instIndex); - ASSERT_EQ(infoSync.baseInfo.ver, 1); - ASSERT_EQ(infoSync.baseInfo.tokenID, localTokenID); - ASSERT_EQ(infoSync.baseInfo.tokenAttr, 0); + EXPECT_EQ(infoSync.baseInfo.bundleName, g_infoManagerTestInfoParms.bundleName); + EXPECT_EQ(infoSync.baseInfo.userID, g_infoManagerTestInfoParms.userID); + EXPECT_EQ(infoSync.baseInfo.instIndex, g_infoManagerTestInfoParms.instIndex); + EXPECT_EQ(infoSync.baseInfo.ver, 1); + EXPECT_EQ(infoSync.baseInfo.tokenID, localTokenID); + EXPECT_EQ(infoSync.baseInfo.tokenAttr, 0); EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(localTokenID)); } diff --git a/interfaces/innerkits/accesstoken/test/unittest/EdmPolicyTest/edm_policy_set_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/EdmPolicyTest/edm_policy_set_test.cpp index 3c9bfe92e870a66d342a3e7cec12a52129b24194..ef98b757da11949398740aae035cf29e5f2d0f0f 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/EdmPolicyTest/edm_policy_set_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/EdmPolicyTest/edm_policy_set_test.cpp @@ -269,7 +269,7 @@ HWTEST_F(EdmPolicySetTest, InitUserPolicy006, TestSize.Level1) std::vector permStatList; EXPECT_EQ(RET_SUCCESS, AccessTokenKit::GetReqPermissions(fullIdUser2.tokenIdExStruct.tokenID, permStatList, true)); - ASSERT_EQ(static_cast(2), permStatList.size()); + EXPECT_EQ(static_cast(2), permStatList.size()); EXPECT_EQ(INTERNET, permStatList[0].permissionName); EXPECT_EQ(PERMISSION_GRANTED, permStatList[0].grantStatus[0]); @@ -335,21 +335,15 @@ HWTEST_F(EdmPolicySetTest, UpdateUserPolicy004, TestSize.Level1) AccessTokenIDEx fullIdUser2; EXPECT_EQ(RET_SUCCESS, TestCommon::AllocTestHapToken(g_testHapInfoParams, g_testPolicyParams, fullIdUser2)); - g_testHapInfoParams.userID = MOCK_USER_ID_10003; - AccessTokenIDEx fullIdUser3; - EXPECT_EQ(RET_SUCCESS, - TestCommon::AllocTestHapToken(g_testHapInfoParams, g_testPolicyParams, fullIdUser3)); UserState user1 = {.userId = MOCK_USER_ID_10001, .isActive = false}; UserState user2 = {.userId = MOCK_USER_ID_10002, .isActive = true}; - UserState user3 = {.userId = MOCK_USER_ID_10003, .isActive = true}; - std::vector userListBefore = { user1, user2, user3 }; + std::vector userListBefore = { user1, user2 }; std::vector permList = { INTERNET, LOCATION }; int32_t ret = AccessTokenKit::InitUserPolicy(userListBefore, permList); EXPECT_EQ(ret, 0); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser1.tokenIdExStruct.tokenID, INTERNET), PERMISSION_DENIED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser2.tokenIdExStruct.tokenID, INTERNET), PERMISSION_GRANTED); - EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser3.tokenIdExStruct.tokenID, INTERNET), PERMISSION_GRANTED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser1.tokenIdExStruct.tokenID, LOCATION), PERMISSION_DENIED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser2.tokenIdExStruct.tokenID, LOCATION), @@ -363,7 +357,6 @@ HWTEST_F(EdmPolicySetTest, UpdateUserPolicy004, TestSize.Level1) EXPECT_EQ(ret, 0); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser1.tokenIdExStruct.tokenID, INTERNET), PERMISSION_GRANTED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser2.tokenIdExStruct.tokenID, INTERNET), PERMISSION_DENIED); - EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser3.tokenIdExStruct.tokenID, INTERNET), PERMISSION_GRANTED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser1.tokenIdExStruct.tokenID, LOCATION), PERMISSION_DENIED); EXPECT_EQ(AccessTokenKit::VerifyAccessToken(fullIdUser2.tokenIdExStruct.tokenID, LOCATION), @@ -371,7 +364,6 @@ HWTEST_F(EdmPolicySetTest, UpdateUserPolicy004, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(fullIdUser1.tokenIdExStruct.tokenID)); EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(fullIdUser2.tokenIdExStruct.tokenID)); - EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(fullIdUser3.tokenIdExStruct.tokenID)); int32_t res = AccessTokenKit::ClearUserPolicy(); EXPECT_EQ(res, 0); diff --git a/interfaces/innerkits/accesstoken/test/unittest/HapTokenTest/get_hap_token_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/HapTokenTest/get_hap_token_test.cpp index 91c471ad1e13840c38ceb54f42a34cfd0ef7f8c1..f91a414542ff126e2fe1002ba8898a0e071f0b20 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/HapTokenTest/get_hap_token_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/HapTokenTest/get_hap_token_test.cpp @@ -66,6 +66,7 @@ void GetHapTokenTest::TearDownTestCase() g_mock = nullptr; } SetSelfTokenID(g_selfTokenId); + TestCommon::ResetTestEvironment(); } void GetHapTokenTest::SetUp() @@ -183,10 +184,9 @@ HWTEST_F(GetHapTokenTest, GetHapTokenIDExFuncTest001, TestSize.Level1) ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); HapTokenInfo hapTokenInfoRes; AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; - int ret = AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes); - ASSERT_EQ(RET_SUCCESS, ret); - ASSERT_EQ(hapTokenInfoRes.bundleName, g_infoManagerTestSystemInfoParms.bundleName); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::GetHapTokenInfo(tokenID, hapTokenInfoRes)); + EXPECT_EQ(hapTokenInfoRes.bundleName, g_infoManagerTestSystemInfoParms.bundleName); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } /** @@ -311,18 +311,18 @@ HWTEST_F(GetHapTokenTest, IsSystemAppByFullTokenIDTest001, TestSize.Level1) ASSERT_EQ(true, TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); AccessTokenIDEx tokenIdEx1 = AccessTokenKit::GetHapTokenIDEx(1, "accesstoken_test", 0); - ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); + EXPECT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); UpdateHapInfoParams info; info.appIDDesc = g_infoManagerTestSystemInfoParms.appIDDesc; info.apiVersion = g_infoManagerTestSystemInfoParms.apiVersion; info.isSystemApp = false; - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UpdateHapToken(tokenIdEx, info, g_infoManagerTestPolicyPrams)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UpdateHapToken(tokenIdEx, info, g_infoManagerTestPolicyPrams)); tokenIdEx1 = AccessTokenKit::GetHapTokenIDEx(1, "accesstoken_test", 0); - ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); + EXPECT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); - ASSERT_EQ(false, TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(false, TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } /** @@ -335,20 +335,20 @@ HWTEST_F(GetHapTokenTest, IsSystemAppByFullTokenIDTest002, TestSize.Level1) { AccessTokenIDEx tokenIdEx = {0}; TestCommon::AllocTestHapToken(g_infoManagerTestSystemInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx); - ASSERT_TRUE(TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); + EXPECT_TRUE(TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); AccessTokenIDEx tokenIdEx1 = AccessTokenKit::GetHapTokenIDEx(1, "accesstoken_test", 0); - ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); + EXPECT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); UpdateHapInfoParams info; info.appIDDesc = g_infoManagerTestNormalInfoParms.appIDDesc; info.apiVersion = g_infoManagerTestNormalInfoParms.apiVersion; info.isSystemApp = true; - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UpdateHapToken(tokenIdEx, info, g_infoManagerTestPolicyPrams)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UpdateHapToken(tokenIdEx, info, g_infoManagerTestPolicyPrams)); tokenIdEx1 = AccessTokenKit::GetHapTokenIDEx(1, "accesstoken_test", 0); - ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); + EXPECT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); - ASSERT_EQ(true, TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(true, TokenIdKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } /** @@ -365,7 +365,7 @@ HWTEST_F(GetHapTokenTest, IsSystemAppByFullTokenIDTest003, TestSize.Level1) ASSERT_EQ(tokenIdEx.tokenIDEx, tokenIdEx1.tokenIDEx); bool res = AccessTokenKit::IsSystemAppByFullTokenID(tokenIdEx.tokenIDEx); ASSERT_TRUE(res); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermDenyTest/accesstoken_deny_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermDenyTest/accesstoken_deny_test.cpp index d1f8e22229eaf8209db4c7a022701273acba0206..a00807532dc1bf403948b28a903a5e35d8ebb8d3 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermDenyTest/accesstoken_deny_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermDenyTest/accesstoken_deny_test.cpp @@ -398,32 +398,19 @@ HWTEST_F(AccessTokenDenyTest, UnregisterPermStateChangeCallback001, TestSize.Lev scopeInfo.permList = {"ohos.permission.CAMERA"}; scopeInfo.tokenIDs = {}; auto callbackPtr = std::make_shared(scopeInfo); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(g_testTokenIDEx.tokenIDEx)); - ASSERT_EQ(AccessTokenError::ERR_PERMISSION_DENIED, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(AccessTokenError::ERR_PERMISSION_DENIED, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(tokenIdEx.tokenIDEx)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); setuid(g_selfUid); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } -#ifndef ATM_BUILD_VARIANT_USER_ENABLE -/** - * @tc.name: ReloadNativeTokenInfo001 - * @tc.desc: ReloadNativeTokenInfo with no permission - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(AccessTokenDenyTest, ReloadNativeTokenInfo001, TestSize.Level1) -{ - ASSERT_EQ(AccessTokenError::ERR_PERMISSION_DENIED, AccessTokenKit::ReloadNativeTokenInfo()); -} -#endif - /** * @tc.name: GetNativeTokenId001 * @tc.desc: Verify the GetNativeTokenId abnormal branch return nullptr proxy. diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/accesstoken_location_request_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/accesstoken_location_request_test.cpp index faaf9209ad2d3f08d9dd5d109554c56deffc679f..1c8547325e3d5fde349593a076a1ede9c8e3d44f 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/accesstoken_location_request_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/accesstoken_location_request_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1922 Huawei Device Co., Ltd. + * Copyright (c) 2025 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 @@ -210,7 +210,7 @@ HWTEST_F(AccessTokenLocationRequestTest, GetSelfPermissionsState001, TestSize.Le AccessTokenIDEx tokenIdEx = AllocHapToken(permissionStateFulls, BACKGROUND_LOCATION_API_VERSION); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenID); - ASSERT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); PermissionListState permVague1 = { .permissionName = "ohos.permission.APPROXIMATELY_LOCATION", @@ -222,9 +222,10 @@ HWTEST_F(AccessTokenLocationRequestTest, GetSelfPermissionsState001, TestSize.Le PermissionGrantInfo info; PermissionOper ret = AccessTokenKit::GetSelfPermissionsState(permsList1, info); - ASSERT_EQ(DYNAMIC_OPER, ret); - ASSERT_EQ(static_cast(1), permsList1.size()); - ASSERT_EQ(DYNAMIC_OPER, permsList1[0].state); + EXPECT_EQ(DYNAMIC_OPER, ret); + EXPECT_EQ(static_cast(1), permsList1.size()); + EXPECT_EQ(DYNAMIC_OPER, permsList1[0].state); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } /** diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/request_permission_on_setting_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/request_permission_on_setting_test.cpp index 4d022d65e94db9c8bd5a82202729a93456c839fb..cb3ecf6e7bbdfaaadf43b255c58d1e710a18c3bf 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/request_permission_on_setting_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/request_permission_on_setting_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1922 Huawei Device Co., Ltd. + * Copyright (c) 2025 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 @@ -121,21 +121,7 @@ HWTEST_F(RequestPermissionOnSettingTest, RequestAppPermOnSettingTest003, TestSiz ASSERT_NE(INVALID_TOKENID, tokenID); AccessTokenKit::RequestAppPermOnSetting(tokenID); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); -} - -/** - * @tc.name: RequestAppPermOnSettingTest004 - * @tc.desc: RequestAppPermOnSetting call function with self token. - * @tc.type: FUNC - * @tc.require: Issue Number - */ -HWTEST_F(RequestPermissionOnSettingTest, RequestAppPermOnSettingTest004, TestSize.Level0) -{ - std::vector reqPerm; - MockHapToken("RequestPermissionOnSettingTest", reqPerm, true); - - AccessTokenKit::RequestAppPermOnSetting(GetSelfTokenID()); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/set_perm_dialog_cap_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/set_perm_dialog_cap_test.cpp index 3d6bab78ea08f30334c159604fc5322baaafc774..1f99e9ec12c9e913acab94c9f13dc6d613a78928 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/set_perm_dialog_cap_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermisionDialogTest/set_perm_dialog_cap_test.cpp @@ -132,19 +132,19 @@ HWTEST_F(SetPermDialogCapTest, SetPermDialogCapFuncTest001, TestSize.Level1) permsList.emplace_back(tmp); // test dialog is forbiddedn - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::SetPermDialogCap(hapBaseInfo, true)); - ASSERT_EQ(RET_SUCCESS, SetSelfTokenID(tokenIdEx.tokenIDEx)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::SetPermDialogCap(hapBaseInfo, true)); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(tokenIdEx.tokenIDEx)); PermissionGrantInfo info; - ASSERT_EQ(FORBIDDEN_OPER, AccessTokenKit::GetSelfPermissionsState(permsList, info)); - ASSERT_EQ(RET_SUCCESS, SetSelfTokenID(selfToken)); + EXPECT_EQ(FORBIDDEN_OPER, AccessTokenKit::GetSelfPermissionsState(permsList, info)); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(selfToken)); // test dialog is not forbiddedn - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::SetPermDialogCap(hapBaseInfo, false)); - ASSERT_EQ(RET_SUCCESS, SetSelfTokenID(tokenIdEx.tokenIDEx)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::SetPermDialogCap(hapBaseInfo, false)); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(tokenIdEx.tokenIDEx)); ASSERT_NE(FORBIDDEN_OPER, AccessTokenKit::GetSelfPermissionsState(permsList, info)); - ASSERT_EQ(RET_SUCCESS, SetSelfTokenID(selfToken)); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(selfToken)); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/get_permission_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/get_permission_test.cpp index 69aa3bb99bc01e1dcf641daf73b585fd51fd599f..c26dc67330b2190a222c669d33a001b3c11eaf08 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/get_permission_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/get_permission_test.cpp @@ -110,17 +110,11 @@ HWTEST_F(GetPermissionTest, GetPermissionUsedTypeAbnormalTest001, TestSize.Level { LOGI(ATM_DOMAIN, ATM_TAG, "GetPermissionUsedTypeAbnormalTest001"); std::string permisson = "ohos.permission.CAMERA"; -#ifndef ATM_BUILD_VARIANT_USER_ENABLE // caller is not native, IsPrivilegedCalling return false(uid != accesstoken_uid) int32_t selfUid = getuid(); setuid(1); EXPECT_EQ(PermUsedTypeEnum::INVALID_USED_TYPE, AccessTokenKit::GetPermissionUsedType(g_selfTokenId, permisson)); setuid(selfUid); -#else - // caller is not native, IsPrivilegedCalling return false - EXPECT_EQ(PermUsedTypeEnum::INVALID_USED_TYPE, - AccessTokenKit::GetPermissionUsedType(g_selfTokenId, permisson)); -#endif } /** @@ -468,57 +462,6 @@ HWTEST_F(GetPermissionTest, ReloadNativeTokenInfo001, TestSize.Level1) ASSERT_EQ(RET_SUCCESS, ret); } -#ifndef ATM_BUILD_VARIANT_USER_ENABLE -uint64_t GetNativeTokenTest(const char *processName, const char **perms, int32_t permNum) -{ - uint64_t tokenId; - NativeTokenInfoParams infoInstance = { - .dcapsNum = 0, - .permsNum = permNum, - .aclsNum = 0, - .dcaps = nullptr, - .perms = perms, - .acls = nullptr, - .aplStr = "system_core", - .processName = processName, - }; - - tokenId = GetAccessTokenId(&infoInstance); - AccessTokenKit::ReloadNativeTokenInfo(); - return tokenId; -} - -/** - * @tc.name: ReloadNativeTokenInfo002 - * @tc.desc: ReloadNativeTokenInfo with same bundlename twicely. - * @tc.type: FUNC - * @tc.require: Issue Number - */ -HWTEST_F(GetPermissionTest, ReloadNativeTokenInfo002, TestSize.Level1) -{ - const char **perms = new const char *[1]; - perms[0] = "ohos.permission.MANAGE_HAP_TOKENID"; - uint64_t token1 = GetNativeTokenTest("TestCase_core", perms, 1); - ASSERT_NE(INVALID_TOKENID, token1); - ASSERT_EQ( - PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(token1, "ohos.permission.MANAGE_HAP_TOKENID", false)); - - uint64_t token2 = GetNativeTokenTest("TestCase_core", nullptr, 0); - ASSERT_NE(INVALID_TOKENID, token2); - - ASSERT_EQ(token1, token2); - ASSERT_EQ( - PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken(token2, "ohos.permission.MANAGE_HAP_TOKENID", false)); - - uint64_t token3 = GetNativeTokenTest("TestCase_core", perms, 1); - ASSERT_NE(INVALID_TOKENID, token3); - - ASSERT_EQ(token1, token3); - ASSERT_EQ( - PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(token3, "ohos.permission.MANAGE_HAP_TOKENID", false)); -} -#endif - /** * @tc.name: GetKernelPermissionTest001 * @tc.desc: diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_for_specified_time_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_for_specified_time_test.cpp index 892426db406c8899f9d5bc8653709733ea8522be..c88a7bc8a42544cc86f4e1739b810ea8e860530f 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_for_specified_time_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_for_specified_time_test.cpp @@ -154,8 +154,10 @@ HWTEST_F(GrantPermissionForSpecifiedTimeTest, GrantPermissionForSpecifiedTimeAbn ASSERT_NE(INVALID_TOKENID, tokenID); uint32_t onceTime = 10; // 10: 10s - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, AccessTokenKit::GrantPermissionForSpecifiedTime(tokenID, SHORT_TEMP_PERMISSION, onceTime)); + + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } /** diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_test.cpp index 3c5538bef7124c65c7c5da3e844db254d27a8fbf..2f2bc01abbd922bec718b2da36702dcd442d0079 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/grant_permission_test.cpp @@ -40,6 +40,7 @@ static const unsigned int TEST_TOKENID_INVALID = 0; static const int CYCLE_TIMES = 100; static const int TEST_USER_ID = 0; static constexpr int32_t DEFAULT_API_VERSION = 8; +static MockHapToken* g_mock = nullptr; }; void GrantPermissionTest::SetUpTestCase() @@ -47,6 +48,11 @@ void GrantPermissionTest::SetUpTestCase() g_selfTokenId = GetSelfTokenID(); TestCommon::SetTestEvironment(g_selfTokenId); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); + reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); + g_mock = new (std::nothrow) MockHapToken("GrantPermissionTest", reqPerm); + // clean up test cases AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -55,6 +61,10 @@ void GrantPermissionTest::SetUpTestCase() void GrantPermissionTest::TearDownTestCase() { + if (g_mock != nullptr) { + delete g_mock; + g_mock = nullptr; + } AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; TestCommon::DeleteTestHapToken(tokenID); @@ -118,9 +128,6 @@ void GrantPermissionTest::TearDown() HWTEST_F(GrantPermissionTest, GrantPermissionFuncTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "GrantPermissionFuncTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - MockHapToken mock("GrantPermissionFuncTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -149,9 +156,6 @@ HWTEST_F(GrantPermissionTest, GrantPermissionFuncTest001, TestSize.Level0) HWTEST_F(GrantPermissionTest, GrantPermissionAbnormalTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "GrantPermissionAbnormalTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - MockHapToken mock("GrantPermissionAbnormalTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -185,9 +189,6 @@ HWTEST_F(GrantPermissionTest, GrantPermissionAbnormalTest001, TestSize.Level0) HWTEST_F(GrantPermissionTest, GrantPermissionAbnormalTest002, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "GrantPermissionAbnormalTest002"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - MockHapToken mock("GrantPermissionAbnormalTest002", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -208,9 +209,6 @@ HWTEST_F(GrantPermissionTest, GrantPermissionAbnormalTest002, TestSize.Level0) HWTEST_F(GrantPermissionTest, GrantPermissionSpecsTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "GrantPermissionSpecsTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - MockHapToken mock("GrantPermissionSpecsTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -261,9 +259,6 @@ HWTEST_F(GrantPermissionTest, GrantPermissionSpecsTest002, TestSize.Level0) HWTEST_F(GrantPermissionTest, GrantPermissionSpecsTest003, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "GrantPermissionSpecsTest003"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - MockHapToken mock("GrantPermissionSpecsTest003", reqPerm, true); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -275,36 +270,6 @@ HWTEST_F(GrantPermissionTest, GrantPermissionSpecsTest003, TestSize.Level0) ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } - -/** - * @tc.name: GrantPermissionSpecsTest004 - * @tc.desc: success to revoke permission when granting permission twice by secure component. - * @tc.type: FUNC - * @tc.require: issueI66BH3 - */ -HWTEST_F(GrantPermissionTest, GrantPermissionSpecsTest004, TestSize.Level0) -{ - std::vector reqPerm; - MockHapToken mock("GrantPermissionSpecsTest004", reqPerm, true); - - AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); - AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; - int ret = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.SECURE_PASTE", PERMISSION_COMPONENT_SET); - ASSERT_EQ(RET_SUCCESS, ret); - ret = AccessTokenKit::GrantPermission(tokenID, "ohos.permission.SECURE_PASTE", PERMISSION_COMPONENT_SET); - ASSERT_EQ(RET_SUCCESS, ret); - - ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.SECURE_PASTE", false); - ASSERT_EQ(PERMISSION_GRANTED, ret); - - ret = AccessTokenKit::RevokePermission(tokenID, "ohos.permission.SECURE_PASTE", PERMISSION_COMPONENT_SET); - ASSERT_EQ(RET_SUCCESS, ret); - - ret = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.SECURE_PASTE", false); - ASSERT_EQ(PERMISSION_DENIED, ret); - - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); -} } // namespace AccessToken } // namespace Security } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/revoke_permission_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/revoke_permission_test.cpp index de702225e79e36b2033ae7008753dccbeb8c17c0..bb24a2e784e5b4686d005ddd30bc19d1a8e131c4 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/revoke_permission_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/PermissionsTest/revoke_permission_test.cpp @@ -40,6 +40,7 @@ static const unsigned int TEST_TOKENID_INVALID = 0; static const int CYCLE_TIMES = 100; static const int TEST_USER_ID = 0; static constexpr int32_t DEFAULT_API_VERSION = 8; +static MockHapToken* g_mock = nullptr; }; void RevokePermissionTest::SetUpTestCase() @@ -47,6 +48,10 @@ void RevokePermissionTest::SetUpTestCase() g_selfTokenId = GetSelfTokenID(); TestCommon::SetTestEvironment(g_selfTokenId); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); + g_mock = new (std::nothrow) MockHapToken("RevokePermissionTest", reqPerm); + // clean up test cases AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -55,6 +60,11 @@ void RevokePermissionTest::SetUpTestCase() void RevokePermissionTest::TearDownTestCase() { + if (g_mock != nullptr) { + delete g_mock; + g_mock = nullptr; + } + AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; TestCommon::DeleteTestHapToken(tokenID); @@ -119,9 +129,6 @@ void RevokePermissionTest::TearDown() HWTEST_F(RevokePermissionTest, RevokePermissionFuncTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionFuncTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionFuncTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -150,9 +157,6 @@ HWTEST_F(RevokePermissionTest, RevokePermissionFuncTest001, TestSize.Level0) HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionAbnormalTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionAbnormalTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -173,9 +177,6 @@ HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest001, TestSize.Level0) HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest002, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionAbnormalTest002"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionAbnormalTest002", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -206,9 +207,6 @@ HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest002, TestSize.Level0) HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest003, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionAbnormalTest003"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionAbnormalTest003", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -230,9 +228,6 @@ HWTEST_F(RevokePermissionTest, RevokePermissionAbnormalTest003, TestSize.Level0) HWTEST_F(RevokePermissionTest, RevokePermissionSpecsTest001, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionSpecsTest001"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionSpecsTest001", reqPerm); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; @@ -284,9 +279,6 @@ HWTEST_F(RevokePermissionTest, RevokePermissionSpecsTest002, TestSize.Level0) HWTEST_F(RevokePermissionTest, RevokePermissionSpecsTest003, TestSize.Level0) { LOGI(ATM_DOMAIN, ATM_TAG, "RevokePermissionSpecsTest003"); - std::vector reqPerm; - reqPerm.emplace_back("ohos.permission.REVOKE_SENSITIVE_PERMISSIONS"); - MockHapToken mock("RevokePermissionSpecsTest003", reqPerm, true); AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(TEST_USER_ID, TEST_BUNDLE_NAME, 0); AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; diff --git a/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/register_perm_state_change_callback_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/register_perm_state_change_callback_test.cpp index 0e1383786f4d58ab9fcd9e9eb4e2b1e19add6061..1f13e450f37f54a8e02d545504c0c9a2e77d0229 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/register_perm_state_change_callback_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/register_perm_state_change_callback_test.cpp @@ -128,33 +128,33 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackFun AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(tokenID, INVALID_TOKENID); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); - ASSERT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); + EXPECT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } /** @@ -201,17 +201,17 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackFun ASSERT_NE(tokenID, INVALID_TOKENID); res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false); - ASSERT_EQ(PERMISSION_DENIED, res); + EXPECT_EQ(PERMISSION_DENIED, res); res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); } /** @@ -244,14 +244,14 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackFun ASSERT_NE(tokenID, INVALID_TOKENID); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); - ASSERT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); } /** @@ -282,17 +282,17 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackFun auto callbackPtr = std::make_shared(scopeInfo); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); callbackPtr->ready_ = false; - ASSERT_EQ(PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); } @@ -378,13 +378,13 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackAbn ASSERT_NE(tokenID, INVALID_TOKENID); callbackPtr->ready_ = false; - ASSERT_EQ(PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); - ASSERT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); + EXPECT_EQ(PERMISSION_DENIED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(PERMISSION_GRANTED, AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } /** @@ -423,17 +423,17 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackAbn scopeInfo.tokenIDs = {tokenIdEx.tokenIdExStruct.tokenID}; scopeInfo.permList = {"ohos.permission.INVALID", "ohos.permission.CAMERA"}; auto callbackPtr = std::make_shared(scopeInfo); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr)); int32_t res = TestCommon::GrantPermissionByTest(tokenIdEx.tokenIdExStruct.tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); } /** @@ -505,16 +505,16 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackSpe scopeInfo.tokenIDs.emplace_back(tokenIdEx.tokenIdExStruct.tokenID); if (i == TOKENIDS_LIST_SIZE_MAX_TEST) { auto callbackPtr1 = std::make_shared(scopeInfo); - ASSERT_EQ( + EXPECT_EQ( AccessTokenError::ERR_PARAM_INVALID, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr1)); break; } auto callbackPtr1 = std::make_shared(scopeInfo); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr1)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr1)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr1)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr1)); } - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); } /** @@ -575,7 +575,7 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackSpe scopeInfo.permList = {"ohos.permission.CAMERA"}; auto callbackPtr = std::make_shared(scopeInfo); int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = TestCommon::GrantPermissionByTest(tokenIdEx.tokenIdExStruct.tokenID, "ohos.permission.CAMERA", 2); EXPECT_EQ(RET_SUCCESS, res); @@ -599,11 +599,11 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackSpe EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr)); } /** @@ -638,7 +638,7 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackSpe scopeInfo.permList = {"ohos.permission.READ_MEDIA"}; auto callbackPtr = std::make_shared(scopeInfo); int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = TestCommon::GrantPermissionByTest(tokenIdEx.tokenIdExStruct.tokenID, "ohos.permission.READ_MEDIA", PERMISSION_SYSTEM_FIXED); @@ -657,12 +657,12 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterPermStateChangeCallbackSpe EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); } /** @@ -692,27 +692,27 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false); - ASSERT_EQ(PERMISSION_GRANTED, res); + EXPECT_EQ(PERMISSION_GRANTED, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); SetSelfTokenID(tokenID); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); @@ -744,23 +744,23 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac callbackPtr->ready_ = false; SetSelfTokenID(tokenID); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); SetSelfTokenID(g_selfShellTokenId); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; SetSelfTokenID(tokenID); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); SetSelfTokenID(g_selfShellTokenId); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); @@ -793,27 +793,27 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false); - ASSERT_EQ(PERMISSION_GRANTED, res); + EXPECT_EQ(PERMISSION_GRANTED, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); SetSelfTokenID(tokenID); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID)); @@ -852,30 +852,30 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac callbackPtr->ready_ = false; SetSelfTokenID(tokenID); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); SetSelfTokenID(g_selfShellTokenId); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.MICROPHONE", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.MICROPHONE", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.MICROPHONE", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.MICROPHONE", 2)); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); SetSelfTokenID(tokenID); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -913,32 +913,32 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr1); - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); scopeInfo.permList = {"ohos.permission.INVALID", "ohos.permission.CAMERA"}; auto callbackPtr = std::make_shared(scopeInfo); res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::VerifyAccessToken(tokenID, "ohos.permission.CAMERA", false); - ASSERT_EQ(PERMISSION_GRANTED, res); + EXPECT_EQ(PERMISSION_GRANTED, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s EXPECT_EQ(true, callbackPtr->ready_); SetSelfTokenID(tokenID); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -979,12 +979,12 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac if (i == PERMS_LIST_SIZE_MAX_TEST) { // 1025 is a invalid size auto callbackPtr = std::make_shared(scopeInfo); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); break; } auto callbackPtr = std::make_shared(scopeInfo); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); } ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -1016,7 +1016,7 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac callbackPtr->ready_ = false; int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -1061,7 +1061,7 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac // tokenIDs size si 0, int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr1); - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); scopeInfo.tokenIDs = {tokenID, tokenID2}; auto callbackPtr = std::make_shared(scopeInfo); @@ -1069,11 +1069,11 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac // tokenIDs size != 1 res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); + EXPECT_EQ(AccessTokenError::ERR_PARAM_INVALID, res); SetSelfTokenID(g_selfShellTokenId); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); - ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); + EXPECT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID2)); } /** @@ -1106,11 +1106,11 @@ HWTEST_F(RegisterPermStateChangeCallbackTest, RegisterSelfPermStateChangeCallbac if (i == MAX_CALLBACK_MAP_SIZE) { // 200 is the max size auto callbackPtr = std::make_shared(scopeInfo); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_CALLBACKS_EXCEED_LIMITATION, res); + EXPECT_EQ(AccessTokenError::ERR_CALLBACKS_EXCEED_LIMITATION, res); break; } auto callbackPtr = std::make_shared(scopeInfo); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); callbackList.emplace_back(callbackPtr); } for (int32_t i = 0; i < MAX_CALLBACK_MAP_SIZE; i++) { // release 200 callback diff --git a/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/un_register_perm_state_change_callback_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/un_register_perm_state_change_callback_test.cpp index d3338ef368881f63e0b81766a2249fa60e8e5313..0331e7b96ddb5ac2ba1627d1b53b445520e375dc 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/un_register_perm_state_change_callback_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/RegisterCallbackTest/un_register_perm_state_change_callback_test.cpp @@ -198,7 +198,7 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_INTERFACE_NOT_USED_TOGETHER, res); + EXPECT_EQ(AccessTokenError::ERR_INTERFACE_NOT_USED_TOGETHER, res); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); SetSelfTokenID(g_selfShellTokenId); @@ -238,13 +238,13 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_CALLBACK_ALREADY_EXIST, res); + EXPECT_EQ(AccessTokenError::ERR_CALLBACK_ALREADY_EXIST, res); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(AccessTokenError::ERR_INTERFACE_NOT_USED_TOGETHER, res); + EXPECT_EQ(AccessTokenError::ERR_INTERFACE_NOT_USED_TOGETHER, res); SetSelfTokenID(g_selfShellTokenId); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); @@ -284,25 +284,25 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); callbackPtr->ready_ = false; res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -348,25 +348,25 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); callbackPtr->ready_ = false; res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -405,27 +405,27 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); SetSelfTokenID(tokenID); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); callbackPtr->ready_ = false; res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -470,28 +470,28 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal callbackPtr->ready_ = false; SetSelfTokenID(tokenID); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr)); - ASSERT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); + EXPECT_EQ(RET_SUCCESS, AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr)); SetSelfTokenID(g_selfShellTokenId); callbackPtr->ready_ = false; - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.DISTRIBUTED_DATASYNC", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.DISTRIBUTED_DATASYNC", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); - ASSERT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.DISTRIBUTED_DATASYNC", 2)); + EXPECT_EQ(RET_SUCCESS, TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.DISTRIBUTED_DATASYNC", 2)); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } @@ -530,25 +530,25 @@ HWTEST_F(UnRegisterPermStateChangeCallbackTest, UnRegisterSelfPermStateChangeCal SetSelfTokenID(tokenID); int32_t res = AccessTokenKit::RegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); res = AccessTokenKit::UnRegisterSelfPermStateChangeCallback(callbackPtr); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); SetSelfTokenID(g_selfShellTokenId); callbackPtr->ready_ = false; res = TestCommon::GrantPermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); callbackPtr->ready_ = false; res = TestCommon::RevokePermissionByTest(tokenID, "ohos.permission.CAMERA", 2); - ASSERT_EQ(RET_SUCCESS, res); + EXPECT_EQ(RET_SUCCESS, res); usleep(500000); // 500000us = 0.5s - ASSERT_EQ(false, callbackPtr->ready_); + EXPECT_EQ(false, callbackPtr->ready_); ASSERT_EQ(RET_SUCCESS, TestCommon::DeleteTestHapToken(tokenID)); } diff --git a/interfaces/innerkits/accesstoken/test/unittest/SaTest/dump_token_info_test.cpp b/interfaces/innerkits/accesstoken/test/unittest/SaTest/dump_token_info_test.cpp index 7a32f46603fa2a0061f498829a2f04d236bac080..83424dac680dacecb3773b0f4cd39bc187d6c9b3 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/SaTest/dump_token_info_test.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/SaTest/dump_token_info_test.cpp @@ -98,7 +98,7 @@ HWTEST_F(DumpTokenInfoTest, DumpTokenInfoAbnormalTest001, TestSize.Level1) AtmToolsParamInfo info; info.tokenId = 123; AccessTokenKit::DumpTokenInfo(info, dumpInfo); - ASSERT_EQ("", dumpInfo); + EXPECT_EQ("", dumpInfo); setuid(g_selfUid); EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); diff --git a/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp b/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp index 93f0d22d4b9242a798b4025900195104f026e88c..bd50abdada05f3bacaf3e535c231befc74b9514d 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp +++ b/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp @@ -336,25 +336,6 @@ int32_t TestCommon::RevokePermissionByTest(AccessTokenID tokenID, const std::str return AccessTokenKit::RevokePermission(tokenID, permission, flag); } -uint64_t TestCommon::GetNativeToken(const char *processName, const char **perms, int32_t permNum) -{ - uint64_t tokenId; - NativeTokenInfoParams infoInstance = { - .dcapsNum = 0, - .permsNum = permNum, - .aclsNum = 0, - .dcaps = nullptr, - .perms = perms, - .acls = nullptr, - .aplStr = "system_core", - .processName = processName, - }; - - tokenId = GetAccessTokenId(&infoInstance); - AccessTokenKit::ReloadNativeTokenInfo(); - return tokenId; -} - AccessTokenID TestCommon::GetNativeTokenIdFromProcess(const std::string &process) { uint64_t selfTokenId = GetSelfTokenID(); diff --git a/interfaces/innerkits/accesstoken/test/unittest/common/test_common.h b/interfaces/innerkits/accesstoken/test/unittest/common/test_common.h index f58fb6bb4ed215132e89cd6e23bd12d69f7b3191..56d814aad4540a5b8d2782607ba36208ad671447 100644 --- a/interfaces/innerkits/accesstoken/test/unittest/common/test_common.h +++ b/interfaces/innerkits/accesstoken/test/unittest/common/test_common.h @@ -66,8 +66,6 @@ public: HapPolicyParams& hapPolicy, AccessTokenIDEx& tokenIdEx); static AccessTokenIDEx AllocAndGrantHapTokenByTest(const HapInfoParams& info, HapPolicyParams& policy); static int32_t DeleteTestHapToken(AccessTokenID tokenID); - static void GetNativeTokenTest(); - static uint64_t GetNativeToken(const char* processName, const char** perms, int32_t permNum); static AccessTokenID GetNativeTokenIdFromProcess(const std::string& process); static AccessTokenIDEx GetHapTokenIdFromBundle( int32_t userID, const std::string& bundleName, int32_t instIndex); diff --git a/interfaces/innerkits/privacy/test/BUILD.gn b/interfaces/innerkits/privacy/test/BUILD.gn index e4a1974aea7fe9fedf8791b674b0067eae817fc7..5619b3333f721b04222daba133211688f3e53cd5 100644 --- a/interfaces/innerkits/privacy/test/BUILD.gn +++ b/interfaces/innerkits/privacy/test/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("libprivacy_sdk_test") { "mock/src/app_manager_access_client.cpp", "unittest/src/permission_deny_test.cpp", "unittest/src/privacy_kit_test.cpp", + "unittest/src/privacy_test_common.cpp", ] cflags_cc = [ "-DHILOG_ENABLE" ] diff --git a/interfaces/innerkits/privacy/test/unittest/src/permission_deny_test.cpp b/interfaces/innerkits/privacy/test/unittest/src/permission_deny_test.cpp index ba30b8a57322b87e1a164180930bc2722e3ab1ce..82ac32a39626d93680d5a141c41e3732182b2cc4 100644 --- a/interfaces/innerkits/privacy/test/unittest/src/permission_deny_test.cpp +++ b/interfaces/innerkits/privacy/test/unittest/src/permission_deny_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -18,6 +18,7 @@ #include "on_permission_used_record_callback_stub.h" #include "privacy_kit.h" #include "privacy_error.h" +#include "privacy_test_common.h" #include "token_setproc.h" namespace OHOS { @@ -47,15 +48,17 @@ using namespace testing::ext; void PermDenyTest::SetUpTestCase() { g_selfTokenId = GetSelfTokenID(); + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); } void PermDenyTest::TearDownTestCase() { + PrivacyTestCommon::ResetTestEvironment(); } void PermDenyTest::SetUp() { - AccessTokenIDEx tokenIDEx = AccessTokenKit::AllocHapToken(g_InfoParms, g_PolicyPrams); + AccessTokenIDEx tokenIDEx = PrivacyTestCommon::AllocTestHapToken(g_InfoParms, g_PolicyPrams); g_FullTokenId = tokenIDEx.tokenIDEx; g_testTokenId = tokenIDEx.tokenIdExStruct.tokenID; @@ -65,8 +68,13 @@ void PermDenyTest::SetUp() void PermDenyTest::TearDown() { EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); - AccessTokenKit::DeleteToken(g_testTokenId); - PrivacyKit::RemovePermissionUsedRecords(g_testTokenId); + PrivacyTestCommon::DeleteTestHapToken(g_testTokenId); + { + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("PermDenyTest", reqPerm, true); + PrivacyKit::RemovePermissionUsedRecords(g_testTokenId); + } } /** 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 48dbb606c6408e486e4ecd12320c440c7ef1ec4b..3cbaca3742b5dd4c0d7f0f77cde937e2733dfebf 100644 --- a/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp +++ b/interfaces/innerkits/privacy/test/unittest/src/privacy_kit_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -37,6 +37,7 @@ #include "perm_setproc.h" #include "privacy_error.h" #include "privacy_kit.h" +#include "privacy_test_common.h" #include "state_change_callback_stub.h" #include "string_ex.h" #include "token_setproc.h" @@ -46,8 +47,8 @@ using namespace OHOS::Security::AccessToken; const static int32_t RET_NO_ERROR = 0; static const uint32_t ACCESS_TOKEN_UID = 3020; -static constexpr int32_t DEFAULT_API_VERSION = 8; static AccessTokenID g_nativeToken = 0; +static MockHapToken* g_mock = nullptr; #ifdef AUDIO_FRAMEWORK_ENABLE static bool g_isMicMute = false; #endif @@ -122,13 +123,6 @@ static HapPolicyParams g_policyPramsC = { .permStateList = {g_infoManagerTestStateC} }; -static PermissionStateFull g_infoManagerTestStateD = { - .permissionName = "ohos.permission.MICROPHONE_BACKGROUND", - .isGeneral = true, - .resDeviceID = {"localC"}, - .grantStatus = {PermissionState::PERMISSION_GRANTED}, - .grantFlags = {1} -}; static HapInfoParams g_infoParmsD = { .userID = 1, .bundleName = "ohos.privacy_test.bundleD", @@ -200,88 +194,59 @@ static BundleUsedRecord g_bundleUsedRecord = { .bundleName = "com.ohos.test", }; -static HapInfoParams g_normalInfoParms = { - .userID = 1, - .bundleName = "accesstoken_test", - .instIndex = 0, - .appIDDesc = "testtesttesttest", - .apiVersion = DEFAULT_API_VERSION, - .isSystemApp = false -}; -static HapInfoParams g_systemInfoParms = { - .userID = 1, - .bundleName = "accesstoken_test", - .instIndex = 0, - .appIDDesc = "testtesttesttest", - .apiVersion = DEFAULT_API_VERSION, - .isSystemApp = true -}; - static AccessTokenID g_selfTokenId = 0; static AccessTokenID g_tokenIdA = 0; static AccessTokenID g_tokenIdB = 0; -static AccessTokenIDEx g_tokenIdC = {0}; +static AccessTokenID g_tokenIdC = 0; static AccessTokenID g_tokenIdE = 0; static AccessTokenID g_tokenIdF = 0; static AccessTokenID g_tokenIdG = 0; static void DeleteTestToken() { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsA.userID, - g_infoParmsA.bundleName, - g_infoParmsA.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsB.userID, - g_infoParmsB.bundleName, - g_infoParmsB.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsC.userID, - g_infoParmsC.bundleName, - g_infoParmsC.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsE.userID, - g_infoParmsE.bundleName, - g_infoParmsE.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsF.userID, - g_infoParmsF.bundleName, - g_infoParmsF.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_infoParmsG.userID, - g_infoParmsG.bundleName, - g_infoParmsG.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_normalInfoParms.userID, - g_normalInfoParms.bundleName, - g_normalInfoParms.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - - tokenId = AccessTokenKit::GetHapTokenID(g_systemInfoParms.userID, - g_systemInfoParms.bundleName, - g_systemInfoParms.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsA.userID, g_infoParmsA.bundleName, g_infoParmsA.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsB.userID, g_infoParmsB.bundleName, g_infoParmsB.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsC.userID, g_infoParmsC.bundleName, g_infoParmsC.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsE.userID, g_infoParmsE.bundleName, g_infoParmsE.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsF.userID, g_infoParmsF.bundleName, g_infoParmsF.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_infoParmsG.userID, g_infoParmsG.bundleName, g_infoParmsG.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); } void PrivacyKitTest::SetUpTestCase() { - DeleteTestToken(); g_selfTokenId = GetSelfTokenID(); - g_nativeToken = AccessTokenKit::GetNativeTokenId("privacy_service"); - + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); + + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + g_mock = new (std::nothrow) MockHapToken("PrivacyKitTest", reqPerm, true); + + g_nativeToken = PrivacyTestCommon::GetNativeTokenIdFromProcess("privacy_service"); + + DeleteTestToken(); #ifdef AUDIO_FRAMEWORK_ENABLE auto audioGroupManager = OHOS::AudioStandard::AudioSystemManager::GetInstance()->GetGroupManager( OHOS::AudioStandard::DEFAULT_VOLUME_GROUP_ID); @@ -293,6 +258,12 @@ void PrivacyKitTest::SetUpTestCase() void PrivacyKitTest::TearDownTestCase() { + if (g_mock != nullptr) { + delete g_mock; + g_mock = nullptr; + } + SetSelfTokenID(g_selfTokenId); + PrivacyTestCommon::ResetTestEvironment(); } void PrivacyKitTest::SetUp() @@ -304,19 +275,30 @@ void PrivacyKitTest::SetUp() audioGroupManager->SetMicrophoneMutePersistent(false, OHOS::AudioStandard::PolicyType::PRIVACY_POLCIY_TYPE); } #endif - AccessTokenKit::AllocHapToken(g_infoParmsA, g_policyPramsA); - AccessTokenKit::AllocHapToken(g_infoParmsB, g_policyPramsB); - AccessTokenKit::AllocHapToken(g_infoParmsC, g_policyPramsC); - AccessTokenKit::AllocHapToken(g_infoParmsE, g_policyPramsE); - AccessTokenKit::AllocHapToken(g_infoParmsF, g_policyPramsF); - AccessTokenKit::AllocHapToken(g_infoParmsG, g_policyPramsG); + AccessTokenIDEx tokenIdEx = {0}; + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsA, g_policyPramsA); + g_tokenIdA = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdA); + + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsB, g_policyPramsB); + g_tokenIdB = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdB); + + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsC, g_policyPramsC); + g_tokenIdC = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdC); + + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsE, g_policyPramsE); + g_tokenIdE = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdE); - g_tokenIdA = AccessTokenKit::GetHapTokenID(g_infoParmsA.userID, g_infoParmsA.bundleName, g_infoParmsA.instIndex); - g_tokenIdB = AccessTokenKit::GetHapTokenID(g_infoParmsB.userID, g_infoParmsB.bundleName, g_infoParmsB.instIndex); - g_tokenIdC = AccessTokenKit::GetHapTokenIDEx(g_infoParmsC.userID, g_infoParmsC.bundleName, g_infoParmsC.instIndex); - g_tokenIdE = AccessTokenKit::GetHapTokenID(g_infoParmsE.userID, g_infoParmsE.bundleName, g_infoParmsE.instIndex); - g_tokenIdF = AccessTokenKit::GetHapTokenID(g_infoParmsF.userID, g_infoParmsF.bundleName, g_infoParmsF.instIndex); - g_tokenIdG = AccessTokenKit::GetHapTokenID(g_infoParmsG.userID, g_infoParmsG.bundleName, g_infoParmsG.instIndex); + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsF, g_policyPramsF); + g_tokenIdF = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdF); + + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_infoParmsG, g_policyPramsG); + g_tokenIdG = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, g_tokenIdG); } void PrivacyKitTest::TearDown() @@ -329,7 +311,6 @@ void PrivacyKitTest::TearDown() OHOS::AudioStandard::PolicyType::PRIVACY_POLCIY_TYPE); } #endif - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); DeleteTestToken(); } @@ -601,17 +582,16 @@ HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord006, TestSize.Level1) } /** - * @tc.name: AddPermissionUsedRecord008 + * @tc.name: AddPermissionUsedRecord007 * @tc.desc: AddPermissionUsedRecord caller is normal app. * @tc.type: FUNC * @tc.require: issueI66BH3 */ -HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord008, TestSize.Level1) +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord007, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("AddPermissionUsedRecord007", reqPerm, false); AddPermParamInfo info; info.tokenId = g_tokenIdA; @@ -623,12 +603,12 @@ HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord008, TestSize.Level1) } /** - * @tc.name: AddPermissionUsedRecord009 + * @tc.name: AddPermissionUsedRecord008 * @tc.desc: query permission record detail count. * @tc.type: FUNC * @tc.require: issueI5P4IU */ -HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord009, TestSize.Level1) +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord008, TestSize.Level1) { int32_t permRecordSize = 0; @@ -680,12 +660,12 @@ HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord009, TestSize.Level1) } /** - * @tc.name: AddPermissionUsedRecord010 + * @tc.name: AddPermissionUsedRecord009 * @tc.desc: test record cross minute not merge. * @tc.type: FUNC * @tc.require: issueI5P4IU */ -HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord010, TestSize.Level1) +HWTEST_F(PrivacyKitTest, AddPermissionUsedRecord009, TestSize.Level1) { AddPermParamInfo info; info.tokenId = g_tokenIdA; @@ -751,13 +731,11 @@ HWTEST_F(PrivacyKitTest, RemovePermissionUsedRecords002, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, RemovePermissionUsedRecords003, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); - ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, - PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID)); - EXPECT_EQ(0, AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("RemovePermissionUsedRecords003", reqPerm, false); + AccessTokenID tokenID = GetSelfTokenID(); + ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::RemovePermissionUsedRecords(tokenID)); } /** @@ -926,16 +904,16 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords004, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecords005, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("GetPermissionUsedRecords005", reqPerm, false); + AccessTokenID tokenID = GetSelfTokenID(); PermissionUsedRequest request; PermissionUsedResult result; std::vector permissionList; // query by tokenId - BuildQueryRequest(g_tokenIdA, "", permissionList, request); + BuildQueryRequest(tokenID, "", permissionList, request); ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::GetPermissionUsedRecords(request, result)); } @@ -1029,33 +1007,32 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync002, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync003, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_systemInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + MockHapToken mock("GetPermissionUsedRecordsAsync003", reqPerm, true); + AccessTokenID tokenID = GetSelfTokenID(); PermissionUsedRequest request; std::vector permissionList; - BuildQueryRequest(g_tokenIdA, "", permissionList, request); + BuildQueryRequest(tokenID, "", permissionList, request); OHOS::sptr callback(new TestCallBack()); ASSERT_EQ(ERR_PERMISSION_DENIED, PrivacyKit::GetPermissionUsedRecords(request, callback)); } /** * @tc.name: GetPermissionUsedRecordsAsync004 - * @tc.desc: cannot GetPermissionUsedRecordsAsync without permission. + * @tc.desc: cannot GetPermissionUsedRecordsAsync caller is normal app. * @tc.type: FUNC * @tc.require: issueI5P4IU */ HWTEST_F(PrivacyKitTest, GetPermissionUsedRecordsAsync004, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + MockHapToken mock("GetPermissionUsedRecordsAsync004", reqPerm, false); + AccessTokenID tokenID = GetSelfTokenID(); + PermissionUsedRequest request; std::vector permissionList; - BuildQueryRequest(g_tokenIdA, "", permissionList, request); + BuildQueryRequest(tokenID, "", permissionList, request); OHOS::sptr callback(new TestCallBack()); ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::GetPermissionUsedRecords(request, callback)); } @@ -1373,10 +1350,8 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback009, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback010, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + MockHapToken mock("RegisterPermActiveStatusCallback010", reqPerm, false); std::vector permList1 = {"ohos.permission.CAMERA"}; auto callbackPtr = std::make_shared(permList1); @@ -1394,14 +1369,11 @@ HWTEST_F(PrivacyKitTest, RegisterPermActiveStatusCallback011, TestSize.Level1) std::vector permList1 = {"ohos.permission.CAMERA"}; auto callbackPtr1 = std::make_shared(permList1); ASSERT_EQ(RET_NO_ERROR, PrivacyKit::RegisterPermActiveStatusCallback(callbackPtr1)); - - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); - ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr1)); - - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); + { + std::vector reqPerm; + MockHapToken mockTmp("RegisterPermActiveStatusCallback011_1", reqPerm, false); + ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr1)); + } ASSERT_EQ(RET_NO_ERROR, PrivacyKit::UnRegisterPermActiveStatusCallback(callbackPtr1)); } @@ -1482,7 +1454,8 @@ HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission001, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission002, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); + std::vector reqPerm; + MockHapToken mock("IsAllowedUsingPermission002", reqPerm, true); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); } @@ -1495,14 +1468,133 @@ HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission002, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission003, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_systemInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + MockHapToken mock("IsAllowedUsingPermission003", reqPerm, true); + std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); } + +/** + * @tc.name: IsAllowedUsingPermission004 + * @tc.desc: IsAllowedUsingPermission with valid tokenId. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission004, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.MICROPHONE"; + std::vector list; + int32_t ret = AppManagerAccessClient::GetInstance().GetForegroundApplications(list); + ASSERT_EQ(0, ret); + if (list.empty()) { + GTEST_LOG_(INFO) << "GetForegroundApplications empty "; + return; + } + uint32_t tokenIdForeground = list[0].accessTokenId; + ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName)); +} + +/** + * @tc.name: IsAllowedUsingPermission005 + * @tc.desc: IsAllowedUsingPermission with valid pid. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission005, TestSize.Level1) +{ + std::vector list; + ASSERT_EQ(0, AppManagerAccessClient::GetInstance().GetForegroundApplications(list)); + if (list.empty()) { + GTEST_LOG_(INFO) << "GetForegroundApplications empty "; + return; + } + + uint32_t tokenIdForeground = list[0].accessTokenId; + int32_t pidForground = list[0].pid; + std::string permissionName = "ohos.permission.MICROPHONE"; + ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, NOT_EXSIT_PID)); + ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, pidForground)); + + permissionName = "ohos.permission.CAMERA"; + ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, NOT_EXSIT_PID)); + ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, pidForground)); +} + +/** + * @tc.name: IsAllowedUsingPermission006 + * @tc.desc: IsAllowedUsingPermission with MICROPHONE_BACKGROUND permission. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission006, TestSize.Level1) +{ + std::string permissionName = "ohos.permission.MICROPHONE"; + ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); + + HapInfoParams info = { + .userID = 1, + .bundleName = "ohos.privacy_test.microphone", + .instIndex = 0, + .appIDDesc = "privacy_test.microphone" + }; + + PermissionStateFull infoManagerTestStateD = { + .permissionName = "ohos.permission.MICROPHONE_BACKGROUND", + .isGeneral = true, + .resDeviceID = {"localC"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1} + }; + + HapPolicyParams policy = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {}, + .permStateList = {infoManagerTestStateD} + }; + + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(info, policy); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(0, tokenId); // hap MICROPHONE_BACKGROUND permission + ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenId, permissionName)); // background hap + + info.isSystemApp = true; + info.bundleName = "ohos.privacy_test.microphone.sys_app"; + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(info, policy); + AccessTokenID sysApptokenId = tokenIdEx.tokenIdExStruct.tokenID; + + uint32_t selfUid = getuid(); + uint64_t selfTokenId = GetSelfTokenID(); + setuid(ACCESS_TOKEN_UID); + + uint32_t opCode1 = -1; + uint32_t opCode2 = -1; + ASSERT_EQ(true, TransferPermissionToOpcode("ohos.permission.SET_FOREGROUND_HAP_REMINDER", opCode1)); + ASSERT_EQ(true, TransferPermissionToOpcode("ohos.permission.PERMISSION_USED_STATS", opCode2)); + ASSERT_EQ(0, AddPermissionToKernel(sysApptokenId, {opCode1, opCode2}, {1, 1})); + EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + + // callkit set hap to foreground with MICROPHONE_BACKGROUND + EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(tokenId, true)); + EXPECT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenId, permissionName)); + + // callkit set g_tokenIdE to foreground without MICROPHONE_BACKGROUND + EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true)); + EXPECT_EQ(true, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); + + EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(tokenId, false)); + EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false)); + + ASSERT_EQ(0, RemovePermissionFromKernel(sysApptokenId)); + ASSERT_EQ(0, PrivacyTestCommon::DeleteTestHapToken(tokenId)); + ASSERT_EQ(0, PrivacyTestCommon::DeleteTestHapToken(sysApptokenId)); + + setuid(selfUid); + EXPECT_EQ(0, SetSelfTokenID(selfTokenId)); +} + /** * @tc.name: StartUsingPermission001 * @tc.desc: StartUsingPermission with invalid tokenId or permission or usedType. @@ -1664,11 +1756,9 @@ HWTEST_F(PrivacyKitTest, StartUsingPermission009, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, StartUsingPermission010, TestSize.Level1) { - g_policyPramsA.permStateList.emplace_back(g_infoManagerTestStateC); - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("StartUsingPermission010", reqPerm, false); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::StartUsingPermission(g_tokenIdE, permissionName)); @@ -1739,10 +1829,10 @@ HWTEST_F(PrivacyKitTest, StartUsingPermission013, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, StartUsingPermission014, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("StartUsingPermission014", reqPerm, false); + std::string permissionName = "ohos.permission.CAMERA"; auto callbackPtr = std::make_shared(); ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, @@ -1825,10 +1915,9 @@ HWTEST_F(PrivacyKitTest, StopUsingPermission005, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, StopUsingPermission006, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_normalInfoParms, g_policyPramsA); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("StopUsingPermission006", reqPerm, false); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::StopUsingPermission(g_tokenIdE, permissionName)); @@ -2073,7 +2162,6 @@ HWTEST_F(PrivacyKitTest, InitProxy001, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, RegisterSecCompEnhance001, TestSize.Level1) { - SetSelfTokenID(g_tokenIdA); SecCompEnhanceData data; data.callback = nullptr; data.challenge = 0; @@ -2085,8 +2173,7 @@ HWTEST_F(PrivacyKitTest, RegisterSecCompEnhance001, TestSize.Level1) data.callback = new (std::nothrow) StateChangeCallback(callbackPtr); EXPECT_EQ(RET_SUCCESS, PrivacyKit::RegisterSecCompEnhance(data)); - AccessTokenID secCompId = AccessTokenKit::GetNativeTokenId("security_component_service"); - EXPECT_EQ(0, SetSelfTokenID(secCompId)); + MockNativeToken mock("security_component_service"); SecCompEnhanceData data1; EXPECT_EQ(RET_SUCCESS, PrivacyKit::GetSecCompEnhance(getpid(), data1)); EXPECT_NE(RET_SUCCESS, PrivacyKit::GetSecCompEnhance(0, data1)); @@ -2102,8 +2189,7 @@ HWTEST_F(PrivacyKitTest, RegisterSecCompEnhance001, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, GetSpecialSecCompEnhance001, TestSize.Level1) { - AccessTokenID secCompId = AccessTokenKit::GetNativeTokenId("security_component_service"); - EXPECT_EQ(0, SetSelfTokenID(secCompId)); + MockNativeToken mock("security_component_service"); std::vector res; ASSERT_EQ(RET_SUCCESS, PrivacyKit::GetSpecialSecCompEnhance("", res)); @@ -2347,7 +2433,7 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos001, TestSize.Level1) // g_tokenIdB add picker used type ASSERT_EQ(RET_SUCCESS, PrivacyKit::AddPermissionUsedRecord(info)); - info.tokenId = g_tokenIdC.tokenIdExStruct.tokenID; + info.tokenId = g_tokenIdC; info.type = PermissionUsedType::SECURITY_COMPONENT_TYPE; // g_tokenIdC add security component used type ASSERT_EQ(RET_SUCCESS, PrivacyKit::AddPermissionUsedRecord(info)); @@ -2361,7 +2447,7 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos001, TestSize.Level1) ASSERT_EQ(PermissionUsedType::NORMAL_TYPE, result.type); // g_tokenIdA only normal type } else if (result.tokenId == g_tokenIdB) { ASSERT_EQ(PermissionUsedType::PICKER_TYPE, result.type); // g_tokenIdB only picker type - } else if (result.tokenId == g_tokenIdC.tokenIdExStruct.tokenID) { + } else if (result.tokenId == g_tokenIdC) { // g_tokenIdC only security component type ASSERT_EQ(PermissionUsedType::SECURITY_COMPONENT_TYPE, result.type); } @@ -2444,7 +2530,7 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos003, TestSize.Level1) // g_tokenIdB add picker used type ASSERT_EQ(RET_SUCCESS, PrivacyKit::AddPermissionUsedRecord(info)); - info.tokenId = g_tokenIdC.tokenIdExStruct.tokenID; + info.tokenId = g_tokenIdC; info.type = PermissionUsedType::SECURITY_COMPONENT_TYPE; // g_tokenIdC add security component used type ASSERT_EQ(RET_SUCCESS, PrivacyKit::AddPermissionUsedRecord(info)); @@ -2463,10 +2549,9 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos003, TestSize.Level1) ASSERT_EQ(PermissionUsedType::PICKER_TYPE, results2[FIRST_INDEX].type); // picker type std::vector results3; - ASSERT_EQ(RET_SUCCESS, PrivacyKit::GetPermissionUsedTypeInfos(g_tokenIdC.tokenIdExStruct.tokenID, - permissionName, results3)); + ASSERT_EQ(RET_SUCCESS, PrivacyKit::GetPermissionUsedTypeInfos(g_tokenIdC, permissionName, results3)); ASSERT_EQ(static_cast(RESULT_NUM_ONE), results3.size()); // only g_tokenIdC - ASSERT_EQ(g_tokenIdC.tokenIdExStruct.tokenID, results3[FIRST_INDEX].tokenId); + ASSERT_EQ(g_tokenIdC, results3[FIRST_INDEX].tokenId); ASSERT_EQ(PermissionUsedType::SECURITY_COMPONENT_TYPE, results3[FIRST_INDEX].type); // security component type } @@ -2502,21 +2587,22 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos004, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos005, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_tokenIdA)); // g_tokenIdA is a normal hap - + std::vector reqPerm; std::string permissionName; std::vector results; - ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::GetPermissionUsedTypeInfos(0, permissionName, results)); - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_infoParmsD, g_policyPramsD); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); // as a system hap without PERMISSION_USED_STATE - ASSERT_EQ(PrivacyError::ERR_PERMISSION_DENIED, PrivacyKit::GetPermissionUsedTypeInfos( - 0, permissionName, results)); + { + // as a normal hap without PERMISSION_USED_STATE + MockHapToken mock("GetPermissionUsedTypeInfos005", reqPerm, false); + ASSERT_EQ(PrivacyError::ERR_NOT_SYSTEM_APP, PrivacyKit::GetPermissionUsedTypeInfos(0, permissionName, results)); + } - PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); - EXPECT_EQ(0, AccessTokenKit::DeleteToken(tokenIdEx.tokenIdExStruct.tokenID)); // delete test hap + { + // as a system hap without PERMISSION_USED_STATE + MockHapToken mock("GetPermissionUsedTypeInfos005", reqPerm, true); + ASSERT_EQ(PrivacyError::ERR_PERMISSION_DENIED, PrivacyKit::GetPermissionUsedTypeInfos( + 0, permissionName, results)); + } } /* @@ -2529,19 +2615,17 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos006, TestSize.Level1) { uint32_t count = MAX_PERMISSION_USED_TYPE_SIZE + 1; - // set callertoken to system app - ASSERT_EQ(0, SetSelfTokenID(g_tokenIdC.tokenIDEx)); - // add 2001 permission used type record std::vector tokenIdList; - std::string tmpBundleName = g_infoParmsC.bundleName; for (uint32_t i = 0; i < count; i++) { - std::string bundleName = tmpBundleName + std::to_string(i); - g_infoParmsC.bundleName = bundleName; - AccessTokenIDEx tokenIdEx = AccessTokenKit::AllocHapToken(g_infoParmsC, g_policyPramsC); + HapInfoParams infoParms = g_infoParmsC; + HapPolicyParams policyPrams = g_policyPramsC; + infoParms.bundleName = infoParms.bundleName + std::to_string(i); + + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(infoParms, policyPrams); AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; - ASSERT_NE(tokenId, INVALID_TOKENID); + EXPECT_NE(INVALID_TOKENID, tokenId); tokenIdList.emplace_back(tokenId); AddPermParamInfo info; @@ -2549,21 +2633,19 @@ HWTEST_F(PrivacyKitTest, GetPermissionUsedTypeInfos006, TestSize.Level1) info.permissionName = "ohos.permission.READ_CONTACTS"; info.successCount = 1; info.failCount = 0; - ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(info)); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(info)); } AccessTokenID tokenId = 0; std::string permissionName; std::vector results; // record over size - ASSERT_EQ(PrivacyError::ERR_OVERSIZE, PrivacyKit::GetPermissionUsedTypeInfos(tokenId, permissionName, results)); + EXPECT_EQ(PrivacyError::ERR_OVERSIZE, PrivacyKit::GetPermissionUsedTypeInfos(tokenId, permissionName, results)); for (const auto& id : tokenIdList) { - PrivacyKit::RemovePermissionUsedRecords(id); - ASSERT_EQ(0, AccessTokenKit::DeleteToken(id)); + EXPECT_EQ(RET_SUCCESS, PrivacyKit::RemovePermissionUsedRecords(id)); + EXPECT_EQ(RET_SUCCESS, PrivacyTestCommon::DeleteTestHapToken(id)); } - - g_infoParmsC.bundleName = tmpBundleName; } /** @@ -2594,10 +2676,8 @@ HWTEST_F(PrivacyKitTest, SetMutePolicyTest001, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, SetMutePolicyTest002, TestSize.Level1) { - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_infoParmsD, g_policyPramsD); - ASSERT_NE(INVALID_TOKENID, tokenIdEx.tokenIDEx); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); // as a system hap without SET_MUTE_POLICY + std::vector reqPerm; + MockHapToken mock("SetMutePolicyTest002", reqPerm, true); // as a system hap without SET_MUTE_POLICY ASSERT_EQ(PrivacyError::ERR_PERMISSION_DENIED, PrivacyKit::SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, true, RANDOM_TOKENID)); } @@ -2610,120 +2690,12 @@ HWTEST_F(PrivacyKitTest, SetMutePolicyTest002, TestSize.Level1) */ HWTEST_F(PrivacyKitTest, SetMutePolicyTest003, TestSize.Level1) { - uint32_t tokenId = AccessTokenKit::GetNativeTokenId("camera_service"); - ASSERT_NE(0, tokenId); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); // as a system service with SET_MUTE_POLICY + MockNativeToken mock("camera_service"); // as a system service with SET_MUTE_POLICY ASSERT_EQ(PrivacyError::ERR_FIRST_CALLER_NOT_EDM, PrivacyKit::SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, true, RANDOM_TOKENID)); } -/** - * @tc.name: IsAllowedUsingPermission011 - * @tc.desc: IsAllowedUsingPermission with valid tokenId. - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission011, TestSize.Level1) -{ - std::string permissionName = "ohos.permission.MICROPHONE"; - std::vector list; - int32_t ret = AppManagerAccessClient::GetInstance().GetForegroundApplications(list); - ASSERT_EQ(0, ret); - if (list.empty()) { - GTEST_LOG_(INFO) << "GetForegroundApplications empty "; - return; - } - uint32_t tokenIdForeground = list[0].accessTokenId; - ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName)); -} - -/** - * @tc.name: IsAllowedUsingPermission012 - * @tc.desc: IsAllowedUsingPermission with valid pid. - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission012, TestSize.Level1) -{ - std::vector list; - ASSERT_EQ(0, AppManagerAccessClient::GetInstance().GetForegroundApplications(list)); - if (list.empty()) { - GTEST_LOG_(INFO) << "GetForegroundApplications empty "; - return; - } - - uint32_t tokenIdForeground = list[0].accessTokenId; - int32_t pidForground = list[0].pid; - std::string permissionName = "ohos.permission.MICROPHONE"; - ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, NOT_EXSIT_PID)); - ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, pidForground)); - - permissionName = "ohos.permission.CAMERA"; - ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, NOT_EXSIT_PID)); - ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenIdForeground, permissionName, pidForground)); -} - -/** - * @tc.name: IsAllowedUsingPermission013 - * @tc.desc: IsAllowedUsingPermission with MICROPHONE_BACKGROUND permission. - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(PrivacyKitTest, IsAllowedUsingPermission013, TestSize.Level1) -{ - std::string permissionName = "ohos.permission.MICROPHONE"; - ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); - - HapInfoParams info = { - .userID = 1, - .bundleName = "ohos.privacy_test.microphone", - .instIndex = 0, - .appIDDesc = "privacy_test.microphone" - }; - - HapPolicyParams policy = { - .apl = APL_NORMAL, - .domain = "test.domain", - .permList = {}, - .permStateList = {g_infoManagerTestStateD} - }; - - AccessTokenIDEx tokenIdEx = AccessTokenKit::AllocHapToken(info, policy); - AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; - ASSERT_NE(0, tokenId); // hap MICROPHONE_BACKGROUND permission - ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenId, permissionName)); // background hap - info.isSystemApp = true; - info.bundleName = "ohos.privacy_test.microphone.sys_app"; - tokenIdEx = AccessTokenKit::AllocHapToken(info, policy); - AccessTokenID sysApptokenId = tokenIdEx.tokenIdExStruct.tokenID; - - uint32_t selfUid = getuid(); - setuid(ACCESS_TOKEN_UID); - - uint32_t opCode1 = -1; - uint32_t opCode2 = -1; - ASSERT_EQ(true, TransferPermissionToOpcode("ohos.permission.SET_FOREGROUND_HAP_REMINDER", opCode1)); - ASSERT_EQ(true, TransferPermissionToOpcode("ohos.permission.PERMISSION_USED_STATS", opCode2)); - ASSERT_EQ(0, AddPermissionToKernel(sysApptokenId, {opCode1, opCode2}, {1, 1})); - EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); - GTEST_LOG_(INFO) << "permissionSet OK "; - - // callkit set hap to foreground with MICROPHONE_BACKGROUND - EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(tokenId, true)); - EXPECT_EQ(true, PrivacyKit::IsAllowedUsingPermission(tokenId, permissionName)); - - // callkit set g_tokenIdE to foreground without MICROPHONE_BACKGROUND - EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true)); - EXPECT_EQ(true, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); - - EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(tokenId, false)); - EXPECT_EQ(0, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false)); - ASSERT_EQ(0, RemovePermissionFromKernel(sysApptokenId)); - setuid(selfUid); - ASSERT_EQ(0, AccessTokenKit::DeleteToken(sysApptokenId)); -} - /** * @tc.name: SetHapWithFGReminder01 * @tc.desc: SetHapWithFGReminder with valid tokenId. @@ -2735,32 +2707,31 @@ HWTEST_F(PrivacyKitTest, SetHapWithFGReminder01, TestSize.Level1) uint32_t opCode1; uint32_t opCode2; uint32_t selfUid = getuid(); - setuid(0); - g_infoParmsA.isSystemApp = true; - AccessTokenIDEx tokenIdEx = AccessTokenKit::AllocHapToken(g_infoParmsA, g_policyPramsA); + uint64_t selfTokenId = GetSelfTokenID(); + HapInfoParams infoParmsA = g_infoParmsA; + HapPolicyParams policyPramsA = g_policyPramsA; + infoParmsA.isSystemApp = true; + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(infoParmsA, policyPramsA); uint32_t tokenTest = tokenIdEx.tokenIdExStruct.tokenID; setuid(ACCESS_TOKEN_UID); EXPECT_EQ(true, TransferPermissionToOpcode("ohos.permission.SET_FOREGROUND_HAP_REMINDER", opCode1)); EXPECT_EQ(true, TransferPermissionToOpcode("ohos.permission.PERMISSION_USED_STATS", opCode2)); - int32_t res = AddPermissionToKernel(tokenTest, {opCode1, opCode2}, {1, 1}); - ASSERT_EQ(res, 0); - GTEST_LOG_(INFO) << "permissionSet OK "; + ASSERT_EQ(RET_SUCCESS, AddPermissionToKernel(tokenTest, {opCode1, opCode2}, {1, 1})); EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); + std::string permissionName = "ohos.permission.MICROPHONE"; ASSERT_EQ(false, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); - int32_t ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true); - ASSERT_EQ(ret, 0); + ASSERT_EQ(RET_SUCCESS, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true)); ASSERT_EQ(true, PrivacyKit::IsAllowedUsingPermission(g_tokenIdE, permissionName)); - ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false); - ASSERT_EQ(ret, 0); + ASSERT_EQ(RET_SUCCESS, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false)); + + ASSERT_EQ(RET_SUCCESS, RemovePermissionFromKernel(tokenIdEx.tokenIDEx)); + ASSERT_EQ(RET_SUCCESS, PrivacyTestCommon::DeleteTestHapToken(tokenTest)); - res = RemovePermissionFromKernel(tokenIdEx.tokenIDEx); - ASSERT_EQ(res, 0); - setuid(0); - ASSERT_EQ(0, AccessTokenKit::DeleteToken(tokenTest)); setuid(selfUid); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(selfTokenId)); } /** @@ -2775,6 +2746,7 @@ HWTEST_F(PrivacyKitTest, SetHapWithFGReminder02, TestSize.Level1) uint32_t opCode2; uint32_t tokenTest = 111; /// 111 is a tokenId uint32_t selfUid = getuid(); + uint64_t selfTokenId = GetSelfTokenID(); setuid(ACCESS_TOKEN_UID); EXPECT_EQ(true, TransferPermissionToOpcode("ohos.permission.SET_FOREGROUND_HAP_REMINDER", opCode1)); @@ -2783,17 +2755,16 @@ HWTEST_F(PrivacyKitTest, SetHapWithFGReminder02, TestSize.Level1) ASSERT_EQ(res, 0); EXPECT_EQ(0, SetSelfTokenID(tokenTest)); - int32_t ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true); - ASSERT_EQ(ret, 0); - ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true); - ASSERT_EQ(ret, PrivacyError::ERR_PARAM_INVALID); - ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false); - ASSERT_EQ(ret, 0); - ret = PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false); - ASSERT_EQ(ret, PrivacyError::ERR_PARAM_INVALID); - res = RemovePermissionFromKernel(tokenTest); - ASSERT_EQ(res, 0); + + ASSERT_EQ(RET_SUCCESS, PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true)); + ASSERT_EQ(PrivacyKit::SetHapWithFGReminder(g_tokenIdE, true), PrivacyError::ERR_PARAM_INVALID); + ASSERT_EQ(PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false), 0); + ASSERT_EQ(PrivacyKit::SetHapWithFGReminder(g_tokenIdE, false), PrivacyError::ERR_PARAM_INVALID); + + ASSERT_EQ(RET_SUCCESS, RemovePermissionFromKernel(tokenTest)); + setuid(selfUid); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(selfTokenId)); } /** @@ -2808,6 +2779,7 @@ HWTEST_F(PrivacyKitTest, SetHapWithFGReminder03, TestSize.Level1) uint32_t opCode2; uint32_t tokenTest = 111; /// 111 is a tokenId uint32_t selfUid = getuid(); + uint64_t selfTokenId = GetSelfTokenID(); setuid(ACCESS_TOKEN_UID); EXPECT_EQ(true, TransferPermissionToOpcode("ohos.permission.SET_FOREGROUND_HAP_REMINDER", opCode1)); @@ -2816,16 +2788,17 @@ HWTEST_F(PrivacyKitTest, SetHapWithFGReminder03, TestSize.Level1) ASSERT_EQ(res, 0); EXPECT_EQ(0, SetSelfTokenID(tokenTest)); + uint32_t nativeTokenId = 672137215; // 672137215 is a native token - int32_t ret = PrivacyKit::SetHapWithFGReminder(nativeTokenId, true); - ASSERT_EQ(ret, PrivacyError::ERR_PARAM_INVALID); - res = RemovePermissionFromKernel(tokenTest); - ASSERT_EQ(res, 0); - setuid(selfUid); + ASSERT_EQ(PrivacyKit::SetHapWithFGReminder(nativeTokenId, true), PrivacyError::ERR_PARAM_INVALID); uint32_t invalidTokenId = 0; - ret = PrivacyKit::SetHapWithFGReminder(invalidTokenId, true); - ASSERT_EQ(ret, PrivacyError::ERR_PARAM_INVALID); + ASSERT_EQ(PrivacyKit::SetHapWithFGReminder(invalidTokenId, true), PrivacyError::ERR_PARAM_INVALID); + + ASSERT_EQ(RET_SUCCESS, RemovePermissionFromKernel(tokenTest)); + + setuid(selfUid); + EXPECT_EQ(RET_SUCCESS, SetSelfTokenID(selfTokenId)); } /** @@ -2851,11 +2824,16 @@ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus001, TestSize.Level1 */ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus002, TestSize.Level1) { + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.ERR_PERMISSION_DENIED"); + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("SetPermissionUsedRecordToggleStatus002", reqPerm, true); + int32_t permRecordSize = 0; bool status = true; - int32_t resGet = PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status); - EXPECT_EQ(resGet, 0); + EXPECT_EQ(RET_SUCCESS, PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, true)); + EXPECT_EQ(RET_SUCCESS, PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status)); EXPECT_TRUE(status); AddPermParamInfo info; @@ -2880,8 +2858,7 @@ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus002, TestSize.Level1 ASSERT_EQ(1, static_cast(result.bundleRecords.size())); ASSERT_EQ(permRecordSize, static_cast(result.bundleRecords[0].permissionRecords.size())); - int32_t resSet = PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, false); - EXPECT_EQ(resSet, 0); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, false)); ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); ASSERT_EQ(0, static_cast(result.bundleRecords.size())); @@ -2892,8 +2869,7 @@ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus002, TestSize.Level1 ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); ASSERT_EQ(0, static_cast(result.bundleRecords.size())); - resSet = PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, true); - EXPECT_EQ(resSet, 0); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, true)); } /** @@ -2904,13 +2880,16 @@ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus002, TestSize.Level1 */ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus003, TestSize.Level1) { + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.ERR_PERMISSION_DENIED"); + reqPerm.emplace_back("ohos.permission.PERMISSION_USED_STATS"); + MockHapToken mock("SetPermissionUsedRecordToggleStatus003", reqPerm, true); + int32_t permRecordSize = 0; bool status = true; - int32_t resSet = PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, false); - int32_t resGet = PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status); - EXPECT_EQ(resSet, 0); - EXPECT_EQ(resGet, 0); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, false)); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status)); EXPECT_FALSE(status); AddPermParamInfo info; @@ -2932,10 +2911,8 @@ HWTEST_F(PrivacyKitTest, SetPermissionUsedRecordToggleStatus003, TestSize.Level1 ASSERT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecords(request, result)); ASSERT_EQ(0, static_cast(result.bundleRecords.size())); - resSet = PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, true); - resGet = PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status); - EXPECT_EQ(resSet, 0); - EXPECT_EQ(resGet, 0); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::SetPermissionUsedRecordToggleStatus(USER_ID_2, true)); + EXPECT_EQ(RET_NO_ERROR, PrivacyKit::GetPermissionUsedRecordToggleStatus(USER_ID_2, status)); EXPECT_TRUE(status); ASSERT_EQ(RET_NO_ERROR, PrivacyKit::AddPermissionUsedRecord(info)); diff --git a/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.cpp b/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f5e502d9ad41daabdf280d351d82e9505264856 --- /dev/null +++ b/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2025 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 "privacy_test_common.h" +#include "gtest/gtest.h" +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +std::mutex g_lockSetToken; +uint64_t g_shellTokenId = 0; +} +void PrivacyTestCommon::SetTestEvironment(uint64_t shellTokenId) +{ + std::lock_guard lock(g_lockSetToken); + g_shellTokenId = shellTokenId; +} + +void PrivacyTestCommon::ResetTestEvironment() +{ + std::lock_guard lock(g_lockSetToken); + g_shellTokenId = 0; +} + +uint64_t PrivacyTestCommon::GetShellTokenId() +{ + std::lock_guard lock(g_lockSetToken); + return g_shellTokenId; +} + +AccessTokenIDEx PrivacyTestCommon::AllocTestHapToken(const HapInfoParams& hapInfo, HapPolicyParams& hapPolicy) +{ + AccessTokenIDEx tokenIdEx = {0}; + uint64_t selfTokenId = GetSelfTokenID(); + for (auto& permissionStateFull : hapPolicy.permStateList) { + PermissionDef permDefResult; + if (AccessTokenKit::GetDefPermission(permissionStateFull.permissionName, permDefResult) != RET_SUCCESS) { + continue; + } + if (permDefResult.availableLevel > hapPolicy.apl) { + hapPolicy.aclRequestedList.emplace_back(permissionStateFull.permissionName); + } + } + if (PrivacyTestCommon::GetNativeTokenIdFromProcess("foundation") == selfTokenId) { + AccessTokenKit::InitHapToken(hapInfo, hapPolicy, tokenIdEx); + } else { + // set sh token for self + MockNativeToken mock("foundation"); + AccessTokenKit::InitHapToken(hapInfo, hapPolicy, tokenIdEx); + + // restore + EXPECT_EQ(0, SetSelfTokenID(selfTokenId)); + } + return tokenIdEx; +} + +int32_t PrivacyTestCommon::DeleteTestHapToken(AccessTokenID tokenID) +{ + uint64_t selfTokenId = GetSelfTokenID(); + if (PrivacyTestCommon::GetNativeTokenIdFromProcess("foundation") == selfTokenId) { + return AccessTokenKit::DeleteToken(tokenID); + } + + // set sh token for self + MockNativeToken mock("foundation"); + + int32_t ret = AccessTokenKit::DeleteToken(tokenID); + // restore + EXPECT_EQ(0, SetSelfTokenID(selfTokenId)); + return ret; +} + +AccessTokenID PrivacyTestCommon::GetNativeTokenIdFromProcess(const std::string &process) +{ + uint64_t selfTokenId = GetSelfTokenID(); + EXPECT_EQ(0, SetSelfTokenID(PrivacyTestCommon::GetShellTokenId())); // set shell token + + std::string dumpInfo; + AtmToolsParamInfo info; + info.processName = process; + AccessTokenKit::DumpTokenInfo(info, dumpInfo); + size_t pos = dumpInfo.find("\"tokenID\": "); + if (pos == std::string::npos) { + return 0; + } + pos += std::string("\"tokenID\": ").length(); + std::string numStr; + while (pos < dumpInfo.length() && std::isdigit(dumpInfo[pos])) { + numStr += dumpInfo[pos]; + ++pos; + } + // restore + EXPECT_EQ(0, SetSelfTokenID(selfTokenId)); + + std::istringstream iss(numStr); + AccessTokenID tokenID; + iss >> tokenID; + return tokenID; +} + +// need call by native process +AccessTokenIDEx PrivacyTestCommon::GetHapTokenIdFromBundle( + int32_t userID, const std::string& bundleName, int32_t instIndex) +{ + uint64_t selfTokenId = GetSelfTokenID(); + ATokenTypeEnum type = AccessTokenKit::GetTokenTypeFlag(static_cast(selfTokenId)); + if (type != TOKEN_NATIVE) { + AccessTokenID tokenId1 = GetNativeTokenIdFromProcess("privacy_service"); + EXPECT_EQ(0, SetSelfTokenID(tokenId1)); + } + AccessTokenIDEx tokenIdEx = AccessTokenKit::GetHapTokenIDEx(userID, bundleName, instIndex); + + EXPECT_EQ(0, SetSelfTokenID(selfTokenId)); + return tokenIdEx; +} + +MockNativeToken::MockNativeToken(const std::string& process) +{ + selfToken_ = GetSelfTokenID(); + uint32_t tokenId = PrivacyTestCommon::GetNativeTokenIdFromProcess(process); + SetSelfTokenID(tokenId); +} + +MockNativeToken::~MockNativeToken() +{ + SetSelfTokenID(selfToken_); +} + +MockHapToken::MockHapToken( + const std::string& bundle, const std::vector& reqPerm, bool isSystemApp) +{ + selfToken_ = GetSelfTokenID(); + HapInfoParams infoParams = { + .userID = 0, + .bundleName = bundle, + .instIndex = 0, + .appIDDesc = "AccessTokenTestAppID", + .apiVersion = PrivacyTestCommon::DEFAULT_API_VERSION, + .isSystemApp = isSystemApp, + .appDistributionType = "", + }; + + HapPolicyParams policyParams = { + .apl = APL_NORMAL, + .domain = "accesstoken_test_domain", + }; + for (size_t i = 0; i < reqPerm.size(); ++i) { + PermissionDef permDefResult; + if (AccessTokenKit::GetDefPermission(reqPerm[i], permDefResult) != RET_SUCCESS) { + continue; + } + PermissionStateFull permState = { + .permissionName = reqPerm[i], + .isGeneral = true, + .resDeviceID = {"local3"}, + .grantStatus = {PermissionState::PERMISSION_DENIED}, + .grantFlags = {PermissionFlag::PERMISSION_DEFAULT_FLAG} + }; + policyParams.permStateList.emplace_back(permState); + if (permDefResult.availableLevel > policyParams.apl) { + policyParams.aclRequestedList.emplace_back(reqPerm[i]); + } + } + + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(infoParams, policyParams); + mockToken_= tokenIdEx.tokenIdExStruct.tokenID; + EXPECT_NE(mockToken_, INVALID_TOKENID); + EXPECT_EQ(0, SetSelfTokenID(tokenIdEx.tokenIDEx)); +} + +MockHapToken::~MockHapToken() +{ + if (mockToken_ != INVALID_TOKENID) { + EXPECT_EQ(0, PrivacyTestCommon::DeleteTestHapToken(mockToken_)); + } + EXPECT_EQ(0, SetSelfTokenID(selfToken_)); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.h b/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.h new file mode 100644 index 0000000000000000000000000000000000000000..38254950e0a00172e32649c21a3a0d9302c5828d --- /dev/null +++ b/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2025 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 PRIVACY_TEST_COMMON_H +#define PRIVACY_TEST_COMMON_H + +#include "access_token.h" +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class MockNativeToken { +public: + explicit MockNativeToken(const std::string& process); + ~MockNativeToken(); +private: + uint64_t selfToken_; +}; + +class MockHapToken { +public: + explicit MockHapToken( + const std::string& bundle, const std::vector& reqPerm, bool isSystemApp = true); + ~MockHapToken(); +private: + uint64_t selfToken_; + uint32_t mockToken_; +}; +class PrivacyTestCommon { +public: + static constexpr int32_t DEFAULT_API_VERSION = 12; + static void SetTestEvironment(uint64_t shellTokenId); + static void ResetTestEvironment(); + static uint64_t GetShellTokenId(); + + static AccessTokenIDEx AllocTestHapToken(const HapInfoParams& hapInfo, HapPolicyParams& hapPolicy); + static int32_t DeleteTestHapToken(AccessTokenID tokenID); + static AccessTokenID GetNativeTokenIdFromProcess(const std::string& process); + static AccessTokenIDEx GetHapTokenIdFromBundle( + int32_t userID, const std::string& bundleName, int32_t instIndex); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // PRIVACY_TEST_COMMON_H diff --git a/interfaces/innerkits/tokensync/test/BUILD.gn b/interfaces/innerkits/tokensync/test/BUILD.gn index a2bddbd3a3ee576d60677fdf7d18191c757a604d..571bbd1c7e879326df25e5301cbe4f70f15caf5a 100644 --- a/interfaces/innerkits/tokensync/test/BUILD.gn +++ b/interfaces/innerkits/tokensync/test/BUILD.gn @@ -30,6 +30,8 @@ ohos_unittest("libtokensync_sdk_test") { "${access_token_path}/frameworks/tokensync/include", "${access_token_path}/interfaces/innerkits/accesstoken/include", "${access_token_path}/interfaces/innerkits/tokensync/include", + "${access_token_path}/interfaces/innerkits/nativetoken/include", + "${access_token_path}/interfaces/innerkits/token_setproc/include", "../src", ] @@ -39,7 +41,12 @@ ohos_unittest("libtokensync_sdk_test") { configs = [ "${access_token_path}/config:coverage_flags" ] - deps = [ "../:libtokensync_sdk" ] + deps = [ + "${access_token_path}/interfaces/innerkits/accesstoken:libaccesstoken_sdk", + "${access_token_path}/interfaces/innerkits/nativetoken:libnativetoken_shared", + "${access_token_path}/interfaces/innerkits/token_setproc:libtokensetproc_shared", + "${access_token_path}/interfaces/innerkits/tokensync:libtokensync_sdk", + ] external_deps = [ "c_utils:utils" ] } diff --git a/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp b/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp index 1e7dc47ff298e03fb1231035f44fc830d90988a6..69a5687d0b2c0351add2164061dc7f93d780d0b1 100644 --- a/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp +++ b/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp @@ -15,7 +15,12 @@ #include "token_sync_kit_test.h" +#include "access_token.h" +#include "access_token_error.h" +#include "accesstoken_kit.h" #include "i_token_sync_manager.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" #include "token_sync_manager_client.h" using namespace testing::ext; @@ -23,12 +28,35 @@ using namespace testing::ext; namespace OHOS { namespace Security { namespace AccessToken { +static void SetNativeTokenId(const std::string &process) +{ + std::string dumpInfo; + AtmToolsParamInfo info; + info.processName = process; + AccessTokenKit::DumpTokenInfo(info, dumpInfo); + size_t pos = dumpInfo.find("\"tokenID\": "); + if (pos == std::string::npos) { + return; + } + pos += std::string("\"tokenID\": ").length(); + std::string numStr; + while (pos < dumpInfo.length() && std::isdigit(dumpInfo[pos])) { + numStr += dumpInfo[pos]; + ++pos; + } + + std::istringstream iss(numStr); + AccessTokenID tokenID; + iss >> tokenID; + + SetSelfTokenID(tokenID); +} + void TokenSyncKitTest::SetUpTestCase() {} void TokenSyncKitTest::TearDownTestCase() -{ -} +{} void TokenSyncKitTest::SetUp() { @@ -66,13 +94,27 @@ static void StartOrStopTokenSyncService(bool start) HWTEST_F(TokenSyncKitTest, UpdateRemoteHapTokenInfo001, TestSize.Level1) { HapTokenInfoForSync tokenInfo; + uint64_t selfTokenId = GetSelfTokenID(); + // proxy is nullptr ASSERT_EQ(TokenSyncError::TOKEN_SYNC_IPC_ERROR, TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo)); StartOrStopTokenSyncService(true); + + // service is starting, but no permission(shell process) + SetNativeTokenId("hdcd"); + int32_t selfUid = getuid(); + setuid(10001); // 10001: UID + ASSERT_EQ(ERR_IDENTITY_CHECK_FAILED, TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo)); + setuid(selfUid); + + // service is starting, and has permission(native process) + SetNativeTokenId("accesstoken_service"); ASSERT_EQ(0, TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo)); + StartOrStopTokenSyncService(false); + SetSelfTokenID(selfTokenId); } /** @@ -83,13 +125,28 @@ HWTEST_F(TokenSyncKitTest, UpdateRemoteHapTokenInfo001, TestSize.Level1) */ HWTEST_F(TokenSyncKitTest, GetRemoteHapTokenInfo001, TestSize.Level1) { + uint64_t selfTokenId = GetSelfTokenID(); + + // proxy is nullptr ASSERT_EQ(TokenSyncError::TOKEN_SYNC_IPC_ERROR, TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo("", 0)); StartOrStopTokenSyncService(true); + + // service is starting, but no permission(shell process) + SetNativeTokenId("hdcd"); + int32_t selfUid = getuid(); + setuid(10001); // 10001: UID + ASSERT_EQ(ERR_IDENTITY_CHECK_FAILED, TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo("", 0)); + setuid(selfUid); + + // service is starting, and has permission(native process) + SetNativeTokenId("accesstoken_service"); ASSERT_EQ(TokenSyncError::TOKEN_SYNC_PARAMS_INVALID, TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo("", 0)); + StartOrStopTokenSyncService(false); + SetSelfTokenID(selfTokenId); } /** @@ -100,13 +157,27 @@ HWTEST_F(TokenSyncKitTest, GetRemoteHapTokenInfo001, TestSize.Level1) */ HWTEST_F(TokenSyncKitTest, DeleteRemoteHapTokenInfo001, TestSize.Level1) { + uint64_t selfTokenId = GetSelfTokenID(); + + // proxy is nullptr ASSERT_EQ(TokenSyncError::TOKEN_SYNC_IPC_ERROR, TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(0)); StartOrStopTokenSyncService(true); + + // service is starting, but no permission(shell process) + SetNativeTokenId("hdcd"); + int32_t selfUid = getuid(); + setuid(10001); // 10001: UID + ASSERT_EQ(ERR_IDENTITY_CHECK_FAILED, TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(0)); + setuid(selfUid); + + // service is starting, and has permission(native process) + SetNativeTokenId("accesstoken_service"); ASSERT_EQ(TokenSyncError::TOKEN_SYNC_PARAMS_INVALID, TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(0)); StartOrStopTokenSyncService(false); + SetSelfTokenID(selfTokenId); } } // namespace AccessToken } // namespace Security diff --git a/services/accesstokenmanager/permission_definitions.json b/services/accesstokenmanager/permission_definitions.json index 770b03143f118c28162dfd0fc7278a6ad8411afc..ed3941c2795f66a0e1e1fe04d1fd0fdc87bd05c6 100644 --- a/services/accesstokenmanager/permission_definitions.json +++ b/services/accesstokenmanager/permission_definitions.json @@ -6307,10 +6307,11 @@ "grantMode": "system_grant", "availableLevel": "system_core", "availableType": "SERVICE", - "since": 18, + "since": 20, "deprecated": "", "provisionEnable": true, - "distributedSceneEnable": true + "distributedSceneEnable": true, + "deviceTypes": ["phone", "tablet"] }, { "name": "ohos.permission.GET_FILE_ICON", diff --git a/services/privacymanager/test/coverage/BUILD.gn b/services/privacymanager/test/coverage/BUILD.gn index 36d7efa6bf57a7d21d4bf0ee83f7690bcff45f7a..d3f3bde0d99bef1e498854c12c8d23a9801a701c 100644 --- a/services/privacymanager/test/coverage/BUILD.gn +++ b/services/privacymanager/test/coverage/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. +# Copyright (c) 2024-2025 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 @@ -28,6 +28,8 @@ if (is_standard_system && ability_base_enable == true) { include_dirs = [ "${access_token_path}/frameworks/common/include", + "${access_token_path}/interfaces/innerkits/nativetoken/include", + "${access_token_path}/interfaces/innerkits/privacy/test/unittest/src", "${access_token_path}/frameworks/privacy/include", "${access_token_path}/interfaces/innerkits/accesstoken/include", "${access_token_path}/interfaces/innerkits/privacy/include", @@ -51,6 +53,7 @@ if (is_standard_system && ability_base_enable == true) { ] sources = [ + "${access_token_path}/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.cpp", "../../src/active/active_status_callback_manager.cpp", "../../src/active/perm_active_status_callback_death_recipient.cpp", "../../src/active/perm_active_status_change_callback_proxy.cpp", @@ -81,6 +84,7 @@ if (is_standard_system && ability_base_enable == true) { "${access_token_path}/frameworks/privacy:privacy_communication_adapter_cxx", "${access_token_path}/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "${access_token_path}/interfaces/innerkits/accesstoken:libtokenid_sdk", + "${access_token_path}/interfaces/innerkits/nativetoken:libnativetoken_shared", "${access_token_path}/interfaces/innerkits/privacy:libprivacy_sdk", "${access_token_path}/interfaces/innerkits/token_setproc:libtoken_setproc", "${access_token_path}/services/common:accesstoken_service_common", diff --git a/services/privacymanager/test/coverage/permission_record_manager_coverage_test.cpp b/services/privacymanager/test/coverage/permission_record_manager_coverage_test.cpp index 93eb24742653a37cd06d62504468e3d35e03edde..c8429c8698aae4f8ee4f98221b6a87001b847737 100644 --- a/services/privacymanager/test/coverage/permission_record_manager_coverage_test.cpp +++ b/services/privacymanager/test/coverage/permission_record_manager_coverage_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -31,6 +31,7 @@ #include "privacy_error.h" #include "privacy_field_const.h" #include "privacy_kit.h" +#include "privacy_test_common.h" #include "state_change_callback.h" #include "time_util.h" #include "token_setproc.h" @@ -113,28 +114,32 @@ public: void PermissionRecordManagerTest::SetUpTestCase() { g_selfTokenId = GetSelfTokenID(); - g_nativeToken = AccessTokenKit::GetNativeTokenId("privacy_service"); + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); + + g_nativeToken = PrivacyTestCommon::GetNativeTokenIdFromProcess("privacy_service"); } -void PermissionRecordManagerTest::TearDownTestCase() {} +void PermissionRecordManagerTest::TearDownTestCase() +{ + PrivacyTestCommon::ResetTestEvironment(); +} void PermissionRecordManagerTest::SetUp() { PermissionRecordManager::GetInstance().Register(); - AccessTokenKit::AllocHapToken(g_InfoParms1, g_PolicyPrams1); - AccessTokenKit::AllocHapToken(g_InfoParms2, g_PolicyPrams2); + PrivacyTestCommon::AllocTestHapToken(g_InfoParms1, g_PolicyPrams1); + PrivacyTestCommon::AllocTestHapToken(g_InfoParms2, g_PolicyPrams2); } void PermissionRecordManagerTest::TearDown() { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - AccessTokenKit::DeleteToken(tokenId); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, - g_InfoParms2.instIndex); - AccessTokenKit::DeleteToken(tokenId); - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms2.userID, g_InfoParms2.bundleName, g_InfoParms2.instIndex); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); } class PermissionRecordManagerCoverTestCb1 : public StateCustomizedCbk { @@ -198,11 +203,14 @@ HWTEST_F(PermissionRecordManagerTest, OnAppStateChanged001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, AppStatusListener001, TestSize.Level1) { - AccessTokenID tokenId1 = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx1 = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId1 = tokenIdEx1.tokenIdExStruct.tokenID; ASSERT_NE(static_cast(0), tokenId1); - AccessTokenID tokenId2 = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, - g_InfoParms2.instIndex); + + AccessTokenIDEx tokenIdEx2 = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms2.userID, g_InfoParms2.bundleName, g_InfoParms2.instIndex); + AccessTokenID tokenId2 = tokenIdEx2.tokenIdExStruct.tokenID; ASSERT_NE(static_cast(0), tokenId2); ContinusPermissionRecord recordA1 = { @@ -252,11 +260,13 @@ HWTEST_F(PermissionRecordManagerTest, AppStatusListener001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(INVALID_TOKENID, tokenId); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.CAMERA"); + reqPerm.emplace_back("ohos.permission.MANAGE_CAMERA_CONFIG"); + MockHapToken mock("FindRecordsToUpdateAndExecutedTest001", reqPerm, false); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); + AccessTokenID tokenId = GetSelfTokenID();; + ASSERT_NE(INVALID_TOKENID, tokenId); ActiveChangeType status = PERM_ACTIVE_IN_BACKGROUND; std::string permission = "ohos.permission.CAMERA"; @@ -282,8 +292,9 @@ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest001, Tes */ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest002, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ActiveChangeType status = PERM_ACTIVE_IN_BACKGROUND; std::string permission = "ohos.permission.MICROPHONE"; @@ -307,8 +318,9 @@ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest002, Tes */ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest003, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ActiveChangeType status = PERM_ACTIVE_IN_FOREGROUND; std::string permission = "ohos.permission.CAMERA"; @@ -331,8 +343,9 @@ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest003, Tes */ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest004, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ActiveChangeType status = PERM_ACTIVE_IN_BACKGROUND; std::string permission = "ohos.permission.CAMERA"; @@ -355,8 +368,9 @@ HWTEST_F(PermissionRecordManagerTest, FindRecordsToUpdateAndExecutedTest004, Tes */ HWTEST_F(PermissionRecordManagerTest, ExecuteCameraCallbackAsyncTest001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); auto callbackPtr = std::make_shared(); @@ -444,8 +458,9 @@ HWTEST_F(PermissionRecordManagerTest, OnRemoteDied001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, OnApplicationStateChanged001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); PrivacyAppStateObserver observer; @@ -517,9 +532,10 @@ HWTEST_F(PermissionRecordManagerTest, RemoveCallback001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, UpdateRecords001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); PermissionUsageFlag flag = FLAG_PERMISSION_USAGE_SUMMARY; PermissionUsedRecord inBundleRecord; @@ -564,9 +580,10 @@ HWTEST_F(PermissionRecordManagerTest, UpdateRecords001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, RemoveRecordFromStartList001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permission = "ohos.permission.READ_MEDIA"; ASSERT_EQ(Constant::SUCCESS, @@ -626,9 +643,10 @@ HWTEST_F(PermissionRecordManagerTest, PermissionListFilter001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, Unregister001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(Constant::SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId, PID, "ohos.permission.READ_MEDIA"), CALLER_PID)); @@ -768,9 +786,11 @@ static void GeneratePermissionRecord(AccessTokenID tokenID) */ HWTEST_F(PermissionRecordManagerTest, GetRecords003, TestSize.Level1) { - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenID); + MockNativeToken mock("privacy_service"); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenID); GeneratePermissionRecord(tokenID); PermissionRecordManager::GetInstance().SetDefaultConfigValue(); @@ -820,9 +840,10 @@ HWTEST_F(PermissionRecordManagerTest, GetRecords003, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, GetRecords004, TestSize.Level1) { - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenID); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenID); GeneratePermissionRecord(tokenID); PermissionRecordManager::GetInstance().SetDefaultConfigValue(); @@ -1002,11 +1023,12 @@ HWTEST_F(PermissionRecordManagerTest, RemoveRecordFromStartListTest001, TestSize { std::set startRecordList = PermissionRecordManager::GetInstance().startRecordList_; PermissionRecordManager::GetInstance().startRecordList_.clear(); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(INVALID_TOKENID, tokenId); + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.CAMERA"); + reqPerm.emplace_back("ohos.permission.MANAGE_CAMERA_CONFIG"); + MockHapToken mock("FindRecordsToUpdateAndExecutedTest001", reqPerm, false); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); + AccessTokenID tokenId = GetSelfTokenID();; ActiveChangeType status = PERM_ACTIVE_IN_FOREGROUND; PermissionRecordManager::GetInstance().AddRecordToStartList( diff --git a/services/privacymanager/test/unittest/BUILD.gn b/services/privacymanager/test/unittest/BUILD.gn index 1520b904c6f86e5268a0809d2e973308862d5f49..a483f42c3ede7d53d9c5f5bdb1cfc8ecdda3e450 100644 --- a/services/privacymanager/test/unittest/BUILD.gn +++ b/services/privacymanager/test/unittest/BUILD.gn @@ -31,6 +31,8 @@ if (is_standard_system && ability_base_enable == true) { "${access_token_path}/frameworks/privacy/include", "${access_token_path}/interfaces/innerkits/accesstoken/include", "${access_token_path}/interfaces/innerkits/privacy/include", + "${access_token_path}/interfaces/innerkits/nativetoken/include", + "${access_token_path}/interfaces/innerkits/privacy/test/unittest/src", "${access_token_path}/interfaces/innerkits/privacy/src", "${access_token_path}/services/common/app_manager/include", "${access_token_path}/services/common/json_parse/include", @@ -51,6 +53,7 @@ if (is_standard_system && ability_base_enable == true) { ] sources = [ + "${access_token_path}/interfaces/innerkits/privacy/test/unittest/src/privacy_test_common.cpp", "${access_token_path}/services/common/libraryloader/src/libraryloader.cpp", "../../src/active/active_status_callback_manager.cpp", "../../src/active/perm_active_status_callback_death_recipient.cpp", @@ -86,6 +89,7 @@ if (is_standard_system && ability_base_enable == true) { "${access_token_path}/frameworks/privacy:privacy_communication_adapter_cxx", "${access_token_path}/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "${access_token_path}/interfaces/innerkits/accesstoken:libtokenid_sdk", + "${access_token_path}/interfaces/innerkits/nativetoken:libnativetoken_shared", "${access_token_path}/interfaces/innerkits/privacy:libprivacy_sdk", "${access_token_path}/interfaces/innerkits/token_setproc:libtokensetproc_shared", "${access_token_path}/services/common:accesstoken_service_common", diff --git a/services/privacymanager/test/unittest/permission_record_manager_test.cpp b/services/privacymanager/test/unittest/permission_record_manager_test.cpp index ad105ad9ee852f08b9dda0cf2bebd4700896b3ff..132ae91ae1022f4e76466ffb55fc4a2e3c755ae3 100644 --- a/services/privacymanager/test/unittest/permission_record_manager_test.cpp +++ b/services/privacymanager/test/unittest/permission_record_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -38,6 +38,7 @@ #include "privacy_error.h" #include "privacy_field_const.h" #include "privacy_kit.h" +#include "privacy_test_common.h" #include "state_change_callback.h" #include "time_util.h" #include "token_setproc.h" @@ -71,6 +72,7 @@ static const int32_t PICKER_TYPE_ADD_VALUE = 2; static const int32_t SEC_COMPONENT_TYPE_ADD_VALUE = 4; static const int32_t VALUE_MAX_LEN = 32; static const char* EDM_MIC_MUTE_KEY = "persist.edm.mic_disable"; +static MockNativeToken* g_mock = nullptr; static PermissionStateFull g_testState1 = { .permissionName = "ohos.permission.CAMERA", .isGeneral = true, @@ -138,11 +140,14 @@ public: void PermissionRecordManagerTest::SetUpTestCase() { + g_selfTokenId = GetSelfTokenID(); + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); + g_mock = new (std::nothrow) MockNativeToken("privacy_service"); + DelayedSingleton::GetInstance()->Initialize(); PermissionRecordManager::GetInstance().Init(); - g_selfTokenId = GetSelfTokenID(); - g_nativeToken = AccessTokenKit::GetNativeTokenId("privacy_service"); + g_nativeToken = PrivacyTestCommon::GetNativeTokenIdFromProcess("privacy_service"); g_isMicEdmMute = PermissionRecordManager::GetInstance().isMicEdmMute_; g_isMicMixMute = PermissionRecordManager::GetInstance().isMicMixMute_; PermissionRecordManager::GetInstance().isMicEdmMute_ = false; @@ -153,6 +158,11 @@ void PermissionRecordManagerTest::TearDownTestCase() { PermissionRecordManager::GetInstance().isMicEdmMute_ = g_isMicEdmMute; PermissionRecordManager::GetInstance().isMicMixMute_ = g_isMicMixMute; + PrivacyTestCommon::ResetTestEvironment(); + if (g_mock != nullptr) { + delete g_mock; + g_mock = nullptr; + } } void PermissionRecordManagerTest::SetUp() @@ -160,8 +170,10 @@ void PermissionRecordManagerTest::SetUp() PermissionRecordManager::GetInstance().Init(); PermissionRecordManager::GetInstance().Register(); - AccessTokenKit::AllocHapToken(g_InfoParms1, g_PolicyPrams1); - AccessTokenKit::AllocHapToken(g_InfoParms2, g_PolicyPrams2); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_InfoParms1, g_PolicyPrams1); + ASSERT_NE(tokenIdEx.tokenIdExStruct.tokenID, INVALID_TOKENID); + tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_InfoParms2, g_PolicyPrams2); + ASSERT_NE(tokenIdEx.tokenIdExStruct.tokenID, INVALID_TOKENID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, false, RANDOM_TOKENID); if (appStateObserver_ != nullptr) { @@ -172,16 +184,15 @@ void PermissionRecordManagerTest::SetUp() void PermissionRecordManagerTest::TearDown() { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms2.userID, g_InfoParms2.bundleName, g_InfoParms2.instIndex); - AccessTokenKit::DeleteToken(tokenId); - PrivacyKit::RemovePermissionUsedRecords(tokenId); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + PrivacyKit::RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); appStateObserver_ = nullptr; - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); } class PermissionRecordManagerTestCb1 : public StateCustomizedCbk { @@ -307,9 +318,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest001, TestSize.Leve auto callbackWrap = new (std::nothrow) StateChangeCallback(callbackPtr); ASSERT_NE(nullptr, callbackPtr); ASSERT_NE(nullptr, callbackWrap); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(ERR_PARAM_INVALID, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(0, PID, permissionName), callbackWrap->AsObject(), CALLER_PID)); } @@ -322,14 +330,13 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest001, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest002, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - auto callbackPtr = std::make_shared(); auto callbackWrap = new (std::nothrow) StateChangeCallback(callbackPtr); ASSERT_NE(nullptr, callbackPtr); ASSERT_NE(nullptr, callbackWrap); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(ERR_PARAM_INVALID, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId, PID, "ohos.permission.LOCATION"), callbackWrap->AsObject(), CALLER_PID)); @@ -356,8 +363,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest002, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest003, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - char value[VALUE_MAX_LEN] = {0}; GetParameter(EDM_MIC_MUTE_KEY, "", value, VALUE_MAX_LEN - 1); GTEST_LOG_(INFO) << "value:" << value; @@ -365,9 +370,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest003, TestSize.Leve bool isMute = strncmp(value, "true", VALUE_MAX_LEN) == 0; SetParameter(EDM_MIC_MUTE_KEY, "true"); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.MICROPHONE"; ASSERT_EQ(PrivacyError::ERR_EDM_POLICY_CHECK_FAILED, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -384,8 +390,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest003, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest004, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - char value[VALUE_MAX_LEN] = {0}; GetParameter(EDM_MIC_MUTE_KEY, "", value, VALUE_MAX_LEN - 1); GTEST_LOG_(INFO) << "value:" << value; @@ -402,9 +406,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest004, TestSize.Leve ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.READ_MEDIA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -426,8 +431,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest004, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest005, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - char value[VALUE_MAX_LEN] = {0}; GetParameter(EDM_MIC_MUTE_KEY, "", value, VALUE_MAX_LEN - 1); GTEST_LOG_(INFO) << "value:" << value; @@ -443,9 +446,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest005, TestSize.Leve ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.READ_MEDIA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -468,8 +472,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest005, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest006, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - char value[VALUE_MAX_LEN] = {0}; GetParameter(EDM_MIC_MUTE_KEY, "", value, VALUE_MAX_LEN - 1); GTEST_LOG_(INFO) << "value:" << value; @@ -485,9 +487,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest006, TestSize.Leve ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.LOCATION"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -510,9 +513,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest006, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest007, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); // tokenId invaild ASSERT_EQ(PrivacyError::ERR_PARAM_INVALID, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -537,17 +541,16 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest007, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest008, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - std::vector permList = {"ohos.permission.CAMERA"}; sptr callback = new (std::nothrow) PermActiveStatusChangeCallback(); ASSERT_NE(nullptr, callback); ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -581,8 +584,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest008, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest009, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - auto callbackPtr1 = std::make_shared(); auto callbackWrap1 = new (std::nothrow) StateChangeCallback(callbackPtr1); ASSERT_NE(nullptr, callbackPtr1); @@ -593,9 +594,10 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest009, TestSize.Leve ASSERT_NE(nullptr, callbackPtr2); ASSERT_NE(nullptr, callbackWrap2); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -632,17 +634,16 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest009, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest010, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - std::vector permList = {"ohos.permission.CAMERA"}; sptr callback = new (std::nothrow) PermActiveStatusChangeCallback(); ASSERT_NE(nullptr, callback); ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -672,16 +673,15 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest010, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest011, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - std::vector permList = {"ohos.permission.CAMERA"}; sptr callback = new (std::nothrow) PermActiveStatusChangeCallback(); ASSERT_NE(nullptr, callback); ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().RegisterPermActiveStatusCallback( GetSelfTokenID(), permList, callback->AsObject())); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -710,8 +710,6 @@ HWTEST_F(PermissionRecordManagerTest, StartUsingPermissionTest011, TestSize.Leve */ HWTEST_F(PermissionRecordManagerTest, ShowGlobalDialog001, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - ASSERT_EQ(true, PermissionRecordManager::GetInstance().ShowGlobalDialog("ohos.permission.CAMERA")); sleep(3); // wait for dialog disappear ASSERT_EQ(true, PermissionRecordManager::GetInstance().ShowGlobalDialog("ohos.permission.MICROPHONE")); @@ -728,8 +726,6 @@ HWTEST_F(PermissionRecordManagerTest, ShowGlobalDialog001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, AppStateChangeListener001, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - char value[VALUE_MAX_LEN] = {0}; GetParameter(EDM_MIC_MUTE_KEY, "", value, VALUE_MAX_LEN - 1); GTEST_LOG_(INFO) << "value:" << value; @@ -739,8 +735,10 @@ HWTEST_F(PermissionRecordManagerTest, AppStateChangeListener001, TestSize.Level1 PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); // status is inactive ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( @@ -775,9 +773,11 @@ HWTEST_F(PermissionRecordManagerTest, TransferOpcodeToPermission001, TestSize.Le */ HWTEST_F(PermissionRecordManagerTest, AddPermissionUsedRecord001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + MockNativeToken mock("camera_service"); // native process with have add permission + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); AddPermParamInfo info; info.tokenId = tokenId; @@ -805,9 +805,11 @@ HWTEST_F(PermissionRecordManagerTest, AddPermissionUsedRecord001, TestSize.Level */ HWTEST_F(PermissionRecordManagerTest, AddPermissionUsedRecord002, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + MockNativeToken mock("camera_service"); // native process with have permission + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); AddPermParamInfo info; info.tokenId = tokenId; @@ -817,19 +819,6 @@ HWTEST_F(PermissionRecordManagerTest, AddPermissionUsedRecord002, TestSize.Level ASSERT_EQ(PrivacyError::ERR_PARAM_INVALID, PermissionRecordManager::GetInstance().AddPermissionUsedRecord(info)); } -/* - * @tc.name: RemovePermissionUsedRecords001 - * @tc.desc: PermissionRecordManager::RemovePermissionUsedRecords function test - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(PermissionRecordManagerTest, RemovePermissionUsedRecords001, TestSize.Level1) -{ - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); -} - /* * @tc.name:SetPermissionUsedRecordToggleStatus001 * @tc.desc: PermissionRecordManager::SetPermissionUsedRecordToggleStatus function test @@ -898,9 +887,10 @@ HWTEST_F(PermissionRecordManagerTest, UpdatePermUsedRecToggleStatusMap001, TestS */ HWTEST_F(PermissionRecordManagerTest, StopUsingPermission001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId); // tokenId invaild ASSERT_EQ(PrivacyError::ERR_PARAM_INVALID, PermissionRecordManager::GetInstance().StopUsingPermission( @@ -1032,7 +1022,7 @@ HWTEST_F(PermissionRecordManagerTest, AddDataValueToResults003, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest001, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, true, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1054,7 +1044,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest001, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest002, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1076,7 +1066,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest002, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest003, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, false, RANDOM_TOKENID); @@ -1098,7 +1088,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest003, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest004, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, true, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1121,7 +1111,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest004, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest005, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1143,7 +1133,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest005, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest006, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, false, RANDOM_TOKENID); @@ -1165,7 +1155,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest006, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest007, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, true, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1188,8 +1178,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest007, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest008, TestSize.Level1) { - EXPECT_EQ(0, SetSelfTokenID(g_nativeToken)); - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, true, RANDOM_TOKENID); @@ -1212,7 +1201,7 @@ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest008, TestSize.Level1) */ HWTEST_F(PermissionRecordManagerTest, SetMutePolicyTest009, TestSize.Level1) { - uint32_t tokenID = AccessTokenKit::GetNativeTokenId("edm"); + uint32_t tokenID = PrivacyTestCommon::GetNativeTokenIdFromProcess("edm"); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::EDM, CallerType::MICROPHONE, false, tokenID); PermissionRecordManager::GetInstance().SetMutePolicy(PolicyType::PRIVACY, CallerType::MICROPHONE, false, RANDOM_TOKENID); @@ -1267,17 +1256,19 @@ HWTEST_F(PermissionRecordManagerTest, ProxyDeathTest001, TestSize.Level1) init.TestDie(CALLER_PID); ASSERT_EQ(0, PermissionRecordManager::GetInstance().startRecordList_.size()); - AccessTokenID tokenId1 = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId1); + AccessTokenID tokenId1 = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId1); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId1, TEST_PID_1, permissionName), CALLER_PID)); - AccessTokenID tokenId2 = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, - g_InfoParms2.instIndex); - ASSERT_NE(static_cast(0), tokenId2); + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, + g_InfoParms1.instIndex); + AccessTokenID tokenId2 = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId2); ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId2, TEST_PID_2, permissionName), CALLER_PID)); @@ -1300,17 +1291,19 @@ HWTEST_F(PermissionRecordManagerTest, ProxyDeathTest002, TestSize.Level1) DiedProxyMaker init; init.AddRecipient(CALLER_PID); init.TestDie(CALLER_PID); - AccessTokenID tokenId1 = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId1); + AccessTokenID tokenId1 = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId1); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId1, TEST_PID_1, permissionName), CALLER_PID)); - AccessTokenID tokenId2 = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, - g_InfoParms2.instIndex); - ASSERT_NE(static_cast(0), tokenId2); + tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, + g_InfoParms1.instIndex); + AccessTokenID tokenId2 = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId2); ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( MakeInfo(tokenId2, TEST_PID_2, permissionName), CALLER_PID2)); @@ -1336,9 +1329,10 @@ HWTEST_F(PermissionRecordManagerTest, HasCallerInStartList001, TestSize.Level1) DiedProxyMaker init; init.AddRecipient(CALLER_PID); init.TestDie(CALLER_PID); - AccessTokenID tokenId1 = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - ASSERT_NE(static_cast(0), tokenId1); + AccessTokenID tokenId1 = tokenIdEx.tokenIdExStruct.tokenID; + ASSERT_NE(INVALID_TOKENID, tokenId1); std::string permissionName = "ohos.permission.CAMERA"; ASSERT_EQ(RET_SUCCESS, PermissionRecordManager::GetInstance().StartUsingPermission( diff --git a/services/privacymanager/test/unittest/privacy_manager_service_test.cpp b/services/privacymanager/test/unittest/privacy_manager_service_test.cpp index 4c656c9eb8f4b303d4c91d3eb56fe2bb63a687cd..0632d4849137b5249fd8cfefb01381914b4901d2 100644 --- a/services/privacymanager/test/unittest/privacy_manager_service_test.cpp +++ b/services/privacymanager/test/unittest/privacy_manager_service_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -27,6 +27,7 @@ #include "privacy_error.h" #include "privacy_field_const.h" #include "privacy_manager_service.h" +#include "privacy_test_common.h" #include "proxy_death_callback_stub.h" #include "state_change_callback.h" #include "string_ex.h" @@ -38,11 +39,11 @@ namespace OHOS { namespace Security { namespace AccessToken { namespace { +static AccessTokenID g_selfTokenId = 0; static constexpr int32_t PERMISSION_USAGE_RECORDS_MAX_NUM = 10; constexpr const char* CAMERA_PERMISSION_NAME = "ohos.permission.CAMERA"; constexpr const char* MICROPHONE_PERMISSION_NAME = "ohos.permission.MICROPHONE"; constexpr const char* LOCATION_PERMISSION_NAME = "ohos.permission.LOCATION"; -static AccessTokenIDEx g_tokenID = {0}; static PermissionStateFull g_testState = { .permissionName = "ohos.permission.CAMERA", .isGeneral = true, @@ -65,20 +66,6 @@ static HapInfoParams g_InfoParms1 = { .appIDDesc = "privacy_test.bundleA", .isSystemApp = true }; - -static HapPolicyParams g_PolicyPrams2 = { - .apl = APL_NORMAL, - .domain = "test.domain.B", - .permList = {}, - .permStateList = {g_testState} -}; - -static HapInfoParams g_InfoParms2 = { - .userID = 1, - .bundleName = "ohos.privacy_test.bundleB", - .instIndex = 0, - .appIDDesc = "privacy_test.bundleB" -}; } class PrivacyManagerServiceTest : public testing::Test { @@ -91,15 +78,17 @@ public: void TearDown(); std::shared_ptr privacyManagerService_; - uint64_t selfTokenId_; }; void PrivacyManagerServiceTest::SetUpTestCase() { + g_selfTokenId = GetSelfTokenID(); + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); } void PrivacyManagerServiceTest::TearDownTestCase() { + PrivacyTestCommon::ResetTestEvironment(); } void PrivacyManagerServiceTest::SetUp() @@ -107,23 +96,18 @@ void PrivacyManagerServiceTest::SetUp() privacyManagerService_ = DelayedSingleton::GetInstance(); PermissionRecordManager::GetInstance().Register(); EXPECT_NE(nullptr, privacyManagerService_); - g_tokenID = AccessTokenKit::AllocHapToken(g_InfoParms1, g_PolicyPrams1); - AccessTokenKit::AllocHapToken(g_InfoParms2, g_PolicyPrams2); - selfTokenId_ = GetSelfTokenID(); + + PrivacyTestCommon::AllocTestHapToken(g_InfoParms1, g_PolicyPrams1); } void PrivacyManagerServiceTest::TearDown() { - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle(g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - AccessTokenKit::DeleteToken(tokenId); - privacyManagerService_->RemovePermissionUsedRecords(tokenId); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms2.userID, g_InfoParms2.bundleName, - g_InfoParms2.instIndex); - AccessTokenKit::DeleteToken(tokenId); - privacyManagerService_->RemovePermissionUsedRecords(tokenId); + PrivacyTestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); + privacyManagerService_->RemovePermissionUsedRecords(tokenIdEx.tokenIdExStruct.tokenID); + privacyManagerService_ = nullptr; - EXPECT_EQ(0, SetSelfTokenID(selfTokenId_)); } /** @@ -182,8 +166,9 @@ HWTEST_F(PrivacyManagerServiceTest, Dump002, TestSize.Level1) { int32_t fd = 1; // 1: std output std::vector args; - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::AllocTestHapToken(g_InfoParms1, g_PolicyPrams1); + + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; args.emplace_back(Str8ToStr16("-t")); std::string tokenIdStr = std::to_string(tokenId); args.emplace_back(Str8ToStr16(tokenIdStr)); @@ -214,11 +199,12 @@ HWTEST_F(PrivacyManagerServiceTest, Dump002, TestSize.Level1) */ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission001, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetNativeTokenId("privacy_service"); - ASSERT_NE(INVALID_TOKENID, tokenId); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + MockNativeToken mock("privacy_service"); + + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(tokenId, MICROPHONE_PERMISSION_NAME, -1)); ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(tokenId, LOCATION_PERMISSION_NAME, -1)); @@ -243,7 +229,7 @@ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission001, TestSize.Level1 */ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission002, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetNativeTokenId("privacy_service"); + AccessTokenID tokenId = PrivacyTestCommon::GetNativeTokenIdFromProcess("privacy_service"); // invalid tokenId ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(0, CAMERA_PERMISSION_NAME, -1)); @@ -251,8 +237,9 @@ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission002, TestSize.Level1 ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(tokenId, CAMERA_PERMISSION_NAME, -1)); // invalid permission - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); + tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(tokenId, "test", -1)); } @@ -265,10 +252,10 @@ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission002, TestSize.Level1 */ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermission003, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetNativeTokenId("privacy_service"); + AccessTokenIDEx tokenIdEx = PrivacyTestCommon::GetHapTokenIdFromBundle( + g_InfoParms1.userID, g_InfoParms1.bundleName, g_InfoParms1.instIndex); - tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); + AccessTokenID tokenId = tokenIdEx.tokenIdExStruct.tokenID; ASSERT_NE(INVALID_TOKENID, tokenId); ASSERT_EQ(false, privacyManagerService_->IsAllowedUsingPermission(tokenId, CAMERA_PERMISSION_NAME, -1)); } @@ -432,10 +419,8 @@ HWTEST_F(PrivacyManagerServiceTest, AddPermissionUsedRecordInner002, TestSize.Le MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("AddPermissionUsedRecordInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); AddPermParamInfoParcel infoParcel; @@ -468,8 +453,8 @@ HWTEST_F(PrivacyManagerServiceTest, AddPermissionUsedRecordInner003, TestSize.Le MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("AddPermissionUsedRecordInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); AddPermParamInfoParcel infoParcel; @@ -524,10 +509,8 @@ HWTEST_F(PrivacyManagerServiceTest, SetPermissionUsedRecordToggleStatusInner002, MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("SetPermissionUsedRecordToggleStatusInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteInt32(userID)); @@ -577,10 +560,8 @@ HWTEST_F(PrivacyManagerServiceTest, GetPermissionUsedRecordToggleStatusInner002, MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("SetPermissionUsedRecordToggleStatusInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteInt32(userID)); @@ -637,10 +618,8 @@ HWTEST_F(PrivacyManagerServiceTest, StartUsingPermissionInner002, TestSize.Level MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("StartUsingPermissionInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); PermissionUsedTypeInfoParcel parcel; @@ -670,8 +649,8 @@ HWTEST_F(PrivacyManagerServiceTest, StartUsingPermissionInner003, TestSize.Level MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("StartUsingPermissionInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); PermissionUsedTypeInfoParcel parcel; @@ -718,8 +697,8 @@ HWTEST_F(PrivacyManagerServiceTest, StartUsingPermissionCallbackInner001, TestSi MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("StartUsingPermissionCallbackInner001", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); PermissionUsedTypeInfoParcel parcel; @@ -813,10 +792,8 @@ HWTEST_F(PrivacyManagerServiceTest, StopUsingPermissionInner002, TestSize.Level1 MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("StopUsingPermissionInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(tokenID)); @@ -843,8 +820,8 @@ HWTEST_F(PrivacyManagerServiceTest, StopUsingPermissionInner003, TestSize.Level1 MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("StopUsingPermissionInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(tokenID)); @@ -893,9 +870,9 @@ HWTEST_F(PrivacyManagerServiceTest, RemovePermissionUsedRecordsInner002, TestSiz MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID nativeTokenID = AccessTokenKit::GetNativeTokenId("device_manager"); + MockNativeToken mock("device_manager"); // set self tokenID to native device_manager + AccessTokenID nativeTokenID = GetSelfTokenID(); ASSERT_NE(nativeTokenID, static_cast(0)); - SetSelfTokenID(nativeTokenID); // set self tokenID to native device_manager ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(tokenID)); @@ -945,10 +922,8 @@ HWTEST_F(PrivacyManagerServiceTest, GetPermissionUsedRecordsInner002, TestSize.L MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("GetPermissionUsedRecordsInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteParcelable(&request)); @@ -974,8 +949,8 @@ HWTEST_F(PrivacyManagerServiceTest, GetPermissionUsedRecordsInner003, TestSize.L MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("GetPermissionUsedRecordsInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteParcelable(&request)); @@ -1033,10 +1008,8 @@ HWTEST_F(PrivacyManagerServiceTest, RegisterPermActiveStatusCallbackInner002, Te MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("RegisterPermActiveStatusCallbackInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(permList.size())); @@ -1059,8 +1032,8 @@ HWTEST_F(PrivacyManagerServiceTest, RegisterPermActiveStatusCallbackInner003, Te MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("RegisterPermActiveStatusCallbackInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(0)); @@ -1102,10 +1075,8 @@ HWTEST_F(PrivacyManagerServiceTest, UnRegisterPermActiveStatusCallbackInner002, MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("UnRegisterPermActiveStatusCallbackInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(RET_SUCCESS, testSub.OnRemoteRequest(static_cast( @@ -1127,8 +1098,8 @@ HWTEST_F(PrivacyManagerServiceTest, UnRegisterPermActiveStatusCallbackInner003, MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - ASSERT_NE(g_tokenID.tokenIDEx, static_cast(0)); - SetSelfTokenID(g_tokenID.tokenIDEx); // set self tokenID to system app + std::vector reqPerm; + MockHapToken mock("UnRegisterPermActiveStatusCallbackInner003", reqPerm, true); // set self tokenID to system app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(RET_SUCCESS, testSub.OnRemoteRequest(static_cast( @@ -1178,10 +1149,8 @@ HWTEST_F(PrivacyManagerServiceTest, IsAllowedUsingPermissionInner002, TestSize.L MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - AccessTokenID hapTokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - ASSERT_NE(hapTokenID, static_cast(0)); - SetSelfTokenID(hapTokenID); // set self tokenID to hapTokenID + std::vector reqPerm; + MockHapToken mock("IsAllowedUsingPermissionInner002", reqPerm, false); // set self tokenID to normal app ASSERT_EQ(true, data.WriteInterfaceToken(IPrivacyManager::GetDescriptor())); ASSERT_EQ(true, data.WriteUint32(tokenID)); diff --git a/services/privacymanager/test/unittest/sensitive_manager_test.cpp b/services/privacymanager/test/unittest/sensitive_manager_test.cpp index cf5010c4202242e69f4f721de02679392f3a01c0..b388e55c35c646143ed5e52ebdad4208365f3ad3 100644 --- a/services/privacymanager/test/unittest/sensitive_manager_test.cpp +++ b/services/privacymanager/test/unittest/sensitive_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2025 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 @@ -27,6 +27,7 @@ #endif #include "camera_manager_adapter.h" #include "permission_record_manager.h" +#include "privacy_test_common.h" #include "token_setproc.h" using namespace testing::ext; @@ -41,6 +42,7 @@ public: void SetUp(); void TearDown(); }; +static MockHapToken* g_mock = nullptr; static AccessTokenID g_selfTokenId = 0; static PermissionStateFull g_testState1 = { .permissionName = "ohos.permission.RUNNING_STATE_OBSERVER", @@ -106,28 +108,32 @@ static HapInfoParams g_infoManagerTestSystemInfoParms = { void SensitiveManagerServiceTest::SetUpTestCase() { g_selfTokenId = GetSelfTokenID(); + PrivacyTestCommon::SetTestEvironment(g_selfTokenId); + + std::vector reqPerm; + reqPerm.emplace_back("ohos.permission.RUNNING_STATE_OBSERVER"); + reqPerm.emplace_back("ohos.permission.MANAGE_CAMERA_CONFIG"); + reqPerm.emplace_back("ohos.permission.GET_RUNNING_INFO"); + reqPerm.emplace_back("ohos.permission.MANAGE_AUDIO_CONFIG"); + reqPerm.emplace_back("ohos.permission.MICROPHONE_CONTROL"); + g_mock = new (std::nothrow) MockHapToken("SensitiveManagerServiceTest", reqPerm); } void SensitiveManagerServiceTest::TearDownTestCase() { + if (g_mock != nullptr) { + delete g_mock; + g_mock = nullptr; + } + PrivacyTestCommon::ResetTestEvironment(); } void SensitiveManagerServiceTest::SetUp() { - AccessTokenKit::AllocHapToken(g_InfoParms1, g_PolicyPrams1); - AccessTokenID tokenId = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, - g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); } void SensitiveManagerServiceTest::TearDown() { - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_InfoParms1.userID, - g_InfoParms1.bundleName, - g_InfoParms1.instIndex); - AccessTokenKit::DeleteToken(tokenID); - EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); } /* @@ -150,8 +156,8 @@ HWTEST_F(SensitiveManagerServiceTest, RegisterAppObserverTest001, TestSize.Level */ HWTEST_F(SensitiveManagerServiceTest, RegisterAppObserverTest002, TestSize.Level1) { - AccessTokenID tokenId = AccessTokenKit::GetNativeTokenId("privacy_service"); - EXPECT_EQ(0, SetSelfTokenID(tokenId)); + MockNativeToken("privacy_service"); + AccessTokenID tokenId = GetSelfTokenID(); sptr listener = new(std::nothrow) ApplicationStateObserverStub(); ASSERT_NE(listener, nullptr); diff --git a/services/tokensyncmanager/test/coverage/BUILD.gn b/services/tokensyncmanager/test/coverage/BUILD.gn index 5ddfb2d6f65e75f7571edd5316615e6ff6099d97..363745110e3c4f34998d3ec5808e760d500c51fc 100644 --- a/services/tokensyncmanager/test/coverage/BUILD.gn +++ b/services/tokensyncmanager/test/coverage/BUILD.gn @@ -26,6 +26,7 @@ ohos_unittest("libtoken_sync_service_coverage_test") { branch_protector_ret = "pac_ret" sources = [ + "${access_token_path}/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp", "../../src/command/base_remote_command.cpp", "../../src/command/delete_remote_token_command.cpp", "../../src/command/sync_remote_hap_token_command.cpp", @@ -63,6 +64,7 @@ ohos_unittest("libtoken_sync_service_coverage_test") { "${access_token_path}/services/accesstokenmanager/main/cpp/include/token", "${access_token_path}/services/common/json_parse/include", "${access_token_path}/services/common/handler/include", + "${access_token_path}/interfaces/innerkits/accesstoken/test/unittest/common/", ] deps = [ diff --git a/services/tokensyncmanager/test/coverage/token_sync_service_coverage_test.cpp b/services/tokensyncmanager/test/coverage/token_sync_service_coverage_test.cpp index 057c63a00289c9f74c60f2a17f3a0ca2d2c9dc7c..c464d8a7eab130884b16ce69a896a64dcbc074da 100644 --- a/services/tokensyncmanager/test/coverage/token_sync_service_coverage_test.cpp +++ b/services/tokensyncmanager/test/coverage/token_sync_service_coverage_test.cpp @@ -45,6 +45,7 @@ #include "socket.h" #include "soft_bus_device_connection_listener.h" #include "soft_bus_socket_listener.h" +#include "test_common.h" #include "token_setproc.h" #include "token_sync_manager_stub.h" @@ -93,7 +94,7 @@ TokenSyncServiceTest::~TokenSyncServiceTest() void NativeTokenGet() { uint64_t tokenId = 0; - tokenId = AccessTokenKit::GetNativeTokenId("token_sync_service"); + tokenId = TestCommon::GetNativeTokenIdFromProcess("token_sync_service"); ASSERT_NE(tokenId, static_cast(0)); EXPECT_EQ(0, SetSelfTokenID(tokenId)); } @@ -102,10 +103,14 @@ void TokenSyncServiceTest::SetUpTestCase() { g_selfUid = getuid(); g_selfTokenId = GetSelfTokenID(); + TestCommon::SetTestEvironment(g_selfTokenId); NativeTokenGet(); } void TokenSyncServiceTest::TearDownTestCase() -{} +{ + SetSelfTokenID(g_selfTokenId); + TestCommon::ResetTestEvironment(); +} void TokenSyncServiceTest::SetUp() { tokenSyncManagerService_ = DelayedSingleton::GetInstance(); diff --git a/services/tokensyncmanager/test/unittest/BUILD.gn b/services/tokensyncmanager/test/unittest/BUILD.gn index 7c224502045d6d3317806caf54dfa81dd849c2a9..7cd426c7b1865abca8ac239110c64056d6708cd4 100644 --- a/services/tokensyncmanager/test/unittest/BUILD.gn +++ b/services/tokensyncmanager/test/unittest/BUILD.gn @@ -26,6 +26,7 @@ ohos_unittest("libtoken_sync_service_standard_test") { branch_protector_ret = "pac_ret" sources = [ + "${access_token_path}/interfaces/innerkits/accesstoken/test/unittest/common/test_common.cpp", "../../src/command/base_remote_command.cpp", "../../src/command/delete_remote_token_command.cpp", "../../src/command/sync_remote_hap_token_command.cpp", @@ -63,6 +64,7 @@ ohos_unittest("libtoken_sync_service_standard_test") { "${access_token_path}/services/accesstokenmanager/main/cpp/include/token", "${access_token_path}/services/common/json_parse/include", "${access_token_path}/services/common/handler/include", + "${access_token_path}/interfaces/innerkits/accesstoken/test/unittest/common/", ] deps = [ diff --git a/services/tokensyncmanager/test/unittest/token_sync_service_test.cpp b/services/tokensyncmanager/test/unittest/token_sync_service_test.cpp index be54f37349f40a7bb3fb2e3cf4164699fe4dedf2..eeeab26ddc6c8ecf65a0a8a6632db3fd76ad4af7 100644 --- a/services/tokensyncmanager/test/unittest/token_sync_service_test.cpp +++ b/services/tokensyncmanager/test/unittest/token_sync_service_test.cpp @@ -46,6 +46,7 @@ #include "socket.h" #include "soft_bus_device_connection_listener.h" #include "soft_bus_socket_listener.h" +#include "test_common.h" #include "token_setproc.h" #include "token_sync_manager_stub.h" @@ -98,7 +99,7 @@ TokenSyncServiceTest::~TokenSyncServiceTest() void NativeTokenGet() { uint64_t tokenId = 0; - tokenId = AccessTokenKit::GetNativeTokenId("token_sync_service"); + tokenId = TestCommon::GetNativeTokenIdFromProcess("token_sync_service"); ASSERT_NE(tokenId, static_cast(0)); EXPECT_EQ(0, SetSelfTokenID(tokenId)); } @@ -107,10 +108,15 @@ void TokenSyncServiceTest::SetUpTestCase() { g_selfUid = getuid(); g_selfTokenId = GetSelfTokenID(); + TestCommon::SetTestEvironment(g_selfTokenId); + NativeTokenGet(); } void TokenSyncServiceTest::TearDownTestCase() -{} +{ + SetSelfTokenID(g_selfTokenId); + TestCommon::ResetTestEvironment(); +} void TokenSyncServiceTest::SetUp() { tokenSyncManagerService_ = DelayedSingleton::GetInstance(); @@ -253,15 +259,13 @@ public: static void DeleteAndAllocToken(AccessTokenID& tokenId) { // create local token - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, + AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(g_infoManagerTestInfoParms.userID, g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); - AccessTokenKit::DeleteToken(tokenID); - - AccessTokenIDEx tokenIdEx = {0}; - tokenIdEx = AccessTokenKit::AllocHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams); - ASSERT_NE(static_cast(0), tokenIdEx.tokenIdExStruct.tokenID); + TestCommon::DeleteTestHapToken(tokenIdEx.tokenIdExStruct.tokenID); - tokenId = tokenIdEx.tokenIdExStruct.tokenID; + AccessTokenIDEx tokenIdEx1 = {0}; + TestCommon::AllocTestHapToken(g_infoManagerTestInfoParms, g_infoManagerTestPolicyPrams, tokenIdEx1); + ASSERT_NE(static_cast(0), tokenIdEx1.tokenIdExStruct.tokenID); } /** @@ -802,10 +806,10 @@ HWTEST_F(TokenSyncServiceTest, GetRemoteHapTokenInfo008, TestSize.Level1) { LOGI(ATM_DOMAIN, ATM_TAG, "GetRemoteHapTokenInfo008 start."); // create local token - AccessTokenID tokenID = AccessTokenKit::GetHapTokenID(g_infoManagerTestInfoParms.userID, - g_infoManagerTestInfoParms.bundleName, - g_infoManagerTestInfoParms.instIndex); - AccessTokenKit::DeleteToken(tokenID); + AccessTokenIDEx tokenIdEx = TestCommon::GetHapTokenIdFromBundle(g_infoManagerTestInfoParms.userID, + g_infoManagerTestInfoParms.bundleName, g_infoManagerTestInfoParms.instIndex); + AccessTokenID tokenID = tokenIdEx.tokenIdExStruct.tokenID; + TestCommon::DeleteTestHapToken(tokenID); // tokenID is not exist std::string jsonBefore =