diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..58080d8750b729b6f7ab316c7b8a670d0741ef81 --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 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("//build/ohos.gni") + +group("security_component_build_module") { + if (is_standard_system) { + deps = [ + "interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + "interfaces/inner_api/security_component:libsecurity_component_sdk", + "services/security_component_service/sa:security_component_service", + "services/security_component_service/sa/sa_profile:security_component_sa_profile_standard", + ] + } +} + +group("security_component_build_module_test") { + testonly = true + deps = [] + if (is_standard_system) { + deps += [ + "interfaces/inner_api/enhance_kits/test:unittest", + "interfaces/inner_api/security_component/test:unittest", + "services/security_component_service/sa/test:unittest", + ] + } +} + +group("security_component_build_fuzz_test") { + testonly = true + deps = [] + if (is_standard_system) { + deps += [ + "test/fuzztest/security_component:fuzztest", + ] + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4a459866a57c25462afad17f3fe0b50d440da080 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 5ce308bef2a03f37674bdcaefb3fa2a47acc8ef2..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# security_component - -null \ No newline at end of file diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..141edb1bece8abd4c986af7b010360f6e2d92dc4 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,47 @@ +# 安全控件管理服务 + +## 简介 + +安全控件是OpenHarmony提供的一组系统实现的ArkUI基础组件。当用户点击了这类组件后,应用将被授予临时授权,应用开发者仅需要像使用Button等组件那样集成到应用自己的页面即可。 +安全控件管理服务主要提供如下功能: + +- 提供应用安全控件的注册、临时授权、取消注册等Native接口实现。 +- 负责安全控件的合法性检查,只有合法的安全控件才能授权成功。 +- 提供其他SA查询临时授权的Native接口实现。提供安全增强相关接口及适配层,供厂商定制安全增强功能使用。 + +## 目录 + +``` +/base/security/security_component +├── frameworks # 框架层,基础功能代码存放目录 +│ ├── common # 框架公共代码存放目录 +│ ├── enhance_adapter # 能力增强适配代码存放目录 +│ └── security_component # 安全控件服务框架代码存放目录 +├── interfaces # 接口层 +│ └── inner_api # 内部接口层 +│ ├── enhance_kits # 安全控件配置接口代码存放目录 +│ └── security_component # 安全控件服务接口层代码存放目录 +└── services # 服务层 + └── security_component_service/sa + └── sa_main # 安全控件服务侧代码存放目录 + +``` + +## 使用 +### 接口说明 + +| **接口申明** | **接口描述** | +| --- | --- | +| int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId); | 注册安全控件 | +| int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo); | 更新安全控件信息 | +| int32_t UnregisterSecurityComponent(int32_t scId); | 取消注册安全控件 | +| int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, const SecCompClickEvent& touchInfo); | 上报点击事件,申请临时授权 | +| int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); | 设置安全控件增强的配置,供多模服务使用 | +| int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, uint8_t* enhanceData, uint32_t& enHancedataLen); | 获取点击事件的安全增强数据,供多模服务使用 | +| bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); | 校验后取消保存控件权限 | + +## 相关仓 + +**[arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine/blob/master/README_zh.md)** + +**[multimodalinput\_input](https://gitee.com/openharmony/multimodalinput_input/blob/master/README_zh.md)** diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..f9134f4ea7e0f1d30d59bd1757d789d68d15f111 --- /dev/null +++ b/bundle.json @@ -0,0 +1,106 @@ +{ + "name": "@openharmony/security_component", + "description": "security_component", + "version": "4.0.0", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "base/security/security_component" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "security_component", + "subsystem": "security", + "syscap": [], + "hisysevent_config": [ + "//base/security/security_component/hisysevent.yaml" + ], + "features": [ "security_component_feature_coverage = false" ], + "adapted_system_type": [ + "standard" + ], + "rom": "2048KB", + "ram": "5102KB", + "deps": { + "components": [ + "ability_base", + "ability_runtime", + "access_token", + "c_utils", + "eventhandler", + "hilog", + "hisysevent", + "hitrace", + "graphic_2d", + "ipc", + "safwk", + "samgr", + "window_manager" + ], + "third_party": [ + "cJSON", + "googletest" + ] + }, + "build": { + "sub_component": [ + "//base/security/security_component:security_component_build_module" + ], + "inner_kits": [ + { + "name": "//base/security/security_component/interfaces/inner_api/security_component:libsecurity_component_sdk", + "header": { + "header_files": [ + "i_sec_comp_probe.h", + "sec_comp_kit.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/security_component/include" + } + }, + { + "name": "//base/security/security_component/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + "header": { + "header_files": [ + "sec_comp_enhance_kit.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/enhance_kits/include" + } + }, + { + "name": "//base/security/security_component/frameworks:libsecurity_component_framework", + "header": { + "header_files": [ + "location_button.h", + "paste_button.h", + "save_button.h" + ], + "header_base": "//base/security/security_component/interfaces/inner_api/security_component/include" + } + }, + { + "name": "//base/security/security_component/frameworks:libsecurity_component_enhance_adapter", + "header": { + "header_files": [ + "sec_comp_enhance_adapter.h" + ], + "header_base": "//base/security/security_component/frameworks/enhance_adapter/include" + } + }, + { + "name": "//base/security/security_component/services/security_component_service/sa:security_component_service", + "header": { + "header_files": [ + "sec_comp_manager.h" + ], + "header_base": "//base/security/security_component/services/security_component_service/sa/sa_main" + } + } + ], + "test": [ + "//base/security/security_component:security_component_build_module_test", + "//base/security/security_component:security_component_build_fuzz_test" + ] + } + } +} diff --git a/config/BUILD.gn b/config/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9cf755498a2f8653a6faf5b583296483493faf47 --- /dev/null +++ b/config/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 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. + +declare_args() { + security_component_feature_coverage = false +} + +config("coverage_flags") { + if (security_component_feature_coverage) { + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + } +} diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..866b79a515ce770466828e46393575776d5dfe74 --- /dev/null +++ b/frameworks/BUILD.gn @@ -0,0 +1,94 @@ +# Copyright (c) 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("//build/ohos.gni") + +sec_comp_root_dir = ".." + +config("libsecurity_component_framework_config") { + include_dirs = [ + "common/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] +} + +ohos_shared_library("libsecurity_component_framework") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_framework" + + include_dirs = [ + "common/include", + "security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + ] + + sources = [ + "common/src/sec_comp_tool.cpp", + "security_component/src/location_button.cpp", + "security_component/src/paste_button.cpp", + "security_component/src/save_button.cpp", + "security_component/src/sec_comp_base.cpp", + "security_component/src/sec_comp_click_event_parcel.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":libsecurity_component_framework_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} + +config("libsecurity_component_enhance_adapter_config") { + include_dirs = [ + "common/include", + "enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include" + ] +} + +ohos_shared_library("libsecurity_component_enhance_adapter") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_enhance_adapter" + + include_dirs = [ + "common/include", + "enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include" + ] + + sources = [ "enhance_adapter/src/sec_comp_enhance_adapter.cpp" ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":libsecurity_component_enhance_adapter_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + + if (current_cpu == "arm64") { + defines = [ "_ARM64_" ] + } +} diff --git a/frameworks/common/include/sec_comp_err.h b/frameworks/common/include/sec_comp_err.h new file mode 100644 index 0000000000000000000000000000000000000000..8cacb68c3e7bc94f9d77bf292a238885ba056370 --- /dev/null +++ b/frameworks/common/include/sec_comp_err.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 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. + */ +#ifndef FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H +#define FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum SCErrCode : int32_t { + SC_OK = 0, + + SC_SERVICE_ERROR_VALUE_INVALID = -50, + SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL = -51, + SC_SERVICE_ERROR_MEMORY_OPERATE_FAIL = -52, + SC_SERVICE_ERROR_IPC_REQUEST_FAIL = -54, + SC_SERVICE_ERROR_SERVICE_NOT_EXIST = -55, + SC_SERVICE_ERROR_COMPONENT_INFO_INVALID = -56, + SC_SERVICE_ERROR_COMPONENT_RECT_OVERLAP = -57, + SC_SERVICE_ERROR_COMPONENT_NOT_EXIST = -58, + SC_SERVICE_ERROR_PERMISSION_OPER_FAIL = -59, + SC_SERVICE_ERROR_CLICK_EVENT_INVALID = -60, + SC_SERVICE_ERROR_COMPONENT_INFO_NOT_EQUAL = -61, + SC_SERVICE_ERROR_CALLER_INVALID = -62, + + SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE = -100, + SC_ENHANCE_ERROR_VALUE_INVALID = -101, + SC_ENHANCE_ERROR_OPER_FAIL = -102, + SC_ENHANCE_ERROR_CALLBACK_REDIRECT = -103, + SC_ENHANCE_ERROR_CALLBACK_REGIST_FAIL = -104, + SC_ENHANCE_ERROR_CALLBACK_HAS_EXIST = -105, + SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST = -106, + SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL = -107, + SC_ENHANCE_ERROR_CALLBACK_CHECK_FAIL = -108, + SC_ENHANCE_ERROR_IN_MALICIOUS_LIST = -109, + SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL = -110 +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // FRAMEWORKS_COMMON_SECURITY_COMPONENT_ERR_H diff --git a/frameworks/common/include/sec_comp_log.h b/frameworks/common/include/sec_comp_log.h new file mode 100644 index 0000000000000000000000000000000000000000..71ab8015292daf7f0c2ffee056c31b11b4818f0b --- /dev/null +++ b/frameworks/common/include/sec_comp_log.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_LOG_H +#define SECURITY_COMPONENT_LOG_H + +#ifdef HILOG_ENABLE + +#include "hilog/log.h" + +#ifndef __cplusplus + +#undef LOG_DOMAIN +#define LOG_DOMAIN 0xD002F07 + +#define SC_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#else + +static constexpr unsigned int SECURITY_DOMAIN_SECURITY_COMPONENT = 0xD002F07; + +#define SC_LOG_DEBUG(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Debug(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(label, fmt, ...) OHOS::HiviewDFX::HiLog::Info(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(label, fmt, ...) OHOS::HiviewDFX::HiLog::Warn(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Error(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Fatal(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) + +#endif // __cplusplus + +#else + +#include + +#undef LOG_TAG + +#define SC_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) +#define SC_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__) + +#endif // HILOG_ENABLE + +#endif // SECURITY_COMPONENT_LOG_H diff --git a/frameworks/common/include/sec_comp_tool.h b/frameworks/common/include/sec_comp_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..197f67d529f7d0d79e8eeb900524610e49e9d210 --- /dev/null +++ b/frameworks/common/include/sec_comp_tool.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_TOOL_H +#define SECURITY_COMPONENT_TOOL_H + +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { + bool IsColorSimilar(const SecCompColor& color1, const SecCompColor& color2); + bool IsColorTransparent(const SecCompColor& color); +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_TOOL_H diff --git a/frameworks/common/src/sec_comp_tool.cpp b/frameworks/common/src/sec_comp_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36d45c48948721d9a33807f34c346408f4cd7683 --- /dev/null +++ b/frameworks/common/src/sec_comp_tool.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_tool.h" + +#include +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr double PI_CIRCLE = 3.1415926; +static constexpr double MIN_HSV_DISTANCE = 25.0; +static constexpr double MAX_RGB_VALUE = 255.0; +static constexpr uint8_t MAX_TRANSPARENT = 0x99; // 60% +static constexpr double ZERO_DOUBLE = 0.0; +static constexpr double THIRTY_ANGLE = 30.0; +static constexpr double SIXTY_ANGLE = 60.0; +static constexpr double ONE_HUNDRED_TWEENTY_ANGLE = 120.0; +static constexpr double ONE_HUNDRED_EIGHTY_ANGLE = 180.0; +static constexpr double TWO_HUNDREDS_FORTY_ANGLE = 240.0; +static constexpr double THREE_HUNDREDS_SIXTY_ANGLE = 360.0; +static constexpr double DEFAULT_R = 100.0; + +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompTool"}; +} + +static inline double MaxValue(double a, double b, double c) +{ + return ((a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c)); +} + +static inline double MinValue(double a, double b, double c) +{ + return ((a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c)); +} + +struct HsvColor { + double h; + double s; + double v; +}; + +static HsvColor RgbToHsv(uint8_t r, uint8_t g, uint8_t b) +{ + HsvColor hsv; + double red = static_cast(r) / MAX_RGB_VALUE; + double green = static_cast(g) / MAX_RGB_VALUE; + double blue = static_cast(b) / MAX_RGB_VALUE; + double max = MaxValue(red, green, blue); + double min = MinValue(red, green, blue); + double delta = max - min; + if (max == min) { + hsv.h = ZERO_DOUBLE; + } else if (max == red) { + hsv.h = fmod((SIXTY_ANGLE * ((green - blue) / delta) + THREE_HUNDREDS_SIXTY_ANGLE), + THREE_HUNDREDS_SIXTY_ANGLE); + } else if (max == green) { + hsv.h = fmod((SIXTY_ANGLE * ((blue - red) / delta) + ONE_HUNDRED_TWEENTY_ANGLE), THREE_HUNDREDS_SIXTY_ANGLE); + } else if (max == blue) { + hsv.h = fmod((SIXTY_ANGLE * ((red - green) / delta) + TWO_HUNDREDS_FORTY_ANGLE), THREE_HUNDREDS_SIXTY_ANGLE); + } + + if (max == 0) { + hsv.s = ZERO_DOUBLE; + } else { + hsv.s = delta / max; + } + + hsv.v = max; + return hsv; +} + +static inline double GetHsvDisX(const HsvColor& hsv, double r) +{ + return r * hsv.v * hsv.s * cos(hsv.h / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); +} + +static inline double GetHsvDisY(const HsvColor& hsv, double r) +{ + return r * hsv.v * hsv.s * sin(hsv.h / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); +} + +static inline double GetHsvDisZ(const HsvColor& hsv, double h) +{ + return h * (1 - hsv.v); +} + +static double HsvDistance(const HsvColor& hsv1, const HsvColor& hsv2) +{ + double rDef = DEFAULT_R; + double angle = THIRTY_ANGLE; + double h = rDef * cos(angle / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); + double r = rDef * sin(angle / ONE_HUNDRED_EIGHTY_ANGLE * PI_CIRCLE); + + double x1 = GetHsvDisX(hsv1, r); + double y1 = GetHsvDisY(hsv1, r); + double z1 = GetHsvDisZ(hsv1, h); + + double x2 = GetHsvDisX(hsv2, r); + double y2 = GetHsvDisY(hsv2, r); + double z2 = GetHsvDisZ(hsv2, h); + + double dx = x1 - x2; + double dy = y1 - y2; + double dz = z1 - z2; + + return sqrt((dx * dx) + (dy * dy) + (dz * dz)); +} + +bool IsColorSimilar(const SecCompColor& color1, const SecCompColor& color2) +{ + HsvColor hsv1 = RgbToHsv(color1.argb.red, color1.argb.green, color1.argb.blue); + HsvColor hsv2 = RgbToHsv(color2.argb.red, color2.argb.green, color2.argb.blue); + + double distance = HsvDistance(hsv1, hsv2); + SC_LOG_DEBUG(LABEL, "Compare color %{public}x %{public}x distance %{public}f", + color1.value, color2.value, distance); + return (distance < MIN_HSV_DISTANCE); +} + +bool IsColorTransparent(const SecCompColor& color) +{ + SC_LOG_DEBUG(LABEL, "Color %{public}x alpha %{public}x", color.value, color.argb.alpha); + return color.argb.alpha < MAX_TRANSPARENT; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h b/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..faada7e763671088f8072a19ca6852b19ae9b2a5 --- /dev/null +++ b/frameworks/enhance_adapter/include/sec_comp_enhance_adapter.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENHANCE_ADAPTER_H +#define SECURITY_COMPONENT_ENHANCE_ADAPTER_H + +#include +#include "iremote_object.h" +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum EnhanceInterfaceType { + SEC_COMP_ENHANCE_INPUT_INTERFACE = 0, + SEC_COMP_ENHANCE_SRV_INTERFACE = 1, + SEC_COMP_ENHANCE_CLIENT_INTERFACE = 2, +}; + +// for multimodalinput to add enhance data to PointerEvent +class SecCompInputEnhanceInterface { +public: + // for multimodalinput to set enhance cfg which is from security component enhance service + virtual int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) = 0; + + // for multimodalinput to get enhance data + virtual int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) = 0; +}; + +// for security component service to send command to enhance service +class SecCompSrvEnhanceInterface { + public: + // enable input enhance, then enhance service send config to multimodalinput + virtual int32_t EnableInputEnhance() = 0; + + // disable input enhance + virtual int32_t DisableInputEnhance() = 0; + + // send click event to enhance service for checking extra data validity + virtual int32_t CheckExtraInfo(const SecCompClickEvent& touchInfo) = 0; + + // send component info to enhance service for checking its validity + virtual int32_t CheckComponentInfoEnhnace(int32_t pid, std::shared_ptr& compInfo, + const nlohmann::json& jsonComponent) = 0; + + // get RemoteObject of enhance service to connect it + virtual sptr GetEnhanceRemoteObject() = 0; + + // start enhance service + virtual void StartEnhanceService() = 0; + + // exit enhance service + virtual void ExitEnhanceService() = 0; + + // notify process died + virtual void NotifyProcessDied(int32_t pid) = 0; +}; + +// for client +class SecCompClientEnhanceInterface { +public: + // preprocess component info which is send to security component service, e.g. RegisterSecurityComponent + virtual bool EnhanceDataPreprocess(const uintptr_t caller, std::string& componentInfo) = 0; + virtual bool EnhanceDataPreprocess(const uintptr_t caller, int32_t scId, std::string& componentInfo) = 0; + + // regiter scid to enhance client + virtual void RegisterScIdEnhance(const uintptr_t caller, int32_t scId) = 0; + // unregiter scid to enhance client + virtual void UnregisterScIdEnhance(const uintptr_t caller, int32_t scId) = 0; +}; + +class SecCompEnhanceAdapter final { +public: + static void InitEnhanceHandler(EnhanceInterfaceType type); + static int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); + static int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen); + + static int32_t CheckExtraInfo(const SecCompClickEvent& touchInfo); + static int32_t EnableInputEnhance(); + static int32_t DisableInputEnhance(); + static int32_t CheckComponentInfoEnhnace(int32_t pid, std::shared_ptr& compInfo, + const nlohmann::json& jsonComponent); + static sptr GetEnhanceRemoteObject(); + static void StartEnhanceService(); + static void ExistEnhanceService(); + static void NotifyProcessDied(int32_t pid); + + static bool EnhanceDataPreprocess(std::string& componentInfo); + static bool EnhanceDataPreprocess(int32_t scId, std::string& componentInfo); + static void RegisterScIdEnhance(int32_t scId); + static void UnregisterScIdEnhance(int32_t scId); + + static SecCompInputEnhanceInterface* inputHandler; + static bool isEnhanceInputHandlerInit; + + static SecCompSrvEnhanceInterface* srvHandler; + static bool isEnhanceSrvHandlerInit; + + static SecCompClientEnhanceInterface* clientHandler; + static bool isEnhanceClientHandlerInit; + + static std::mutex initMtx; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_ADAPTER_H diff --git a/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp b/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28d1aa9390c46972aa4dc866033be6b073806081 --- /dev/null +++ b/frameworks/enhance_adapter/src/sec_comp_enhance_adapter.cpp @@ -0,0 +1,235 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_enhance_adapter.h" + +#include +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEnhanceAdapter"}; + +#ifdef _ARM64_ +static const std::string LIB_PATH = "/system/lib64/"; +#else +static const std::string LIB_PATH = "/system/lib/"; +#endif +static const std::string ENHANCE_INPUT_INTERFACE_LIB = LIB_PATH + "libsec_comp_input_enhance.z.so"; +static const std::string ENHANCE_SRV_INTERFACE_LIB = LIB_PATH + "libsec_comp_service_enhance.z.so"; +static const std::string ENHANCE_CLIENT_INTERFACE_LIB = LIB_PATH + "libsec_comp_client_enhance.z.so"; +} + +SecCompInputEnhanceInterface* SecCompEnhanceAdapter::inputHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceInputHandlerInit = false; + +SecCompSrvEnhanceInterface* SecCompEnhanceAdapter::srvHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceSrvHandlerInit = false; + +SecCompClientEnhanceInterface* SecCompEnhanceAdapter::clientHandler = nullptr; +bool SecCompEnhanceAdapter::isEnhanceClientHandlerInit = false; + +std::mutex SecCompEnhanceAdapter::initMtx; + +void SecCompEnhanceAdapter::InitEnhanceHandler(EnhanceInterfaceType type) +{ + std::unique_lock lck(initMtx); + std::string libPath = ""; + switch (type) { + case SEC_COMP_ENHANCE_INPUT_INTERFACE: + libPath = ENHANCE_INPUT_INTERFACE_LIB; + isEnhanceInputHandlerInit = true; + break; + case SEC_COMP_ENHANCE_SRV_INTERFACE: + libPath = ENHANCE_SRV_INTERFACE_LIB; + isEnhanceSrvHandlerInit = true; + break; + case SEC_COMP_ENHANCE_CLIENT_INTERFACE: + libPath = ENHANCE_CLIENT_INTERFACE_LIB; + isEnhanceClientHandlerInit = true; + break; + default: + break; + } + if (dlopen(libPath.c_str(), RTLD_LAZY) == nullptr) { + SC_LOG_ERROR(LABEL, "init enhance lib %{public}s failed, error %{public}s", libPath.c_str(), dlerror()); + } +} + +int32_t SecCompEnhanceAdapter::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + if (!isEnhanceInputHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_INPUT_INTERFACE); + } + if (inputHandler != nullptr) { + return inputHandler->SetEnhanceCfg(cfg, cfgLen); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + if (!isEnhanceInputHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_INPUT_INTERFACE); + } + if (inputHandler != nullptr) { + return inputHandler->GetPointerEventEnhanceData(data, dataLen, enhanceData, enHancedataLen); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::CheckExtraInfo(const SecCompClickEvent& touchInfo) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->CheckExtraInfo(touchInfo); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(std::string& componentInfo) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + return clientHandler->EnhanceDataPreprocess(enhanceCallerAddr, componentInfo); + } + return true; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(int32_t scId, std::string& componentInfo) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + return clientHandler->EnhanceDataPreprocess(enhanceCallerAddr, scId, componentInfo); + } + return true; +} + +void SecCompEnhanceAdapter::RegisterScIdEnhance(int32_t scId) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + clientHandler->RegisterScIdEnhance(enhanceCallerAddr, scId); + } +} + +void SecCompEnhanceAdapter::UnregisterScIdEnhance(int32_t scId) +{ + if (!isEnhanceClientHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + } + + uintptr_t enhanceCallerAddr = reinterpret_cast(__builtin_return_address(0)); + if (clientHandler != nullptr) { + clientHandler->UnregisterScIdEnhance(enhanceCallerAddr, scId); + } +} + +int32_t SecCompEnhanceAdapter::EnableInputEnhance() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->EnableInputEnhance(); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +int32_t SecCompEnhanceAdapter::DisableInputEnhance() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->DisableInputEnhance(); + } + return SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE; +} + +void SecCompEnhanceAdapter::StartEnhanceService() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->StartEnhanceService(); + } +} + +void SecCompEnhanceAdapter::ExistEnhanceService() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->ExitEnhanceService(); + } +} + +void SecCompEnhanceAdapter::NotifyProcessDied(int32_t pid) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + srvHandler->NotifyProcessDied(pid); + } +} + +int32_t SecCompEnhanceAdapter::CheckComponentInfoEnhnace(int32_t pid, + std::shared_ptr& compInfo, const nlohmann::json& jsonComponent) +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + return srvHandler->CheckComponentInfoEnhnace(pid, compInfo, jsonComponent); + } + return SC_OK; +} + +sptr SecCompEnhanceAdapter::GetEnhanceRemoteObject() +{ + if (!isEnhanceSrvHandlerInit) { + InitEnhanceHandler(SEC_COMP_ENHANCE_SRV_INTERFACE); + } + if (srvHandler != nullptr) { + auto service = srvHandler->GetEnhanceRemoteObject(); + return service; + } + return nullptr; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/include/sec_comp_click_event_parcel.h b/frameworks/security_component/include/sec_comp_click_event_parcel.h new file mode 100644 index 0000000000000000000000000000000000000000..ea39a20663e668fe1b64fc9971ced8b482546a59 --- /dev/null +++ b/frameworks/security_component/include/sec_comp_click_event_parcel.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_CLICK_INFO_PARCEL_H +#define SECURITY_COMPONENT_CLICK_INFO_PARCEL_H + +#include "parcel.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompClickEventParcel final : public Parcelable { + SecCompClickEventParcel() = default; + + ~SecCompClickEventParcel() override = default; + + bool Marshalling(Parcel& out) const override; + + static SecCompClickEventParcel* Unmarshalling(Parcel& in); + + SecCompClickEvent touchInfoParams_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_CLICK_INFO_PARCEL_H diff --git a/frameworks/security_component/src/location_button.cpp b/frameworks/security_component/src/location_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b62b9e9780b262a0841ab1c1a85f5cf90ae1e7d6 --- /dev/null +++ b/frameworks/security_component/src/location_button.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 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. + */ +#include "location_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "LocationButton"}; +} + +bool LocationButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= LocationDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= LocationIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool LocationButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + LocationButton* otherLocationButton = reinterpret_cast(other); + if (otherLocationButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not location button."); + return false; + } + return (icon_ == otherLocationButton->icon_) && (text_ == otherLocationButton->text_) && + (bg_ == otherLocationButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/paste_button.cpp b/frameworks/security_component/src/paste_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41941dc73233d2f6bb7c7eb6e004a580fdd917e0 --- /dev/null +++ b/frameworks/security_component/src/paste_button.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 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. + */ +#include "paste_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "PasteButton"}; +} + +bool PasteButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= PasteDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= PasteIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool PasteButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + PasteButton* otherPasteButton = reinterpret_cast(other); + if (otherPasteButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not paste button."); + return false; + } + return (icon_ == otherPasteButton->icon_) && (text_ == otherPasteButton->text_) && + (bg_ == otherPasteButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/save_button.cpp b/frameworks/security_component/src/save_button.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22fc45c2167b9c8b9d74f0ef638236258d489bd2 --- /dev/null +++ b/frameworks/security_component/src/save_button.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 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. + */ +#include "save_button.h" + +#include +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SaveButton"}; +} + +bool SaveButton::IsParamValid() +{ + if ((text_ <= UNKNOWN_TEXT) || (static_cast(text_) >= SaveDesc::MAX_LABEL_TYPE) || + (icon_ <= UNKNOWN_ICON) || (static_cast(icon_) >= SaveIcon::MAX_ICON_TYPE)) { + return false; + } + + return true; +} + +bool SaveButton::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (!SecCompBase::CompareComponentBasicInfo(other, isRectCheck)) { + SC_LOG_ERROR(LABEL, "SecComp base not equal."); + return false; + } + SaveButton* otherSaveButton = reinterpret_cast(other); + if (otherSaveButton == nullptr) { + SC_LOG_ERROR(LABEL, "other is not save button."); + return false; + } + return (icon_ == otherSaveButton->icon_) && (text_ == otherSaveButton->text_) && + (bg_ == otherSaveButton->bg_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/frameworks/security_component/src/sec_comp_base.cpp b/frameworks/security_component/src/sec_comp_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c12e77ac6112fcebd5aa114f770b6cd752f6f7a --- /dev/null +++ b/frameworks/security_component/src/sec_comp_base.cpp @@ -0,0 +1,369 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_base.h" + +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompBase"}; +} + +const std::string JsonTagConstants::JSON_RECT = "rect"; +const std::string JsonTagConstants::JSON_SC_TYPE = "type"; +const std::string JsonTagConstants::JSON_NODE_ID = "nodeId"; +const std::string JsonTagConstants::JSON_RECT_X = "x"; +const std::string JsonTagConstants::JSON_RECT_Y = "y"; +const std::string JsonTagConstants::JSON_RECT_WIDTH = "width"; +const std::string JsonTagConstants::JSON_RECT_HEIGHT = "height"; +const std::string JsonTagConstants::JSON_WINDOW_RECT = "windowRect"; +const std::string JsonTagConstants::JSON_SIZE_TAG = "size"; +const std::string JsonTagConstants::JSON_FONT_SIZE_TAG = "fontSize"; +const std::string JsonTagConstants::JSON_ICON_SIZE_TAG = "iconSize"; +const std::string JsonTagConstants::JSON_PADDING_SIZE_TAG = "paddingSize"; +const std::string JsonTagConstants::JSON_PADDING_LEFT_TAG = "left"; +const std::string JsonTagConstants::JSON_PADDING_TOP_TAG = "top"; +const std::string JsonTagConstants::JSON_PADDING_RIGHT_TAG = "right"; +const std::string JsonTagConstants::JSON_PADDING_BOTTOM_TAG = "bottom"; +const std::string JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG = "textIconSpace"; +const std::string JsonTagConstants::JSON_RECT_WIDTH_TAG = "width"; +const std::string JsonTagConstants::JSON_RECT_HEIGHT_TAG = "height"; +const std::string JsonTagConstants::JSON_COLORS_TAG = "colors"; +const std::string JsonTagConstants::JSON_FONT_COLOR_TAG = "fontColor"; +const std::string JsonTagConstants::JSON_ICON_COLOR_TAG = "iconColor"; +const std::string JsonTagConstants::JSON_BG_COLOR_TAG = "bgColor"; +const std::string JsonTagConstants::JSON_BORDER_TAG = "border"; +const std::string JsonTagConstants::JSON_BORDER_WIDTH_TAG = "borderWidth"; +const std::string JsonTagConstants::JSON_PARENT_TAG = "parent"; +const std::string JsonTagConstants::JSON_PARENT_EFFECT_TAG = "parentEffect"; +const std::string JsonTagConstants::JSON_STYLE_TAG = "style"; +const std::string JsonTagConstants::JSON_TEXT_TAG = "text"; +const std::string JsonTagConstants::JSON_ICON_TAG = "icon"; +const std::string JsonTagConstants::JSON_BG_TAG = "bg"; + +bool SecCompBase::ParseDimension(const nlohmann::json& json, const std::string& tag, DimensionT& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_number_float()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParseColor(const nlohmann::json& json, const std::string& tag, SecCompColor& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res.value = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParseBool(const nlohmann::json& json, const std::string& tag, bool& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_boolean()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + res = json.at(tag).get(); + return true; +} + +bool SecCompBase::ParsePadding(const nlohmann::json& json, const std::string& tag, PaddingSize& res) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonPadding = json.at(tag); + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_TOP_TAG, res.top)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_RIGHT_TAG, res.right)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_BOTTOM_TAG, res.bottom)) { + return false; + } + if (!ParseDimension(jsonPadding, JsonTagConstants::JSON_PADDING_LEFT_TAG, res.left)) { + return false; + } + return true; +} + +bool SecCompBase::ParseColors(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonColors = json.at(tag); + if (!ParseColor(jsonColors, JsonTagConstants::JSON_FONT_COLOR_TAG, fontColor_)) { + return false; + } + if (!ParseColor(jsonColors, JsonTagConstants::JSON_ICON_COLOR_TAG, iconColor_)) { + return false; + } + if (!ParseColor(jsonColors, JsonTagConstants::JSON_BG_COLOR_TAG, bgColor_)) { + return false; + } + return true; +} + +bool SecCompBase::ParseBorders(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonBorder = json.at(tag); + return ParseDimension(jsonBorder, JsonTagConstants::JSON_BORDER_WIDTH_TAG, borderWidth_); +} + +bool SecCompBase::ParseSize(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonSize = json.at(tag); + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_FONT_SIZE_TAG, fontSize_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_ICON_SIZE_TAG, iconSize_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, textIconSpace_)) { + return false; + } + + if (!ParsePadding(jsonSize, JsonTagConstants::JSON_PADDING_SIZE_TAG, padding_)) { + return false; + } + + return true; +} + +bool SecCompBase::ParseParent(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonParent = json.at(tag); + return ParseBool(jsonParent, JsonTagConstants::JSON_PARENT_EFFECT_TAG, parentEffect_); +} + +bool SecCompBase::ParseRect(const nlohmann::json& json, const std::string& tag, SecCompRect& rect) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + + auto jsonSize = json.at(tag); + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_X, rect.x_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_Y, rect.y_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_WIDTH, rect.width_)) { + return false; + } + + if (!ParseDimension(jsonSize, JsonTagConstants::JSON_RECT_HEIGHT, rect.height_)) { + return false; + } + + return true; +} + +bool SecCompBase::FromJson(const nlohmann::json& jsonSrc) +{ + SC_LOG_DEBUG(LABEL, "Button info %{public}s.", jsonSrc.dump().c_str()); + if ((jsonSrc.find(JsonTagConstants::JSON_SC_TYPE) == jsonSrc.end()) || + !jsonSrc.at(JsonTagConstants::JSON_SC_TYPE).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", JsonTagConstants::JSON_SC_TYPE.c_str()); + return false; + } + int32_t value = jsonSrc.at(JsonTagConstants::JSON_SC_TYPE).get(); + if ((value <= static_cast(SecCompType::UNKNOWN_SC_TYPE)) || + (value >= static_cast(SecCompType::MAX_SC_TYPE))) { + SC_LOG_ERROR(LABEL, "scType is invalid."); + return false; + } + type_ = static_cast(value); + + if ((jsonSrc.find(JsonTagConstants::JSON_NODE_ID) == jsonSrc.end()) || + !jsonSrc.at(JsonTagConstants::JSON_NODE_ID).is_number()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", JsonTagConstants::JSON_NODE_ID.c_str()); + return false; + } + nodeId_ = jsonSrc.at(JsonTagConstants::JSON_NODE_ID).get(); + + if (!ParseRect(jsonSrc, JsonTagConstants::JSON_RECT, rect_)) { + return false; + } + if (!ParseRect(jsonSrc, JsonTagConstants::JSON_WINDOW_RECT, windowRect_)) { + return false; + } + if (!ParseSize(jsonSrc, JsonTagConstants::JSON_SIZE_TAG)) { + return false; + } + if (!ParseColors(jsonSrc, JsonTagConstants::JSON_COLORS_TAG)) { + return false; + } + if (!ParseBorders(jsonSrc, JsonTagConstants::JSON_BORDER_TAG)) { + return false; + } + if (!ParseParent(jsonSrc, JsonTagConstants::JSON_PARENT_TAG)) { + return false; + } + if (!ParseStyle(jsonSrc, JsonTagConstants::JSON_STYLE_TAG)) { + return false; + } + + return true; +} + +void SecCompBase::ToJson(nlohmann::json& jsonRes) const +{ + jsonRes[JsonTagConstants::JSON_SC_TYPE] = type_; + jsonRes[JsonTagConstants::JSON_NODE_ID] = nodeId_; + jsonRes[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, rect_.x_}, + {JsonTagConstants::JSON_RECT_Y, rect_.y_}, + {JsonTagConstants::JSON_RECT_WIDTH, rect_.width_}, + {JsonTagConstants::JSON_RECT_HEIGHT, rect_.height_} + }; + jsonRes[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, windowRect_.x_}, + {JsonTagConstants::JSON_RECT_Y, windowRect_.y_}, + {JsonTagConstants::JSON_RECT_WIDTH, windowRect_.width_}, + {JsonTagConstants::JSON_RECT_HEIGHT, windowRect_.height_} + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, padding_.top }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, padding_.right }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, padding_.bottom }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, padding_.left }, + }; + + jsonRes[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, fontSize_ }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, iconSize_ }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, textIconSpace_ }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonRes[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, fontColor_.value }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, iconColor_.value }, + { JsonTagConstants::JSON_BG_COLOR_TAG, bgColor_.value } + }; + + jsonRes[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, borderWidth_ }, + }; + jsonRes[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, parentEffect_ }, + }; + + jsonRes[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, text_ }, + { JsonTagConstants::JSON_ICON_TAG, icon_ }, + { JsonTagConstants::JSON_BG_TAG, bg_ }, + }; +} + +std::string SecCompBase::ToJsonStr() const +{ + nlohmann::json json; + ToJson(json); + return json.dump(); +} + +bool SecCompBase::CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const +{ + if (other == nullptr) { + SC_LOG_ERROR(LABEL, "other is nullptr."); + return false; + } + + SecCompRect rect = other->rect_; + SecCompRect windowRect = other->windowRect_; + if (isRectCheck) { + rect = rect_; + windowRect = windowRect_; + } + + auto leftValue = std::tie(type_, fontSize_, iconSize_, textIconSpace_, padding_.top, padding_.right, + padding_.bottom, padding_.left, fontColor_.value, bgColor_.value, iconColor_.value, borderWidth_, + rect, windowRect); + auto rightValue = std::tie(other->type_, other->fontSize_, other->iconSize_, other->textIconSpace_, + other->padding_.top, other->padding_.right, other->padding_.bottom, other->padding_.left, + other->fontColor_.value, other->bgColor_.value, other->iconColor_.value, other->borderWidth_, + other->rect_, other->windowRect_); + + return (leftValue == rightValue); +} + +bool SecCompBase::ParseStyle(const nlohmann::json& json, const std::string& tag) +{ + if ((json.find(tag) == json.end()) || !json.at(tag).is_object()) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + auto jsonStyle = json.at(tag); + if (!(jsonStyle.at(JsonTagConstants::JSON_TEXT_TAG).is_number() && + jsonStyle.at(JsonTagConstants::JSON_ICON_TAG).is_number() && + jsonStyle.at(JsonTagConstants::JSON_BG_TAG).is_number())) { + SC_LOG_ERROR(LABEL, "json: %{public}s tag invalid.", tag.c_str()); + return false; + } + text_ = jsonStyle.at(JsonTagConstants::JSON_TEXT_TAG).get(); + icon_ = jsonStyle.at(JsonTagConstants::JSON_ICON_TAG).get(); + if (!IsParamValid()) { + SC_LOG_ERROR(LABEL, "text or icon is invalid."); + return false; + } + + bg_ = static_cast(jsonStyle.at(JsonTagConstants::JSON_BG_TAG).get()); + if ((bg_ <= SecCompBackground::UNKNOWN_BG) || (bg_ >= SecCompBackground::MAX_BG_TYPE)) { + SC_LOG_ERROR(LABEL, "bg is invalid."); + return false; + } + + return true; +} +} // namespace base +} // namespace Security +} // namespace OHOS + diff --git a/frameworks/security_component/src/sec_comp_click_event_parcel.cpp b/frameworks/security_component/src/sec_comp_click_event_parcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55390c9cb2015c56239e4b05757b37c0f8b498ab --- /dev/null +++ b/frameworks/security_component/src/sec_comp_click_event_parcel.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_click_event_parcel.h" + +#include "sec_comp_log.h" +#include "securec.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClickEventParcel"}; +} + +bool SecCompClickEventParcel::Marshalling(Parcel& out) const +{ + if (!(out.WriteDouble(this->touchInfoParams_.touchX)) || !(out.WriteDouble(this->touchInfoParams_.touchY))) { + SC_LOG_ERROR(LABEL, "Write touch xy pointer fail"); + return false; + } + + if (!(out.WriteUint64(this->touchInfoParams_.timestamp))) { + SC_LOG_ERROR(LABEL, "Write touch timestamp fail"); + return false; + } + + if (!(out.WriteUint32(this->touchInfoParams_.extraInfo.dataSize))) { + SC_LOG_ERROR(LABEL, "Write extraInfo dataSize fail"); + return false; + } + + if (this->touchInfoParams_.extraInfo.dataSize != 0 && + !(out.WriteBuffer(this->touchInfoParams_.extraInfo.data, this->touchInfoParams_.extraInfo.dataSize))) { + SC_LOG_ERROR(LABEL, "Write touch extraInfo data fail"); + return false; + } + + return true; +} + +SecCompClickEventParcel* SecCompClickEventParcel::Unmarshalling(Parcel& in) +{ + SecCompClickEventParcel* touchInfoParcel = new (std::nothrow) SecCompClickEventParcel(); + if (touchInfoParcel == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc policy parcel fail"); + return nullptr; + } + + SecCompClickEvent touchInfo; + if (!in.ReadDouble(touchInfo.touchX) || !in.ReadDouble(touchInfo.touchY)) { + SC_LOG_ERROR(LABEL, "Read touch xy porinter fail"); + delete touchInfoParcel; + return nullptr; + } + + if (!in.ReadUint64(touchInfo.timestamp)) { + SC_LOG_ERROR(LABEL, "Read timestamp fail"); + delete touchInfoParcel; + return nullptr; + } + + if (!in.ReadUint32(touchInfo.extraInfo.dataSize)) { + SC_LOG_ERROR(LABEL, "Read extraInfo data size fail"); + delete touchInfoParcel; + return nullptr; + } + + if (touchInfo.extraInfo.dataSize == 0) { + touchInfoParcel->touchInfoParams_ = touchInfo; + return touchInfoParcel; + } else if (touchInfo.extraInfo.dataSize > MAX_EXTRA_SIZE) { + SC_LOG_ERROR(LABEL, "Read extraInfo data size invalid"); + delete touchInfoParcel; + return nullptr; + } + + touchInfo.extraInfo.data = const_cast(in.ReadBuffer(touchInfo.extraInfo.dataSize)); + if (touchInfo.extraInfo.data == nullptr) { + SC_LOG_ERROR(LABEL, "Read extraInfo data failed"); + delete touchInfoParcel; + return nullptr; + } + + touchInfoParcel->touchInfoParams_ = touchInfo; + return touchInfoParcel; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/hisysevent.yaml b/hisysevent.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51ab79c24090920aff499264d6b30b0000427f43 --- /dev/null +++ b/hisysevent.yaml @@ -0,0 +1,94 @@ +# Copyright (c) 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. + +domain: SEC_COMPONENT + +CALLBACK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to execute the callback} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + REASON: {type: STRING, desc: callback execution failure cause} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +CALLER_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Illegal invocation} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + +CHALLENGE_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Challenge value verification failed} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +CLICK_INFO_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to verify the click event} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +COMPONENT_INFO_CHECK_FAILED: + __BASE: {type: SECURITY, level: CRITICAL, desc: Failed to verify the component information} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + CALL_SCENE: {type: STRING, desc: call scene} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +INIT_FAILED: + __BASE: {type: FAULT, level: CRITICAL, desc: Failed to initialize the security component environment} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + REASON: {type: STRING, desc: callback execution failure cause} + +REGISTER_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: The security component is registered successfully} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +REPEAT_CALLBACK_REGISTER: + __BASE: {type: SECURITY, level: CRITICAL, desc: Repeated registration callback} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + +SERVICE_INIT_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component service starts successfully} + PID: {type: INT32, desc: pid of the service process} + +TEMP_GRANT_FAILED: + __BASE: {type: FAULT, level: CRITICAL, desc: Security component authorization failed} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +TEMP_GRANT_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component authorization successfully} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} + SC_TYPE: {type: STRING, desc: security component type} + +UNREGISTER_SUCCESS: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Security component unregister} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_UID: {type: INT32, desc: caller uid} + SC_ID: {type: INT32, desc: security component id} diff --git a/interfaces/inner_api/enhance_kits/BUILD.gn b/interfaces/inner_api/enhance_kits/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..03d5acf48dd20aabcb847dad2c4de37cc34a8a7d --- /dev/null +++ b/interfaces/inner_api/enhance_kits/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (c) 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("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("sec_comp_enhance_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + ] +} + +ohos_shared_library("libsecurity_component_enhance_sdk") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_enhance_sdk" + + public_configs = [ ":sec_comp_enhance_config" ] + + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + ] + + sources = [ + "src/sec_comp_enhance_kit.cpp", + ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single" + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..11f46ee7cb036d82c5ce9d06dbf6d91f1895a92b --- /dev/null +++ b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENHANCE_KITS_H +#define SECURITY_COMPONENT_ENHANCE_KITS_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompEnhanceKit { + static void InitClientEnhance(); + static int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); + static int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_KITS_H diff --git a/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h new file mode 100644 index 0000000000000000000000000000000000000000..c7e0c6f15599f9156492edd8290e5984110cf9e8 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/include/sec_comp_enhance_kit_c.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENHANCE_KIT_C_H +#define SECURITY_COMPONENT_ENHANCE_KIT_C_H + +void InitSecCompClientEnhance(void); + +#endif // SECURITY_COMPONENT_ENHANCE_KIT_C_H + diff --git a/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp b/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b16511ce6ffab9e6aea282a579d013c4ac70186 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/src/sec_comp_enhance_kit.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 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. + */ + +#include "sec_comp_enhance_kit.h" + +#include "sec_comp_enhance_adapter.h" + +extern "C" void InitSecCompClientEnhance() +{ + OHOS::Security::SecurityComponent::SecCompEnhanceKit::InitClientEnhance(); +} + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void SecCompEnhanceKit::InitClientEnhance(void) +{ + SecCompEnhanceAdapter::InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); +} + +int32_t SecCompEnhanceKit::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + return SecCompEnhanceAdapter::SetEnhanceCfg(cfg, cfgLen); +} + +int32_t SecCompEnhanceKit::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + return SecCompEnhanceAdapter::GetPointerEventEnhanceData(data, dataLen, enhanceData, enHancedataLen); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/enhance_kits/test/BUILD.gn b/interfaces/inner_api/enhance_kits/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bf1409c6a69a946289966c76e9158347d6dd7242 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 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("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_enhance_sdk_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ "unittest/src" ] + + sources = [ "unittest/src/sec_comp_enhance_test.cpp" ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + if (current_cpu == "arm64") { + defines = [ "_ARM64_" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":sec_comp_enhance_sdk_test" ] +} diff --git a/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb3c2ab5e2fc3b40638feb3fa56cfa403a31d8b5 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_enhance_test.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEnhanceTest"}; +static bool g_inputEnhanceExist = false; +static bool g_srvEnhanceExist = false; +static constexpr uint32_t SEC_COMP_ENHANCE_CFG_SIZE = 76; +#ifdef _ARM64_ +static const std::string LIB_PATH = "/system/lib64/"; +#else +static const std::string LIB_PATH = "/system/lib/"; +#endif +static const std::string ENHANCE_INPUT_INTERFACE_LIB = LIB_PATH + "libsec_comp_input_enhance.z.so"; +static const std::string ENHANCE_SRV_INTERFACE_LIB = LIB_PATH + "libsec_comp_service_enhance.z.so"; +static constexpr uint32_t MAX_HMAC_SIZE = 64; +} // namespace + +void SecCompEnhanceTest::SetUpTestCase() +{ + if (access(ENHANCE_INPUT_INTERFACE_LIB.c_str(), F_OK) == 0) { + g_inputEnhanceExist = true; + } + + if (access(ENHANCE_SRV_INTERFACE_LIB.c_str(), F_OK) == 0) { + g_srvEnhanceExist = true; + } + + SC_LOG_INFO(LABEL, "SetUpTestCase."); +} + +void SecCompEnhanceTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "TearDownTestCase."); +} + +void SecCompEnhanceTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompEnhanceTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: SetEnhanceCfg001 + * @tc.desc: test SetEnhanceCfg + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, SetEnhanceCfg001, TestSize.Level1) +{ + uint8_t cfgData[SEC_COMP_ENHANCE_CFG_SIZE] = { 0 }; + int32_t result = SecCompEnhanceKit::SetEnhanceCfg(cfgData, SEC_COMP_ENHANCE_CFG_SIZE); + if (g_inputEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: GetPoniterEventEnhanceData001 + * @tc.desc: test GetPoniterEventEnhanceData + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, GetPoniterEventEnhanceData001, TestSize.Level1) +{ + uint8_t originData[16] = { 0 }; + uint32_t dataLen = 16; + uint8_t* enhanceData = nullptr; + uint32_t enHancedataLen = MAX_HMAC_SIZE; + + int32_t result = SecCompEnhanceKit::GetPointerEventEnhanceData(originData, dataLen, enhanceData, enHancedataLen); + if (g_inputEnhanceExist) { + EXPECT_EQ(result, SC_SERVICE_ERROR_SERVICE_NOT_EXIST); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: EnableInputEnhance001 + * @tc.desc: test UnmarshallEnhanceCfg + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, EnableInputEnhance001, TestSize.Level1) +{ + int32_t result = SecCompEnhanceAdapter::EnableInputEnhance(); + if (g_srvEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} + +/** + * @tc.name: DisableInputEnhance001 + * @tc.desc: test DisableInputEnhance + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompEnhanceTest, DisableInputEnhance001, TestSize.Level1) +{ + int32_t result = SecCompEnhanceAdapter::DisableInputEnhance(); + if (g_srvEnhanceExist) { + EXPECT_EQ(result, SC_OK); + } else { + EXPECT_EQ(result, SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE); + } +} diff --git a/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h new file mode 100644 index 0000000000000000000000000000000000000000..deff0d4a99042f8654e3de4608a7f275ca6fe842 --- /dev/null +++ b/interfaces/inner_api/enhance_kits/test/unittest/src/sec_comp_enhance_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENHANCE_KITS_TEST +#define SECURITY_COMPONENT_ENHANCE_KITS_TEST + +#include +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_enhance_kit.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEnhanceTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_KITS_TEST \ No newline at end of file diff --git a/interfaces/inner_api/security_component/BUILD.gn b/interfaces/inner_api/security_component/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a286b4c905db87950d243b7098a67e17d6471cde --- /dev/null +++ b/interfaces/inner_api/security_component/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 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("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("sec_comp_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "//third_party/json/include", + ] +} + +ohos_shared_library("libsecurity_component_sdk") { + subsystem_name = "security" + part_name = "security_component" + output_name = "libsecurity_component_sdk" + + public_configs = [ ":sec_comp_config" ] + + include_dirs = [ + "include", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + ] + + sources = [ + "src/sec_comp_caller_authorization.cpp", + "src/sec_comp_client.cpp", + "src/sec_comp_death_recipient.cpp", + "src/sec_comp_kit.cpp", + "src/sec_comp_load_callback.cpp", + "src/sec_comp_proxy.cpp", + "src/sec_comp_ui_register.cpp" + ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework" + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] +} diff --git a/interfaces/inner_api/security_component/include/i_sec_comp_probe.h b/interfaces/inner_api/security_component/include/i_sec_comp_probe.h new file mode 100644 index 0000000000000000000000000000000000000000..c83cd997c603d59e48612b1dc942ba7ecc98b795 --- /dev/null +++ b/interfaces/inner_api/security_component/include/i_sec_comp_probe.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 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. + */ +#ifndef I_SECURITY_COMPONENT_PROPE_H +#define I_SECURITY_COMPONENT_PROPE_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class ISecCompProbe { +public: + virtual int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) = 0; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_PROPE_H diff --git a/interfaces/inner_api/security_component/include/i_sec_comp_service.h b/interfaces/inner_api/security_component/include/i_sec_comp_service.h new file mode 100644 index 0000000000000000000000000000000000000000..0b6d2e72be294ef361cdbbb9c69ca476c657c41a --- /dev/null +++ b/interfaces/inner_api/security_component/include/i_sec_comp_service.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 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. + */ +#ifndef I_SECURITY_COMPONENT_SERVICE_H +#define I_SECURITY_COMPONENT_SERVICE_H + +#include +#include "access_token.h" +#include "iremote_broker.h" +#include "sec_comp_info.h" +#include "security_component_service_ipc_interface_code.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr int32_t SA_ID_SECURITY_COMPONENT_SERVICE = 3506; + +class ISecCompService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.ISecCompService"); + + virtual int32_t RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) = 0; + virtual int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) = 0; + virtual int32_t UnregisterSecurityComponent(int32_t scId) = 0; + virtual int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, + const SecCompClickEvent& touchInfo, sptr callerToken) = 0; + virtual bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) = 0; + virtual sptr GetEnhanceRemoteObject() = 0; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_SERVICE_H diff --git a/interfaces/inner_api/security_component/include/location_button.h b/interfaces/inner_api/security_component/include/location_button.h new file mode 100644 index 0000000000000000000000000000000000000000..927189cb75898764e5cf182492bd6da3bb1c4b9c --- /dev/null +++ b/interfaces/inner_api/security_component/include/location_button.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 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. + */ +#ifndef I_SECURITY_COMPONENT_LOCATION_BUTTON_H +#define I_SECURITY_COMPONENT_LOCATION_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class LocationDesc : int32_t { + CURRENT_LOCATION = 0, + ADD_LOCATION = 1, + SELECT_LOCATION = 2, + SHARE_LOCATION = 3, + SEND_LOCATION = 4, + LOCATING = 5, + LOCATION = 6, + SEND_CURRENT_LOCATION = 7, + RELOCATION = 8, + PUNCH_IN = 9, + CURRENT_POSITION = 10, + MAX_LABEL_TYPE +}; + +enum class LocationIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class LocationButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_LOCATION_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/paste_button.h b/interfaces/inner_api/security_component/include/paste_button.h new file mode 100644 index 0000000000000000000000000000000000000000..241a316f2250790efa7e7c75e239d459b91deb93 --- /dev/null +++ b/interfaces/inner_api/security_component/include/paste_button.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_PASTE_BUTTON_H +#define SECURITY_COMPONENT_PASTE_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class PasteDesc : int32_t { + PASTE = 0, + MAX_LABEL_TYPE +}; + +enum class PasteIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class PasteButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_LOCATION_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/save_button.h b/interfaces/inner_api/security_component/include/save_button.h new file mode 100644 index 0000000000000000000000000000000000000000..ea7b5f516ebcd6ced4efe5ce5f92fa17e0b91413 --- /dev/null +++ b/interfaces/inner_api/security_component/include/save_button.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 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. + */ +#ifndef I_SECURITY_COMPONENT_SAVE_BUTTON_H +#define I_SECURITY_COMPONENT_SAVE_BUTTON_H + +#include +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class SaveDesc : int32_t { + DOWNLOAD = 0, + DOWNLOAD_FILE = 1, + SAVE = 2, + SAVE_IMAGE = 3, + SAVE_FILE = 4, + DOWNLOAD_AND_SHARE = 5, + RECEIVE = 6, + CONTINUE_TO_RECEIVE = 7, + MAX_LABEL_TYPE +}; + +enum class SaveIcon : int32_t { + FILLED_ICON = 0, + LINE_ICON = 1, + MAX_ICON_TYPE +}; + +class SaveButton : public SecCompBase { +public: + virtual bool IsParamValid() override; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const override; +private: + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_SAVE_BUTTON_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_base.h b/interfaces/inner_api/security_component/include/sec_comp_base.h new file mode 100644 index 0000000000000000000000000000000000000000..7449a003cd6ab2eb0bfc9777c8992483e4f6e0a3 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_base.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_BASE_H +#define SECURITY_COMPONENT_BASE_H + +#include "nlohmann/json.hpp" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr int32_t UNKNOWN_TEXT = -2; +constexpr int32_t NO_TEXT = -1; +constexpr int32_t UNKNOWN_ICON = -2; +constexpr int32_t NO_ICON = -1; + +enum class SecCompBackground { + UNKNOWN_BG = -2, + NO_BG_TYPE = -1, + CAPSULE = 0, + CIRCLE = 1, + NORMAL = 2, + MAX_BG_TYPE +}; + +class JsonTagConstants final { +public: + static const std::string JSON_RECT; + static const std::string JSON_SC_TYPE; + static const std::string JSON_NODE_ID; + static const std::string JSON_RECT_X; + static const std::string JSON_RECT_Y; + static const std::string JSON_RECT_WIDTH; + static const std::string JSON_RECT_HEIGHT; + static const std::string JSON_WINDOW_RECT; + + static const std::string JSON_SIZE_TAG; + static const std::string JSON_FONT_SIZE_TAG; + static const std::string JSON_ICON_SIZE_TAG; + static const std::string JSON_PADDING_SIZE_TAG; + static const std::string JSON_PADDING_LEFT_TAG; + static const std::string JSON_PADDING_TOP_TAG; + static const std::string JSON_PADDING_RIGHT_TAG; + static const std::string JSON_PADDING_BOTTOM_TAG; + static const std::string JSON_TEXT_ICON_PADDING_TAG; + static const std::string JSON_RECT_WIDTH_TAG; + static const std::string JSON_RECT_HEIGHT_TAG; + static const std::string JSON_COLORS_TAG; + static const std::string JSON_FONT_COLOR_TAG; + static const std::string JSON_ICON_COLOR_TAG; + static const std::string JSON_BG_COLOR_TAG; + + static const std::string JSON_BORDER_TAG; + static const std::string JSON_BORDER_WIDTH_TAG; + static const std::string JSON_PARENT_TAG; + static const std::string JSON_PARENT_EFFECT_TAG; + + static const std::string JSON_STYLE_TAG; + static const std::string JSON_TEXT_TAG; + static const std::string JSON_ICON_TAG; + static const std::string JSON_BG_TAG; +}; + +class SecCompBase { +public: + SecCompBase() = default; + virtual ~SecCompBase() = default; + bool FromJson(const nlohmann::json& jsonSrc); + void ToJson(nlohmann::json& jsonRes) const; + std::string ToJsonStr(void) const; + virtual bool CompareComponentBasicInfo(SecCompBase *other, bool isRectCheck) const; + void SetValid(bool valid) + { + isValid_ = valid; + }; + + bool GetValid() + { + return isValid_; + }; + + // size + DimensionT fontSize_ = DEFAULT_DIMENSION; + DimensionT iconSize_ = DEFAULT_DIMENSION; + PaddingSize padding_; + DimensionT textIconSpace_ = DEFAULT_DIMENSION; + + // color + SecCompColor fontColor_; + SecCompColor iconColor_; + SecCompColor bgColor_; + + // border + DimensionT borderWidth_ = DEFAULT_DIMENSION; + + // parent effect + bool parentEffect_ = false; + + SecCompType type_ = UNKNOWN_SC_TYPE; + SecCompRect rect_; + SecCompRect windowRect_; + bool isValid_ = false; + + int32_t text_ = UNKNOWN_TEXT; + int32_t icon_ = UNKNOWN_ICON; + SecCompBackground bg_ = SecCompBackground::UNKNOWN_BG; + + int32_t nodeId_ = 0; +protected: + virtual bool IsParamValid() = 0; +private: + bool ParseDimension(const nlohmann::json& json, const std::string& tag, DimensionT& res); + bool ParseColor(const nlohmann::json& json, const std::string& tag, SecCompColor& res); + bool ParseBool(const nlohmann::json& json, const std::string& tag, bool& res); + bool ParsePadding(const nlohmann::json& json, const std::string& tag, PaddingSize& res); + bool ParseColors(const nlohmann::json& json, const std::string& tag); + bool ParseBorders(const nlohmann::json& json, const std::string& tag); + bool ParseSize(const nlohmann::json& json, const std::string& tag); + bool ParseParent(const nlohmann::json& json, const std::string& tag); + bool ParseRect(const nlohmann::json& json, const std::string& tag, SecCompRect& rect); + bool ParseStyle(const nlohmann::json& json, const std::string& tag); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_BASE_H + diff --git a/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h b/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h new file mode 100644 index 0000000000000000000000000000000000000000..d1564a0b0c74a7fed0af767eedd62f51d7e4b6c0 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_caller_authorization.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 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. + */ + +#ifndef INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H + +#include +#include +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompCallerAuthorization { +public: + static SecCompCallerAuthorization& GetInstance(); + virtual ~SecCompCallerAuthorization() = default; + void RegisterSecCompKitCaller(std::vector& callerList); + bool IsKitCaller(uintptr_t callerAddr); + +private: + SecCompCallerAuthorization() = default; + std::vector kitCallerList_; + bool isInit_ = false; + DISALLOW_COPY_AND_MOVE(SecCompCallerAuthorization); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_CALLER_AYTHORIZATION_H + diff --git a/interfaces/inner_api/security_component/include/sec_comp_client.h b/interfaces/inner_api/security_component/include/sec_comp_client.h new file mode 100644 index 0000000000000000000000000000000000000000..954fe115e0f62a55995573171257b0b01d07b702 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_client.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SECURITY_COMPONENT_CLIENT_H +#define SECURITY_COMPONENT_CLIENT_H + +#include +#include +#include +#include "i_sec_comp_service.h" +#include "sec_comp_death_recipient.h" +#include "sec_comp_err.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompClient final { +public: + static SecCompClient& GetInstance(); + + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId); + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo); + int32_t UnregisterSecurityComponent(int32_t scId); + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken); + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + sptr GetEnhanceRemoteObject(bool doLoadSa); + + void FinishStartSASuccess(const sptr& remoteObject); + void FinishStartSAFail(); + void OnRemoteDiedHandle(); + +private: + SecCompClient(); + virtual ~SecCompClient(); + DISALLOW_COPY_AND_MOVE(SecCompClient); + + bool TryToGetSecCompSa(); + bool StartLoadSecCompSa(); + void WaitForSecCompSa(); + void GetSecCompSa(); + void LoadSecCompSa(); + sptr GetProxy(bool doLoadSa); + void GetProxyFromRemoteObject(const sptr& remoteObject); + + std::mutex cvLock_; + bool readyFlag_ = false; + std::condition_variable secComCon_; + std::mutex proxyMutex_; + sptr proxy_ = nullptr; + sptr serviceDeathObserver_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_CLIENT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h b/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..4a18525526e50c4689e0715a0fb81cbecd659e30 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_death_recipient.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_DEATH_RECIPIENT_H +#define SECURITY_COMPONENT_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompDeathRecipient : public IRemoteObject::DeathRecipient { +public: + SecCompDeathRecipient() {} + virtual ~SecCompDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_DEATH_RECIPIENT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_info.h b/interfaces/inner_api/security_component/include/sec_comp_info.h new file mode 100644 index 0000000000000000000000000000000000000000..d02ebb2263ac29f8a1b3fda0612ad3966855fa61 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_info.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SECURITY_COMPONENT_INFO_H +#define SECURITY_COMPONENT_INFO_H + +#include + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +static constexpr int32_t INVALID_SC_ID = -1; +using DimensionT = double; // unit is vp +static constexpr DimensionT DEFAULT_DIMENSION = 0.0; +static constexpr DimensionT MIN_FONT_SIZE = 12.0; +static constexpr DimensionT MIN_ICON_SIZE = 12.0; +static constexpr DimensionT MIN_PADDING_SIZE = 0.0; +static constexpr DimensionT MIN_PADDING_WITHOUT_BG = 4.0; +static constexpr uint32_t MAX_EXTRA_SIZE = 0x1000; + +struct PaddingSize { + DimensionT top = DEFAULT_DIMENSION; + DimensionT right = DEFAULT_DIMENSION; + DimensionT bottom = DEFAULT_DIMENSION; + DimensionT left = DEFAULT_DIMENSION; +}; + +enum SecCompType { + UNKNOWN_SC_TYPE = 0, + LOCATION_COMPONENT, + PASTE_COMPONENT, + SAVE_COMPONENT, + MAX_SC_TYPE +}; + +union SecCompColor { + struct { + uint8_t blue; + uint8_t green; + uint8_t red; + uint8_t alpha; + } argb; + uint32_t value; +}; + +inline bool IsComponentTypeValid(int32_t type) +{ + return (type > UNKNOWN_SC_TYPE && type < MAX_SC_TYPE); +} + +inline bool GreatOrEqual(double left, double right) +{ + constexpr double epsilon = -0.001; + return (left - right) > epsilon; +} + +inline bool GreatNotEqual(double left, double right) +{ + constexpr double epsilon = 0.001; + return (left - right) > epsilon; +} + +inline bool IsEqual(double left, double right) +{ + constexpr double epsilon = 0.001; + if (left > right) { + return (left - right) < epsilon; + } else if (right > left) { + return (right - left) < epsilon; + } else { + return true; + } +} + +class SecCompRect { +public: + SecCompRect() = default; + ~SecCompRect() = default; + + bool IsInRect(double x, double y) const + { + return (GreatOrEqual(x, x_) && GreatOrEqual((x_ + width_), x) && + GreatOrEqual(y, y_) && GreatOrEqual((y_ + height_), y)); + }; + + bool operator==(const SecCompRect& other) const + { + return (IsEqual(x_, other.x_)) && (IsEqual(y_, other.y_)) && + (IsEqual(width_, other.width_)) && (IsEqual(height_, other.height_)); + } + + DimensionT x_ = 0.0; + DimensionT y_ = 0.0; + DimensionT width_ = 0.0; + DimensionT height_ = 0.0; +}; + +struct ExtraInfo { + uint32_t dataSize; + uint8_t* data; +}; + +struct SecCompClickEvent { + double touchX; + double touchY; + uint64_t timestamp; + ExtraInfo extraInfo; +}; + +struct SecCompPointEvent { + double touchX; + double touchY; + uint64_t timestamp; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_INFO_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_kit.h b/interfaces/inner_api/security_component/include/sec_comp_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..80c20c253e41cb738da2f701e9e07f932c53f1fb --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_kit.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 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. + */ +#ifndef INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H + +#include +#include "accesstoken_kit.h" +#include "iremote_object.h" +#include "sec_comp_info.h" +#include "sec_comp_ui_register.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompKit { +public: + static int32_t RegisterSecurityComponent(SecCompType type, std::string& componentInfo, int32_t& scId); + static int32_t UpdateSecurityComponent(int32_t scId, std::string& componentInfo); + static int32_t UnregisterSecurityComponent(int32_t scId); + static int32_t ReportSecurityComponentClickEvent(int32_t scId, + std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken = nullptr); + static bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + static sptr GetEnhanceRemoteObject(bool isLoad); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_KIT_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_load_callback.h b/interfaces/inner_api/security_component/include/sec_comp_load_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..5513896e17473d10bddf632a0da0849fc98755a3 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_load_callback.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_LOAD_CALLBACK_H +#define SECURITY_COMPONENT_LOAD_CALLBACK_H + +#include "system_ability_load_callback_stub.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompLoadCallback : public SystemAbilityLoadCallbackStub { +public: + explicit SecCompLoadCallback(); + + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr& remoteObject); + void OnLoadSystemAbilityFail(int32_t systemAbilityId); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_LOAD_CALLBACK_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_proxy.h b/interfaces/inner_api/security_component/include/sec_comp_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..729877bcc026aa558e0abea0680a8db1cc431e56 --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_proxy.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_PROXY_H +#define SECURITY_COMPONENT_PROXY_H + +#include +#include "i_sec_comp_service.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompProxy : public IRemoteProxy { +public: + explicit SecCompProxy(const sptr& impl); + ~SecCompProxy() override; + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId) override; + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override; + int32_t UnregisterSecurityComponent(int32_t scId) override; + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) override; + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override; + sptr GetEnhanceRemoteObject() override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_PROXY_H diff --git a/interfaces/inner_api/security_component/include/sec_comp_ui_register.h b/interfaces/inner_api/security_component/include/sec_comp_ui_register.h new file mode 100644 index 0000000000000000000000000000000000000000..b415bb164fdbe6c384c6f12c253dd1ac67719d9c --- /dev/null +++ b/interfaces/inner_api/security_component/include/sec_comp_ui_register.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 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. + */ +#ifndef INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H +#define INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H + +#include "i_sec_comp_probe.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompUiRegister { +public: + SecCompUiRegister(std::vector& callerList, ISecCompProbe* probe); + virtual ~SecCompUiRegister() = default; + static ISecCompProbe* callbackProbe; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // INTERFACES_INNER_API_SECURITY_COMPONENT_UI_REGISTER_H + diff --git a/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h b/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h new file mode 100644 index 0000000000000000000000000000000000000000..a873e90f74de90df0b0d6f5bd90136dff0e2c17b --- /dev/null +++ b/interfaces/inner_api/security_component/include/security_component_service_ipc_interface_code.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SECURITY_COMPONENT_IPC_INTERFACE_CODE_H +#define SECURITY_COMPONENT_IPC_INTERFACE_CODE_H + +/* SAID: 3506 */ +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum SecurityComponentServiceInterfaceCode { + REGISTER_SECURITY_COMPONENT = 0, + UPDATE_SECURITY_COMPONENT = 1, + UNREGISTER_SECURITY_COMPONENT = 2, + REPORT_SECURITY_COMPONENT_CLICK_EVENT = 3, + GET_SECURITY_COMPONENT_ENHANCE_OBJECT = 4, + VERIFY_TEMP_SAVE_PERMISSION = 5, +}; + +enum EnhanceInterfaceCode { + REGISTER_CHECK_CALLBACK = 0, +}; + +enum EnhanceCallbackCheckCode { + GET_CALLER_SECURITY_COMPONENT_INFO = 0, +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_IPC_INTERFACE_CODE_H + diff --git a/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp b/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b98be285b612ac3528e4601f775143fa5a3c1e7c --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_caller_authorization.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_caller_authorization.h" + +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr int32_t MAX_FUNC_ASM_SIZE = 0x250; +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompCallerAuthorization"}; +static constexpr size_t MAX_CALLER_SIZE = 10; +} + +void SecCompCallerAuthorization::RegisterSecCompKitCaller(std::vector& callerList) +{ + if (isInit_) { + SC_LOG_ERROR(LABEL, "can not init repeatly"); + return; + } + + isInit_ = true; + if ((callerList.size() == 0) || (callerList.size() > MAX_CALLER_SIZE)) { + SC_LOG_ERROR(LABEL, "caller size is invalid"); + return; + } + + kitCallerList_ = callerList; +} + +bool SecCompCallerAuthorization::IsKitCaller(uintptr_t callerAddr) +{ + if (!isInit_) { + SC_LOG_INFO(LABEL, "caller authorization has not init"); + return true; + } + for (size_t i = 0; i < kitCallerList_.size(); i++) { + if ((callerAddr > kitCallerList_[i]) && (callerAddr < kitCallerList_[i] + MAX_FUNC_ASM_SIZE)) { + return true; + } + } + return false; +} + +SecCompCallerAuthorization& SecCompCallerAuthorization::GetInstance() +{ + static SecCompCallerAuthorization instance; + return instance; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/interfaces/inner_api/security_component/src/sec_comp_client.cpp b/interfaces/inner_api/security_component/src/sec_comp_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e20ceeabdc73b9da67c79848333a199d7dc165b --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_client.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_client.h" + +#include "iservice_registry.h" +#include "sec_comp_load_callback.h" +#include "sec_comp_log.h" +#include "sec_comp_proxy.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClient"}; +} // namespace + +SecCompClient& SecCompClient::GetInstance() +{ + static SecCompClient instance; + return instance; +} + +SecCompClient::SecCompClient() +{} + +SecCompClient::~SecCompClient() +{ + if (proxy_ == nullptr) { + return; + } + auto remoteObj = proxy_->AsObject(); + if (remoteObj == nullptr) { + return; + } + if (serviceDeathObserver_ != nullptr) { + remoteObj->RemoveDeathRecipient(serviceDeathObserver_); + } +} + +int32_t SecCompClient::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->RegisterSecurityComponent(type, componentInfo, scId); +} + +int32_t SecCompClient::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->UpdateSecurityComponent(scId, componentInfo); +} + +int32_t SecCompClient::UnregisterSecurityComponent(int32_t scId) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->UnregisterSecurityComponent(scId); +} + +int32_t SecCompClient::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + auto proxy = GetProxy(true); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return proxy->ReportSecurityComponentClickEvent(scId, componentInfo, touchInfo, callerToken); +} + +bool SecCompClient::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + auto proxy = GetProxy(false); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "Proxy is null"); + return false; + } + + return proxy->ReduceAfterVerifySavePermission(tokenId); +} + +sptr SecCompClient::GetEnhanceRemoteObject(bool doLoadSa) +{ + auto proxy = GetProxy(doLoadSa); + if (proxy == nullptr) { + return nullptr; + } + + return proxy->GetEnhanceRemoteObject(); +} + +bool SecCompClient::StartLoadSecCompSa() +{ + { + std::unique_lock lock(cvLock_); + readyFlag_ = false; + } + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + SC_LOG_ERROR(LABEL, "GetSystemAbilityManager return null"); + return false; + } + sptr ptrSecCompLoadCallback = + new (std::nothrow) SecCompLoadCallback(); + if (ptrSecCompLoadCallback == nullptr) { + SC_LOG_ERROR(LABEL, "New ptrSecCompLoadCallback fail."); + return false; + } + + int32_t result = sam->LoadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE, + ptrSecCompLoadCallback); + if (result != SC_OK) { + SC_LOG_ERROR(LABEL, "LoadSystemAbility %{public}d failed", SA_ID_SECURITY_COMPONENT_SERVICE); + return false; + } + SC_LOG_INFO(LABEL, "Notify samgr load sa %{public}d, waiting for service start", SA_ID_SECURITY_COMPONENT_SERVICE); + return true; +} + +bool SecCompClient::TryToGetSecCompSa() +{ + auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sam == nullptr) { + SC_LOG_ERROR(LABEL, "GetSystemAbilityManager return null"); + return false; + } + + auto secCompSa = sam->CheckSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (secCompSa == nullptr) { + SC_LOG_INFO(LABEL, "Service is not start."); + return false; + } + GetProxyFromRemoteObject(secCompSa); + return true; +} + +void SecCompClient::WaitForSecCompSa() +{ + // wait_for release lock and block until time out(1s) or match the condition with notice + std::unique_lock lock(cvLock_); + auto waitStatus = secComCon_.wait_for( + lock, std::chrono::milliseconds(SA_ID_SECURITY_COMPONENT_SERVICE), [this]() { return readyFlag_; }); + if (!waitStatus) { + // time out or loadcallback fail + SC_LOG_ERROR(LABEL, "security component load sa timeout"); + return; + } +} + +void SecCompClient::FinishStartSASuccess(const sptr& remoteObject) +{ + GetProxyFromRemoteObject(remoteObject); + // get lock which wait_for release and send a notice so that wait_for can out of block + std::unique_lock lock(cvLock_); + readyFlag_ = true; + secComCon_.notify_one(); +} + +void SecCompClient::FinishStartSAFail() +{ + SC_LOG_ERROR(LABEL, "get security component sa failed."); + // get lock which wait_for release and send a notice + std::unique_lock lock(cvLock_); + readyFlag_ = true; + secComCon_.notify_one(); +} + +void SecCompClient::LoadSecCompSa() +{ + if (!StartLoadSecCompSa()) { + return; + } + WaitForSecCompSa(); +} + +void SecCompClient::OnRemoteDiedHandle() +{ + SC_LOG_ERROR(LABEL, "Remote service died"); + std::unique_lock lock(proxyMutex_); + proxy_ = nullptr; + serviceDeathObserver_ = nullptr; + { + std::unique_lock lock1(cvLock_); + readyFlag_ = false; + } +} + +void SecCompClient::GetProxyFromRemoteObject(const sptr& remoteObject) +{ + if (remoteObject == nullptr) { + return; + } + + sptr serviceDeathObserver = new (std::nothrow) SecCompDeathRecipient(); + if (serviceDeathObserver == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc service death observer fail"); + return; + } + + if (!remoteObject->AddDeathRecipient(serviceDeathObserver)) { + SC_LOG_ERROR(LABEL, "Add service death observer fail"); + return; + } + + auto proxy = iface_cast(remoteObject); + if (proxy == nullptr) { + SC_LOG_ERROR(LABEL, "iface_cast get null"); + return; + } + proxy_ = proxy; + serviceDeathObserver_ = serviceDeathObserver; + SC_LOG_INFO(LABEL, "GetSystemAbility %{public}d success", SA_ID_SECURITY_COMPONENT_SERVICE); + return; +} + +sptr SecCompClient::GetProxy(bool doLoadSa) +{ + std::unique_lock lock(proxyMutex_); + if (proxy_ != nullptr) { + return proxy_; + } + if (TryToGetSecCompSa() || !doLoadSa) { + return proxy_; + } + + LoadSecCompSa(); + return proxy_; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp b/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbdf7fcb9c67e82a5439bb290a4e969ecd00ebd4 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_death_recipient.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_death_recipient.h" + +#include "sec_comp_client.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void SecCompDeathRecipient::OnRemoteDied(const wptr& object) +{ + SecCompClient::GetInstance().OnRemoteDiedHandle(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_kit.cpp b/interfaces/inner_api/security_component/src/sec_comp_kit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05b7bd2472c4764086526fbf692a6c35aecada2c --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_kit.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_kit.h" + +#include "hisysevent.h" +#include "ipc_skeleton.h" +#include "sec_comp_caller_authorization.h" +#include "sec_comp_client.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompKit"}; +} // namespace + +int32_t SecCompKit::RegisterSecurityComponent(SecCompType type, + std::string& componentInfo, int32_t& scId) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "register security component fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "REGITSTER"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompClient::GetInstance().RegisterSecurityComponent(type, componentInfo, scId); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "register security component fail, error: %{public}d", res); + return res; + } + SecCompEnhanceAdapter::RegisterScIdEnhance(scId); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "REGISTER_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", type); + return res; +} + +int32_t SecCompKit::UpdateSecurityComponent(int32_t scId, std::string& componentInfo) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "update security component fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "UPDATE"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(scId, componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompClient::GetInstance().UpdateSecurityComponent(scId, componentInfo); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "update security component fail, error: %{public}d", res); + } + return res; +} + +int32_t SecCompKit::UnregisterSecurityComponent(int32_t scId) +{ + int32_t res = SecCompClient::GetInstance().UnregisterSecurityComponent(scId); + SecCompEnhanceAdapter::UnregisterScIdEnhance(scId); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "unregister security component fail, error: %{public}d", res); + return res; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "UNREGISTER_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId); + return res; +} + +int32_t SecCompKit::ReportSecurityComponentClickEvent(int32_t scId, + std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + if (!SecCompCallerAuthorization::GetInstance().IsKitCaller( + reinterpret_cast(__builtin_return_address(0)))) { + SC_LOG_ERROR(LABEL, "report click event fail, caller invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLER_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "CALL_SCENE", "CLICK"); + return SC_SERVICE_ERROR_CALLER_INVALID; + } + + if (!SecCompEnhanceAdapter::EnhanceDataPreprocess(scId, componentInfo)) { + SC_LOG_ERROR(LABEL, "Preprocess security component fail"); + return SC_ENHANCE_ERROR_VALUE_INVALID; + } + + int32_t res = + SecCompClient::GetInstance().ReportSecurityComponentClickEvent(scId, componentInfo, touchInfo, callerToken); + if (res != SC_OK) { + SC_LOG_ERROR(LABEL, "report click event fail, error: %{public}d", res); + } + return res; +} + +bool SecCompKit::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + bool res = + SecCompClient::GetInstance().ReduceAfterVerifySavePermission(tokenId); + if (!res) { + SC_LOG_ERROR(LABEL, "verify temp save permission, error: %{public}d", res); + } + return res; +} + +sptr SecCompKit::GetEnhanceRemoteObject(bool isLoad) +{ + return SecCompClient::GetInstance().GetEnhanceRemoteObject(isLoad); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp b/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fd9f263797e6b51c1aea5af9ffc4e7dfd131565 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_load_callback.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_load_callback.h" + +#include "i_sec_comp_service.h" +#include "sec_comp_client.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompClient"}; +} // namespace +SecCompLoadCallback::SecCompLoadCallback() {} + +void SecCompLoadCallback::OnLoadSystemAbilitySuccess( + int32_t systemAbilityId, const sptr& remoteObject) +{ + if (systemAbilityId != SA_ID_SECURITY_COMPONENT_SERVICE) { + SC_LOG_ERROR(LABEL, "start systemabilityId is not security_component!"); + return; + } + + if (remoteObject == nullptr) { + SC_LOG_ERROR(LABEL, "remoteObject is null."); + SecCompClient::GetInstance().FinishStartSAFail(); + return; + } + + SC_LOG_INFO(LABEL, "Start systemAbilityId: %{public}d success!", systemAbilityId); + + SecCompClient::GetInstance().FinishStartSASuccess(remoteObject); +} + +void SecCompLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + if (systemAbilityId != SA_ID_SECURITY_COMPONENT_SERVICE) { + SC_LOG_ERROR(LABEL, "start systemabilityId is not security_component!"); + return; + } + + SC_LOG_ERROR(LABEL, "Start systemAbilityId: %{public}d failed.", systemAbilityId); + + SecCompClient::GetInstance().FinishStartSAFail(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp b/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f61833ce2353b6e3c019a56e4fd4508323d54544 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_proxy.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_proxy.h" + +#include "sec_comp_click_event_parcel.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompProxy"}; +} + +SecCompProxy::SecCompProxy(const sptr& impl) : IRemoteProxy(impl) +{} + +SecCompProxy::~SecCompProxy() +{} + +int32_t SecCompProxy::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteUint32(type)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL + } + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read result int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!reply.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read scId int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT), data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read result int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::UnregisterSecurityComponent(int32_t scId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +int32_t SecCompProxy::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!data.WriteString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Write string fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + sptr parcel = new (std::nothrow) SecCompClickEventParcel(); + if (parcel == nullptr) { + SC_LOG_ERROR(LABEL, "New click event parcel failed"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + parcel->touchInfoParams_ = touchInfo; + if (!data.WriteParcelable(parcel)) { + SC_LOG_ERROR(LABEL, "Write touchInfo fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if ((callerToken != nullptr) && !data.WriteRemoteObject(callerToken)) { + SC_LOG_ERROR(LABEL, "Write caller token fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return requestResult; + } + int32_t res; + if (!reply.ReadInt32(res)) { + SC_LOG_ERROR(LABEL, "Read int32 fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return res; +} + +bool SecCompProxy::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return false; + } + + if (!data.WriteUint32(tokenId)) { + SC_LOG_ERROR(LABEL, "Write Uint32 fail"); + return false; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return false; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return false; + } + bool res; + if (!reply.ReadBool(res)) { + SC_LOG_ERROR(LABEL, "Read bool fail"); + return false; + } + return res; +} + +sptr SecCompProxy::GetEnhanceRemoteObject() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(SecCompProxy::GetDescriptor())) { + SC_LOG_ERROR(LABEL, "Write descriptor fail"); + return nullptr; + } + + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + sptr remote = Remote(); + if (remote == nullptr) { + SC_LOG_ERROR(LABEL, "Remote service is null"); + return nullptr; + } + int32_t requestResult = remote->SendRequest( + static_cast(SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT), + data, reply, option); + if (requestResult != SC_OK) { + SC_LOG_ERROR(LABEL, "Request fail, result: %{public}d", requestResult); + return nullptr; + } + sptr callback = reply.ReadRemoteObject(); + if (callback == nullptr) { + SC_LOG_ERROR(LABEL, "Read remote object fail"); + } + return callback; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp b/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a94215f6da0093abd6ec7b8069e8275e7a2b1234 --- /dev/null +++ b/interfaces/inner_api/security_component/src/sec_comp_ui_register.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_ui_register.h" + +#include "sec_comp_caller_authorization.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompUiRegister"}; +} // namespace + +ISecCompProbe* SecCompUiRegister::callbackProbe = nullptr; + +SecCompUiRegister::SecCompUiRegister(std::vector& callerList, ISecCompProbe* probe) +{ + SC_LOG_INFO(LABEL, "Init"); + SecCompCallerAuthorization::GetInstance().RegisterSecCompKitCaller(callerList); + callbackProbe = probe; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/interfaces/inner_api/security_component/test/BUILD.gn b/interfaces/inner_api/security_component/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0aabcdc2703c15c74ddd94b5a1a5d4c06d4d58af --- /dev/null +++ b/interfaces/inner_api/security_component/test/BUILD.gn @@ -0,0 +1,191 @@ +# Copyright (c) 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("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_sdk_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_test.cpp", + "unittest/src/paste_button_test.cpp", + "unittest/src/save_button_test.cpp", + "unittest/src/sec_comp_kit_test.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +ohos_unittest("sec_comp_register_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_sample_build.cpp", + "unittest/src/sec_comp_register_callback_test.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +ohos_unittest("sec_comp_report_click_without_hmac_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_sample_build.cpp", + "unittest/src/sec_comp_report_click_without_hmac_test.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +ohos_unittest("sec_comp_register_without_callback_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_sample_build.cpp", + "unittest/src/sec_comp_register_without_callback_test.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +ohos_unittest("sec_comp_register_challenge_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "unittest/src/location_button_sample_build.cpp", + "unittest/src/sec_comp_register_challenge_test.cpp", + ] + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "${sec_comp_root_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ + ":sec_comp_sdk_test", + ":sec_comp_register_challenge_test", + ":sec_comp_register_test", + ":sec_comp_register_without_callback_test", + ":sec_comp_report_click_without_hmac_test" + ] +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.cpp b/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cdb68d20c056bf4f20a045acdc622b826481606 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 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. + */ +#include "location_button_sample_build.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +static const std::string WRONG_TYPE = "wrongType"; +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0xffffff00; +static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; + +void LocationButtonSampleBuild::BuildLocationComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.h b/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.h new file mode 100644 index 0000000000000000000000000000000000000000..9bde8927e0d48848b3093570ffddce1dadfe6c5a --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_sample_build.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 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. + */ + +#ifndef LOCATION_BUTTON_SAMPLE_BUILD_H +#define LOCATION_BUTTON_SAMPLE_BUILD_H +#include "location_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { + +class LocationButtonSampleBuild { +public: + static void BuildLocationComponentInfo(nlohmann::json& jsonComponent); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // LOCATION_BUTTON_SAMPLE_BUILD_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef7503ae2e55710b103f182aeee5665bc329ebdf --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.cpp @@ -0,0 +1,607 @@ +/* + * Copyright (c) 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. + */ +#include "location_button_test.h" +#include +#include "sec_comp_log.h" +#include "sec_comp_err.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "LocationButtonTest"}; + +static const std::string WRONG_TYPE = "wrongType"; +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0x7ffff00; +static constexpr uint32_t TEST_COLOR_RED = 0xff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0x0000ff; +static constexpr uint32_t TEST_DIFF_COLOR = 0; + +static void BuildLocationComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} + +void LocationButtonTest::SetUpTestCase() +{} + +void LocationButtonTest::TearDownTestCase() +{} + +void LocationButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void LocationButtonTest::TearDown() +{} + +/** + * @tc.name: FromJson001 + * @tc.desc: Test LocationButton from json success + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton comp; + ASSERT_TRUE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson002 + * @tc.desc: Test empty LocationButton from json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson003 + * @tc.desc: Test location button from wrong type json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton comp; + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = WRONG_TYPE; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = 0; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson004 + * @tc.desc: Test location button from wrong rect json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson004, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + nlohmann::json wrongJson = nlohmann::json::parse("{", nullptr, false); + jsonComponent[JsonTagConstants::JSON_RECT] = wrongJson; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, WRONG_TYPE}, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE}, + {JsonTagConstants::JSON_RECT_HEIGHT, WRONG_TYPE} + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson005 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson005, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson006 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson006, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson007 + * @tc.desc: Test location button from wrong size json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson007, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, WRONG_TYPE }, + }; + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson008 + * @tc.desc: Test location button from wrong border and parent json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson008, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp; + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); + + BuildLocationComponentInfo(jsonComponent); + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(comp.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson009 + * @tc.desc: Test location button from wrong type params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson009, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton button; + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, WRONG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson010 + * @tc.desc: Test location button from wrong type params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton button; + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, WRONG_TYPE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, WRONG_TYPE } + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: FromJson011 + * @tc.desc: Test location button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, FromJson011, TestSize.Level1) +{ +nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: ToJsonStr001 + * @tc.desc: Test ToJsonStr normal branch + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, ToJsonStr001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + ASSERT_EQ(jsonComponent.dump(), button.ToJsonStr()); +} + +/** + * @tc.name: CompareComponentBasicInfo001 + * @tc.desc: Test CompareComponentBasicInfo other is null + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareComponentBasicInfo001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + LocationButton button; + + ASSERT_FALSE(button.CompareComponentBasicInfo(nullptr, true)); +} + +/** + * @tc.name: CompareLocationButton001 + * @tc.desc: Test compare location button + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareLocationButton001, TestSize.Level1) +{ + LocationButton button1; + LocationButton button2; + + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(LocationDesc::SELECT_LOCATION); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(LocationIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: CompareLocationButton002 + * @tc.desc: Test LocationButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(LocationButtonTest, CompareLocationButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + LocationButton comp1; + BuildLocationComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + LocationButton comp2 = comp1; + + comp1.type_ = SAVE_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = LOCATION_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TEST_SIZE; + + comp1.fontColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TEST_COLOR_RED; + + comp1.bgColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7324bd73e3b2b12313a6c7cef783030e4c3fc192 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/location_button_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_LOCATION_BUTTON_TEST_H +#define SEC_COMP_LOCATION_BUTTON_TEST_H + +#include +#include "location_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class LocationButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_LOCATION_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..625c4acebcd80e1432943020717745b1498cfab3 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.cpp @@ -0,0 +1,254 @@ +/* + * Copyright (c) 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. + */ +#include "paste_button_test.h" +#include +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "PasteButtonTest"}; + +static const std::string WRONG_TYPE = "wrongType"; +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0x7ffff00; +static constexpr uint32_t TEST_COLOR_RED = 0xff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0x0000ff; +static constexpr uint32_t TEST_DIFF_COLOR = 0; + +static void BuildPasteComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = PASTE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} + +void PasteButtonTest::SetUpTestCase() +{} + +void PasteButtonTest::TearDownTestCase() +{} + +void PasteButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void PasteButtonTest::TearDown() +{} + +/** + * @tc.name: IsParamValid001 + * @tc.desc: Test paste button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, FromJson010, TestSize.Level1) +{ +nlohmann::json jsonComponent; + BuildPasteComponentInfo(jsonComponent); + PasteButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE}, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, PasteDesc::PASTE }, + { JsonTagConstants::JSON_ICON_TAG, PasteIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: ComparePasteButton001 + * @tc.desc: Test compare paste button + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, ComparePasteButton001, TestSize.Level1) +{ + PasteButton button1; + PasteButton button2; + + nlohmann::json jsonComponent; + BuildPasteComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(PasteDesc::PASTE); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(PasteIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: ComparePasteButton002 + * @tc.desc: Test PasteButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9JB + */ +HWTEST_F(PasteButtonTest, ComparePasteButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + PasteButton comp1; + BuildPasteComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + PasteButton comp2 = comp1; + + comp1.type_ = LOCATION_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = PASTE_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TEST_SIZE; + + comp1.fontColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TEST_COLOR_RED; + + comp1.bgColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} \ No newline at end of file diff --git a/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..6e73d91cb198d05934540909dce27f25e2dc8326 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/paste_button_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_PASTE_BUTTON_TEST_H +#define SEC_COMP_PASTE_BUTTON_TEST_H + +#include +#include "paste_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class PasteButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_PASTE_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8771c78b7015ac2b04dc478cefe19c7f35b27ec6 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.cpp @@ -0,0 +1,253 @@ +/* + * Copyright (c) 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. + */ +#include "save_button_test.h" +#include +#include "sec_comp_log.h" +#include "sec_comp_err.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SaveButtonTest"}; + +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0x7ffff00; +static constexpr uint32_t TEST_COLOR_RED = 0xff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0x0000ff; +static constexpr uint32_t TEST_DIFF_COLOR = 0; + +static void BuildSaveComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = SAVE_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_Y, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_WIDTH, TEST_COORDINATE }, + {JsonTagConstants::JSON_RECT_HEIGHT, TEST_COORDINATE } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} + +void SaveButtonTest::SetUpTestCase() +{} + +void SaveButtonTest::TearDownTestCase() +{} + +void SaveButtonTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SaveButtonTest::TearDown() +{} + +/** + * @tc.name: IsParamValid001 + * @tc.desc: Test save button from wrong value params json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, FromJson010, TestSize.Level1) +{ +nlohmann::json jsonComponent; + BuildSaveComponentInfo(jsonComponent); + SaveButton button; + + ASSERT_TRUE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, UNKNOWN_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD}, + { JsonTagConstants::JSON_ICON_TAG, UNKNOWN_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::UNKNOWN_BG }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::MAX_LABEL_TYPE }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::MAX_ICON_TYPE }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, SaveDesc::DOWNLOAD }, + { JsonTagConstants::JSON_ICON_TAG, SaveIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::MAX_BG_TYPE }, + }; + ASSERT_FALSE(button.FromJson(jsonComponent)); +} + +/** + * @tc.name: CompareSaveButton001 + * @tc.desc: Test compare save button + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, CompareSaveButton001, TestSize.Level1) +{ + SaveButton button1; + SaveButton button2; + + nlohmann::json jsonComponent; + BuildSaveComponentInfo(jsonComponent); + + ASSERT_TRUE(button1.FromJson(jsonComponent)); + ASSERT_TRUE(button2.FromJson(jsonComponent)); + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); + + button1.text_ = UNKNOWN_TEXT; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.text_ = static_cast(SaveDesc::DOWNLOAD); + + button1.icon_ = UNKNOWN_ICON; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.icon_ = static_cast(SaveIcon::LINE_ICON); + + button1.bg_ = SecCompBackground::UNKNOWN_BG; + ASSERT_FALSE(button1.CompareComponentBasicInfo(&button2, true)); + button1.bg_ = SecCompBackground::CIRCLE; + + ASSERT_TRUE(button1.CompareComponentBasicInfo(&button2, true)); +} + +/** + * @tc.name: CompareSaveButton002 + * @tc.desc: Test SaveButton compare + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SaveButtonTest, CompareSaveButton002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + SaveButton comp1; + BuildSaveComponentInfo(jsonComponent); + ASSERT_TRUE(comp1.FromJson(jsonComponent)); + SaveButton comp2 = comp1; + + comp1.type_ = PASTE_COMPONENT; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.type_ = SAVE_COMPONENT; + + comp1.fontSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontSize_ = TEST_SIZE; + + comp1.iconSize_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconSize_ = TEST_SIZE; + + comp1.padding_.top = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.top = TEST_DIMENSION; + + comp1.padding_.right = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.right = TEST_DIMENSION; + + comp1.padding_.bottom = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.bottom = TEST_DIMENSION; + + comp1.padding_.left = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.padding_.left = TEST_DIMENSION; + + comp1.textIconSpace_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.textIconSpace_ = TEST_SIZE; + + comp1.borderWidth_ = DEFAULT_DIMENSION; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.borderWidth_ = TEST_SIZE; + + comp1.fontColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.fontColor_.value = TEST_COLOR_RED; + + comp1.bgColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.bgColor_.value = TEST_COLOR_YELLOW; + + comp1.iconColor_.value = TEST_DIFF_COLOR; + ASSERT_FALSE(comp1.CompareComponentBasicInfo(&comp2, true)); + comp1.iconColor_.value = TEST_COLOR_BLUE; + + ASSERT_TRUE(comp1.CompareComponentBasicInfo(&comp2, true)); +} \ No newline at end of file diff --git a/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h new file mode 100644 index 0000000000000000000000000000000000000000..34c9f6adc60ba9134ba27d82108af6dfafd779fa --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/save_button_test.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_SAVE_BUTTON_TEST_H +#define SEC_COMP_SAVE_BUTTON_TEST_H + +#include +#include "save_button.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SaveButtonTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_SAVE_BUTTON_TEST_H diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c43a610b1d2d319ad2966ca12c99be41b0a4f9c0 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_kit_test.h" +#include "location_button.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompKitTest"}; +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr uint32_t TEST_COLOR = 0xffffffff; +static constexpr size_t MAX_CALLER_SIZE = 10; + +static void TestInCallerNotCheckList() +{ + int32_t scId = -1; + struct SecCompClickEvent touch; + std::string emptyStr = ""; + int registerRes = SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, emptyStr, scId); + int updateRes = SecCompKit::UpdateSecurityComponent(scId, emptyStr); + int reportRes = SecCompKit::ReportSecurityComponentClickEvent(scId, emptyStr, touch, nullptr); + + EXPECT_EQ(registerRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_EQ(updateRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_EQ(reportRes, SC_SERVICE_ERROR_CALLER_INVALID); +} + +static void TestInCallerCheckList() +{ + int32_t scId = -1; + struct SecCompClickEvent touch; + std::string emptyStr = ""; + int registerRes = SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, emptyStr, scId); + int updateRes = SecCompKit::UpdateSecurityComponent(scId, emptyStr); + int reportRes = SecCompKit::ReportSecurityComponentClickEvent(scId, emptyStr, touch, nullptr); + + EXPECT_NE(registerRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_NE(updateRes, SC_SERVICE_ERROR_CALLER_INVALID); + EXPECT_NE(reportRes, SC_SERVICE_ERROR_CALLER_INVALID); +} +} // namespace + +void SecCompKitTest::SetUpTestCase() +{ + SC_LOG_INFO(LABEL, "SetUpTestCase."); +} + +void SecCompKitTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "TearDownTestCase."); +} + +void SecCompKitTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompKitTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: ExceptCall001 + * @tc.desc: do kit except call. + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompKitTest, ExceptCall001, TestSize.Level1) +{ + LocationButton comp; + comp.fontSize_ = TEST_SIZE; + comp.iconSize_ = TEST_SIZE; + comp.padding_.top = TEST_DIMENSION; + comp.padding_.right = TEST_DIMENSION; + comp.padding_.bottom = TEST_DIMENSION; + comp.padding_.left = TEST_DIMENSION; + comp.textIconSpace_ = TEST_SIZE; + comp.bgColor_.value = TEST_COLOR; + comp.fontColor_.value = TEST_COLOR; + comp.iconColor_.value = TEST_COLOR; + comp.borderWidth_ = TEST_SIZE; + comp.parentEffect_ = true; + comp.type_ = LOCATION_COMPONENT; + comp.rect_.x_ = TEST_COORDINATE; + comp.rect_.y_ = TEST_COORDINATE; + comp.rect_.width_ = TEST_COORDINATE; + comp.rect_.height_ = TEST_COORDINATE; + + nlohmann::json jsonRes; + comp.ToJson(jsonRes); + int32_t scId = -1; + std::string jsonStr = jsonRes.dump(); + ASSERT_NE(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, jsonStr, scId)); + ASSERT_EQ(-1, scId); + ASSERT_NE(SC_OK, SecCompKit::UpdateSecurityComponent(scId, jsonStr)); + + struct SecCompClickEvent touch = { + .touchX = TEST_COORDINATE, + .touchY = TEST_COORDINATE, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + EXPECT_NE(SC_OK, SecCompKit::ReportSecurityComponentClickEvent(scId, jsonStr, touch, nullptr)); + EXPECT_NE(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: ExceptCall001 + * @tc.desc: test caller check. + * @tc.type: FUNC + * @tc.require: AR000HO9JS + */ +HWTEST_F(SecCompKitTest, TestCallerCheck001, TestSize.Level1) +{ + std::vector callerList = { + reinterpret_cast(TestInCallerCheckList), + }; + SecCompUiRegister registerCallback(callerList, nullptr); + TestInCallerCheckList(); + TestInCallerNotCheckList(); + + // prohibit init caller list repeately + std::vector callerList1 = { + reinterpret_cast(TestInCallerNotCheckList), + }; + SecCompUiRegister registerCallback1(callerList1, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} + +/** + * @tc.name: ExceptCall002 + * @tc.desc: test invalid caller register. + * @tc.type: FUNC + * @tc.require: AR000HO9JS + */ +HWTEST_F(SecCompKitTest, TestCallerCheck002, TestSize.Level1) +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; + + for (size_t i = 0; i < MAX_CALLER_SIZE + 1; i++) { + callerList.emplace_back(reinterpret_cast(TestInCallerNotCheckList)); + } + SecCompUiRegister registerCallback2(callerList, nullptr); + TestInCallerNotCheckList(); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} + diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..3bd124102c671cb161bfa59bced2f511397809f5 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_kit_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_KIT_TEST +#define SECURITY_COMPONENT_KIT_TEST + +#include +#include "sec_comp_kit.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompKitTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_KIT_TEST \ No newline at end of file diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e90704811ea325c66b05057c6b7e50c60a3d5342 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_callback_test.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 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. + */ +#include + +#include "i_sec_comp_probe.h" +#include "location_button.h" +#include "location_button_sample_build.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_kit.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_ui_register.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompRegisterCallbackTest"}; + +class MockUiSecCompProbe : public ISecCompProbe { +public: + int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) override + { + componentInfo = mockComponentInfo; + return mockRes; + } + std::string mockComponentInfo; + int32_t mockRes; +}; + +static MockUiSecCompProbe g_probe; +static void InitUiRegister() +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, &g_probe); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} +} // namespace + +class SecCompRegisterCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; + +void SecCompRegisterCallbackTest::SetUpTestCase() +{ + InitUiRegister(); + SC_LOG_INFO(LABEL, "SecCompRegisterCallbackTest."); +} + +void SecCompRegisterCallbackTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "SecCompRegisterCallbackTest."); +} + +void SecCompRegisterCallbackTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompRegisterCallbackTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: Register001 + * @tc.desc: test register security component success. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register001, TestSize.Level1) +{ + SC_LOG_INFO(LABEL, "Register001."); + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_NE(-1, scId); + + EXPECT_EQ(SC_OK, SecCompKit::UnregisterSecurityComponent(scId)); +} + +/** + * @tc.name: Register002 + * @tc.desc: test register callback failed. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register002, TestSize.Level1) +{ + SC_LOG_INFO(LABEL, "Register002."); + + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = -1; + + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL, + SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} + +/** + * @tc.name: Register003 + * @tc.desc: test register in MaliciousAppList. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterCallbackTest, Register003, TestSize.Level1) +{ + SC_LOG_INFO(LABEL, "Register003."); + + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); +} + diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_challenge_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_challenge_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7e0273d2e504e8419e657370e747579e1456c9b --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_challenge_test.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 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. + */ +#include + +#include "i_sec_comp_probe.h" +#include "location_button.h" +#include "location_button_sample_build.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_client.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_kit.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_ui_register.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompRegisterChallengeTest"}; + +class MockUiSecCompProbe : public ISecCompProbe { +public: + int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) override + { + componentInfo = mockComponentInfo; + return mockRes; + } + std::string mockComponentInfo; + int32_t mockRes; +}; + +static MockUiSecCompProbe g_probe; + +static void InitUiRegister() +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, &g_probe); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} +} // namespace + +class SecCompRegisterChallengeTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; + +void SecCompRegisterChallengeTest::SetUpTestCase() +{ + InitUiRegister(); + SC_LOG_INFO(LABEL, "SecCompRegisterChallengeTest."); +} + +void SecCompRegisterChallengeTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "SecCompRegisterChallengeTest."); +} + +void SecCompRegisterChallengeTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompRegisterChallengeTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: RegisterWithoutPreprocess001 + * @tc.desc: test register without preprocess + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterChallengeTest, RegisterWithoutPreprocess001, TestSize.Level1) +{ + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + + SecCompEnhanceAdapter::InitEnhanceHandler(SEC_COMP_ENHANCE_CLIENT_INTERFACE); + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL, + SecCompClient::GetInstance().RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} + diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_without_callback_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_without_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c835ca8521ca52f5f360f7c0853b9adfc95579e --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_register_without_callback_test.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 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. + */ +#include + +#include "i_sec_comp_probe.h" +#include "location_button.h" +#include "location_button_sample_build.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_kit.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_ui_register.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompRegisterWithoutCallbackTest"}; + +static void InitUiRegister() +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, nullptr); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} +} // namespace + +class SecCompRegisterWithoutCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; + +void SecCompRegisterWithoutCallbackTest::SetUpTestCase() +{ + InitUiRegister(); + SC_LOG_INFO(LABEL, "SecCompRegisterWithoutCallbackTest."); +} + +void SecCompRegisterWithoutCallbackTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "SecCompRegisterWithoutCallbackTest."); +} + +void SecCompRegisterWithoutCallbackTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompRegisterWithoutCallbackTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: RegisterWithoutCallback001 + * @tc.desc: test register without callback + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterWithoutCallbackTest, RegisterWithoutCallback001, TestSize.Level1) +{ + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST, + SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} + +/** + * @tc.name: RegisterWithoutCallback002 + * @tc.desc: test register in MaliciousAppList. + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompRegisterWithoutCallbackTest, RegisterWithoutCallback002, TestSize.Level1) +{ + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + + int32_t scId; + ASSERT_EQ(SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST, + SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_EQ(-1, scId); +} diff --git a/interfaces/inner_api/security_component/test/unittest/src/sec_comp_report_click_without_hmac_test.cpp b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_report_click_without_hmac_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c59fb21f0f2ea7afe8ae55b58914352a7197e29 --- /dev/null +++ b/interfaces/inner_api/security_component/test/unittest/src/sec_comp_report_click_without_hmac_test.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 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. + */ +#include + +#include "i_sec_comp_probe.h" +#include "location_button.h" +#include "location_button_sample_build.h" +#define private public +#include "sec_comp_caller_authorization.h" +#undef private +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_comp_kit.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_ui_register.h" + +using namespace testing::ext; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompReportClickWithoutHmacTest"}; +static constexpr double TEST_COORDINATE = 100.0; + +class MockUiSecCompProbe : public ISecCompProbe { +public: + int32_t GetComponentInfo(int32_t nodeId, std::string& componentInfo) override + { + componentInfo = mockComponentInfo; + return mockRes; + } + std::string mockComponentInfo; + int32_t mockRes; +}; + +static MockUiSecCompProbe g_probe; +static void InitUiRegister() +{ + std::vector callerList; + SecCompUiRegister registerCallback(callerList, &g_probe); + SecCompCallerAuthorization::GetInstance().kitCallerList_.clear(); + SecCompCallerAuthorization::GetInstance().isInit_ = false; +} +} // namespace + +class SecCompReportClickWithoutHmacTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp() override; + + void TearDown() override; +}; + +void SecCompReportClickWithoutHmacTest::SetUpTestCase() +{ + InitUiRegister(); + SC_LOG_INFO(LABEL, "SecCompReportClickWithoutHmacTest."); +} + +void SecCompReportClickWithoutHmacTest::TearDownTestCase() +{ + SC_LOG_INFO(LABEL, "SecCompReportClickWithoutHmacTest."); +} + +void SecCompReportClickWithoutHmacTest::SetUp() +{ + SC_LOG_INFO(LABEL, "SetUp ok."); +} + +void SecCompReportClickWithoutHmacTest::TearDown() +{ + SC_LOG_INFO(LABEL, "TearDown."); +} + +/** + * @tc.name: ReportClickWithoutHmac001 + * @tc.desc: test report click event without hmac data + * @tc.type: FUNC + * @tc.require: AR000HO9JM + */ +HWTEST_F(SecCompReportClickWithoutHmacTest, ReportClickWithoutHmac001, TestSize.Level1) +{ + nlohmann::json jsonRes; + LocationButtonSampleBuild::BuildLocationComponentInfo(jsonRes); + std::string locationInfo = jsonRes.dump(); + g_probe.mockComponentInfo = locationInfo; + g_probe.mockRes = 0; + + int32_t scId; + ASSERT_EQ(SC_OK, SecCompKit::RegisterSecurityComponent(LOCATION_COMPONENT, locationInfo, scId)); + ASSERT_NE(-1, scId); + + struct SecCompClickEvent touch = { + .touchX = TEST_COORDINATE, + .touchY = TEST_COORDINATE, + .timestamp = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + EXPECT_EQ(SC_SERVICE_ERROR_CLICK_EVENT_INVALID, + SecCompKit::ReportSecurityComponentClickEvent(scId, locationInfo, touch, nullptr)); +} diff --git a/patches/patches.json b/patches/patches.json new file mode 100644 index 0000000000000000000000000000000000000000..3fd8b0293fc04bd4590d905a08f0139aca20ae1a --- /dev/null +++ b/patches/patches.json @@ -0,0 +1,9 @@ +{ + "patches": [ + { + "project":"productdefine_common", + "path":"productdefine/common", + "pr_url":"https://gitee.com/openharmony/productdefine_common/pulls/693" + } + ] +} \ No newline at end of file diff --git a/security_component.gni b/security_component.gni new file mode 100644 index 0000000000000000000000000000000000000000..f92bdb19a951625547cfe81a7d40c3ce5dff0707 --- /dev/null +++ b/security_component.gni @@ -0,0 +1,14 @@ +# Copyright (c) 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. + +sec_comp_dir = "//base/security/security_component" diff --git a/services/security_component_service/sa/BUILD.gn b/services/security_component_service/sa/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4cc4ace089e6cb9d494c9d6ddb1937f547648b86 --- /dev/null +++ b/services/security_component_service/sa/BUILD.gn @@ -0,0 +1,91 @@ +# Copyright (c) 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("//build/ohos.gni") + +sec_comp_root_dir = "../../.." + +config("security_component_service_config") { + include_dirs = [ + "sa_main", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] +} + +ohos_prebuilt_etc("security_component_service.rc") { + source = "security_component_service.cfg" + relative_install_dir = "init" + subsystem_name = "security" + part_name = "security_component" +} + +ohos_shared_library("security_component_service") { + subsystem_name = "security" + part_name = "security_component" + + include_dirs = [ + "sa_main", + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + ] + + sources = [ + "sa_main/app_mgr_death_recipient.cpp", + "sa_main/app_state_observer.cpp", + "sa_main/delay_exit_task.cpp", + "sa_main/first_use_dialog.cpp", + "sa_main/sec_comp_entity.cpp", + "sa_main/sec_comp_info_helper.cpp", + "sa_main/sec_comp_manager.cpp", + "sa_main/sec_comp_perm_manager.cpp", + "sa_main/sec_comp_service.cpp", + "sa_main/sec_comp_stub.cpp", + "sa_main/sec_event_handler.cpp", + ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + cflags = [ "-DHILOG_ENABLE" ] + + deps = [ + ":security_component_service.rc", + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + public_configs = [ ":security_component_service_config" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:runtime", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libdm", + ] +} diff --git a/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e37725810df2eee82a11734d6e4c7fc82064484 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 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. + */ +#include "app_mgr_death_recipient.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +void AppMgrDeathRecipient::OnRemoteDied(const wptr& object) +{ + SecCompManager::GetInstance().ExitWhenAppMgrDied(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..d4dc41c1dbe8328c7b1b7292d619ac2f70a04ac0 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_mgr_death_recipient.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 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. + */ +#ifndef APP_MGR_DEATH_RECIPIENT_H +#define APP_MGR_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { +public: + AppMgrDeathRecipient() {} + virtual ~AppMgrDeathRecipient() = default; + void OnRemoteDied(const wptr& object) override; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // APP_MGR_DEATH_RECIPIENT_H + diff --git a/services/security_component_service/sa/sa_main/app_state_observer.cpp b/services/security_component_service/sa/sa_main/app_state_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be4fa4e23221265154929bd36e369f0c094202e9 --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_state_observer.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 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. + */ +#include "app_state_observer.h" + +#include "sec_comp_log.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "AppStateObserver"}; +} + +AppStateObserver::AppStateObserver() +{ +} + +AppStateObserver::~AppStateObserver() +{ +} + +bool AppStateObserver::IsProcessForeground(int32_t pid, int32_t uid) +{ + Utils::UniqueReadGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (pid == iter->pid) { + return true; + } + + if ((iter->pid == -1) && (uid == iter->uid)) { + iter->pid = pid; + return true; + } + } + return false; +} + +void AppStateObserver::AddProcessToForegroundSet(int32_t pid, const SecCompProcessData& data) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (pid == -1) { + if (iter->uid == data.uid) { + SC_LOG_INFO(LABEL, "uid %{public}d is already in foreground", data.uid); + return; + } + } else if (pid == iter->pid) { + SC_LOG_INFO(LABEL, "pid %{public}d is already in foreground", pid); + return; + } + } + foregrandProcList_.emplace_back(data); +} + +void AppStateObserver::AddProcessToForegroundSet(const AppExecFwk::AppStateData& stateData) +{ + SecCompProcessData proc = { + .bundleName = stateData.bundleName, + .pid = stateData.pid, + .uid = stateData.uid + }; + AddProcessToForegroundSet(stateData.pid, proc); +} + +void AppStateObserver::AddProcessToForegroundSet(const AppExecFwk::ProcessData &processData) +{ + SecCompProcessData proc = { + .bundleName = processData.bundleName, + .pid = processData.pid, + .uid = processData.uid + }; + AddProcessToForegroundSet(processData.pid, proc); +} + +void AppStateObserver::RemoveProcessFromForegroundSet(const AppExecFwk::ProcessData &processData) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + if (processData.pid == iter->pid) { + foregrandProcList_.erase(iter); + return; + } + } +} + +void AppStateObserver::OnProcessStateChanged(const AppExecFwk::ProcessData &processData) +{ + if (processData.state == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) { + AddProcessToForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessForeground(processData.pid); + } else if (processData.state == AppExecFwk::AppProcessState::APP_STATE_BACKGROUND) { + RemoveProcessFromForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessBackground(processData.pid); + } +} + +void AppStateObserver::OnProcessDied(const AppExecFwk::ProcessData& processData) +{ + SC_LOG_INFO(LABEL, "OnProcessDied die %{public}s pid %{public}d", + processData.bundleName.c_str(), processData.pid); + RemoveProcessFromForegroundSet(processData); + SecCompManager::GetInstance().NotifyProcessDied(processData.pid); +} + +void AppStateObserver::DumpProcess(std::string& dumpStr) +{ + Utils::UniqueWriteGuard infoGuard(this->fgProcLock_); + for (auto iter = foregrandProcList_.begin(); iter != foregrandProcList_.end(); ++iter) { + dumpStr.append("uid:" + std::to_string(iter->uid) + ", pid:" + std::to_string(iter->pid)); + dumpStr.append(", procName:" + iter->bundleName + "\n"); + } +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/app_state_observer.h b/services/security_component_service/sa/sa_main/app_state_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..56998a00217a643c25a230aec946f233f1a0b78f --- /dev/null +++ b/services/security_component_service/sa/sa_main/app_state_observer.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H +#define SECURITY_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H + +#include +#include +#include "app_mgr_interface.h" +#include "application_state_observer_stub.h" +#include "iremote_object.h" +#include "rwlock.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompProcessData { + std::string bundleName; + int32_t pid = -1; + int32_t uid = -1; +}; + +class AppStateObserver : public AppExecFwk::ApplicationStateObserverStub { +public: + explicit AppStateObserver(); + virtual ~AppStateObserver(); + + void OnProcessStateChanged(const AppExecFwk::ProcessData& processData) override; + void OnProcessDied(const AppExecFwk::ProcessData& processData) override; + bool IsProcessForeground(int32_t pid, int32_t uid); + void AddProcessToForegroundSet(int32_t pid, const SecCompProcessData& data); + void AddProcessToForegroundSet(const AppExecFwk::ProcessData& processData); + void AddProcessToForegroundSet(const AppExecFwk::AppStateData& stateData); + void DumpProcess(std::string& dumpStr); + +private: + void RemoveProcessFromForegroundSet(const AppExecFwk::ProcessData& processData); + std::vector foregrandProcList_; + OHOS::Utils::RWLock fgProcLock_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + +#endif // SECURITY_COMPONENT_SA_APP_STATE_OBSERVER_APP_STATE_OBSERVER_H + diff --git a/services/security_component_service/sa/sa_main/delay_exit_task.cpp b/services/security_component_service/sa/sa_main/delay_exit_task.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d78873085860cc1f3c6c1f0d7f348fa65cea462 --- /dev/null +++ b/services/security_component_service/sa/sa_main/delay_exit_task.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 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. + */ +#include "delay_exit_task.h" + +#include "sec_comp_log.h" +#include "sec_comp_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "DelayExitTask"}; +static const std::string DELAY_EXIT_TASK = "DelayExitTask"; +static const int32_t DELAY_EXIT_MILLISECONDS = 30 * 1000; // 30s +} + +DelayExitTask::DelayExitTask() +{ +} + +DelayExitTask& DelayExitTask::GetInstance() +{ + static DelayExitTask instance; + return instance; +} + +void DelayExitTask::Init(const std::shared_ptr& secHandler) +{ + secHandler_ = secHandler; +} + +void DelayExitTask::Start() +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + + std::function delayed = ([]() { + SecCompManager::GetInstance().ExitSaProcess(); + }); + + SC_LOG_INFO(LABEL, "Delay exit service after %{public}d ms", DELAY_EXIT_MILLISECONDS); + secHandler_->ProxyPostTask(delayed, DELAY_EXIT_TASK, DELAY_EXIT_MILLISECONDS); +} + +void DelayExitTask::Stop() +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + + SC_LOG_INFO(LABEL, "service delay exit handler stop"); + secHandler_->ProxyRemoveTask(DELAY_EXIT_TASK); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/delay_exit_task.h b/services/security_component_service/sa/sa_main/delay_exit_task.h new file mode 100644 index 0000000000000000000000000000000000000000..d4315df7ca61d32ebefc758239ae514b11e54d90 --- /dev/null +++ b/services/security_component_service/sa/sa_main/delay_exit_task.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_DELAY_EXIT_TASK_H +#define SECURITY_COMPONENT_DELAY_EXIT_TASK_H + +#include +#include +#include "nocopyable.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class DelayExitTask { +public: + static DelayExitTask& GetInstance(); + virtual ~DelayExitTask() = default; + + void Init(const std::shared_ptr& secHandler); + void Start(); + void Stop(); +private: + DelayExitTask(); + std::shared_ptr secHandler_; + + DISALLOW_COPY_AND_MOVE(DelayExitTask); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_DELAY_EXIT_TASK_H + diff --git a/services/security_component_service/sa/sa_main/first_use_dialog.cpp b/services/security_component_service/sa/sa_main/first_use_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6439824a8321fd106e6f216677d4c3c0dbd35529 --- /dev/null +++ b/services/security_component_service/sa/sa_main/first_use_dialog.cpp @@ -0,0 +1,297 @@ +/* + * Copyright (c) 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. + */ +#include "first_use_dialog.h" + +#include +#include +#include +#include +#include +#include "ability_manager_client.h" +#include "accesstoken_kit.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "want_params_wrapper.h" +#include "want.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "FirstUseDialog"}; +static const std::string SEC_COMP_SRV_CFG_PATH = "/data/service/el1/public/security_component_service"; +static const std::string FIRST_USE_RECORD_JSON = SEC_COMP_SRV_CFG_PATH + "/first_use_record.json"; +static const std::string FIRST_USE_RECORD_TAG = "FirstUseRecord"; +static const std::string TOKEN_ID_TAG = "TokenId"; +static const std::string COMP_TYPE_TAG = "CompType"; + +const std::string GRANT_ABILITY_BUNDLE_NAME = "com.ohos.permissionmanager"; +const std::string GRANT_ABILITY_ABILITY_NAME = "com.ohos.permissionmanager.SecurityExtAbility"; +const std::string TYPE_KEY = "ohos.user.security.type"; +const std::string TOKEN_KEY = "ohos.ability.params.token"; + +constexpr uint32_t MAX_CFG_FILE_SIZE = 100 * 1024; // 100k +} + +bool FirstUseDialog::IsCfgDirExist(void) +{ + struct stat fstat = {}; + if (stat(SEC_COMP_SRV_CFG_PATH.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", SEC_COMP_SRV_CFG_PATH.c_str(), errno); + return false; + } + + if (!S_ISDIR(fstat.st_mode)) { + SC_LOG_ERROR(LABEL, "path %{public}s is not directory.", SEC_COMP_SRV_CFG_PATH.c_str()); + return false; + } + return true; +} + +bool FirstUseDialog::IsCfgFileExist(void) +{ + struct stat fstat = {}; + if (stat(FIRST_USE_RECORD_JSON.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + return true; +} + +bool FirstUseDialog::IsCfgFileValid(void) +{ + struct stat fstat = {}; + if (stat(FIRST_USE_RECORD_JSON.c_str(), &fstat) != 0) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + if (fstat.st_size > MAX_CFG_FILE_SIZE) { + SC_LOG_INFO(LABEL, "path %{public}s errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + return true; +} + +bool FirstUseDialog::ReadCfgContent(std::string& content) +{ + std::stringstream buffer; + std::ifstream i(FIRST_USE_RECORD_JSON); + if (!i.is_open()) { + SC_LOG_ERROR(LABEL, "cannot open file %{public}s, errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return false; + } + buffer << i.rdbuf(); + content = buffer.str(); + i.close(); + return true; +} + +void FirstUseDialog::WriteCfgContent(const std::string& content) +{ + std::ofstream out(FIRST_USE_RECORD_JSON); + if (!out.is_open()) { + SC_LOG_ERROR(LABEL, "cannot open file %{public}s, errno %{public}d.", FIRST_USE_RECORD_JSON.c_str(), errno); + return; + } + out << content; + out.close(); +} + +bool FirstUseDialog::ParseRecord(nlohmann::json& jsonRes, + AccessToken::AccessTokenID& id, uint64_t& type) +{ + if (jsonRes.find(TOKEN_ID_TAG) == jsonRes.end() || + !jsonRes.at(TOKEN_ID_TAG).is_number()) { + SC_LOG_ERROR(LABEL, "parse TokenId failed."); + return false; + } + id = jsonRes.at(TOKEN_ID_TAG).get(); + if (id == AccessToken::INVALID_TOKENID) { + SC_LOG_ERROR(LABEL, "TokenId is not invalid."); + return false; + } + + if (jsonRes.find(COMP_TYPE_TAG) == jsonRes.end() || + !jsonRes.at(COMP_TYPE_TAG).is_number()) { + SC_LOG_ERROR(LABEL, "parse CompType failed."); + return false; + } + type = jsonRes.at(COMP_TYPE_TAG).get(); + return true; +} + +void FirstUseDialog::ParseRecords(nlohmann::json& jsonRes) +{ + std::unique_lock lock(useMapMutex_); + if (jsonRes.find(FIRST_USE_RECORD_TAG) == jsonRes.end() || + !jsonRes.at(FIRST_USE_RECORD_TAG).is_array()) { + SC_LOG_ERROR(LABEL, "parse tag failed."); + return; + } + + nlohmann::json recordListJson = jsonRes.at(FIRST_USE_RECORD_TAG); + for (auto& recordJson : recordListJson) { + AccessToken::AccessTokenID id; + uint64_t type; + if (!ParseRecord(recordJson, id, type)) { + SC_LOG_ERROR(LABEL, "parse record failed."); + return; + } + firstUseMap_[id] = type; + } +} + +void FirstUseDialog::LoadFirstUseRecord(void) +{ + if (!IsCfgFileValid()) { + SC_LOG_INFO(LABEL, "first use record is invalid."); + return; + } + + std::string content; + if (!ReadCfgContent(content)) { + return; + } + + nlohmann::json jsonRes = nlohmann::json::parse(content, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "cfg info format is invalid"); + return; + } + + ParseRecords(jsonRes); +} + +void FirstUseDialog::SaveFirstUseRecord(void) +{ + SC_LOG_INFO(LABEL, "start save first_use_record json"); + if (!IsCfgDirExist()) { + SC_LOG_ERROR(LABEL, "dir %{public}s is not exist, errno %{public}d", + SEC_COMP_SRV_CFG_PATH.c_str(), errno); + return; + } + + if (!IsCfgFileExist()) { + if (creat(FIRST_USE_RECORD_JSON.c_str(), S_IRUSR | S_IWUSR) == -1) { + SC_LOG_ERROR(LABEL, "create %{public}s failed, errno %{public}d", + FIRST_USE_RECORD_JSON.c_str(), errno); + return; + } + } + + nlohmann::json jsonRes; + { + std::unique_lock lock(useMapMutex_); + nlohmann::json recordsJson; + for (auto iter = firstUseMap_.begin(); iter != firstUseMap_.end(); ++iter) { + AccessToken::AccessTokenID id = iter->first; + AccessToken::HapTokenInfo info; + if (AccessToken::AccessTokenKit::GetHapTokenInfo(id, info) != AccessToken::RET_SUCCESS) { + SC_LOG_INFO(LABEL, "token id %{public}d is not exist, do not update it.", id); + continue; + } + nlohmann::json recordJson; + recordJson[TOKEN_ID_TAG] = id; + recordJson[COMP_TYPE_TAG] = iter->second; + recordsJson.emplace_back(recordJson); + } + + jsonRes[FIRST_USE_RECORD_TAG] = recordsJson; + } + WriteCfgContent(jsonRes.dump()); +} + +void FirstUseDialog::StartDialogAbility(SecCompType type, sptr callerToken) +{ + int32_t typeNum; + if (type == LOCATION_COMPONENT) { + typeNum = 0; + } else if (type == SAVE_COMPONENT) { + typeNum = 1; + } else { + SC_LOG_ERROR(LABEL, "unknown type."); + return; + } + + AAFwk::Want want; + want.SetElementName(GRANT_ABILITY_BUNDLE_NAME, GRANT_ABILITY_ABILITY_NAME); + want.SetParam(TYPE_KEY, typeNum); + want.SetParam(TOKEN_KEY, callerToken); + int startRes = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, callerToken); + SC_LOG_INFO(LABEL, "start ability res %{public}d", startRes); +} + +void FirstUseDialog::SendSaveEventHandler(void) +{ + std::function delayed = ([this]() { + this->SaveFirstUseRecord(); + }); + + SC_LOG_INFO(LABEL, "Delay first_use_record json"); + secHandler_->ProxyPostTask(delayed); +} + +void FirstUseDialog::NotifyFirstUseDialog(AccessToken::AccessTokenID tokenId, SecCompType type, + sptr callerToken) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "event handler invalid."); + return; + } + if (callerToken == nullptr) { + SC_LOG_INFO(LABEL, "callerToken is null, no need to notify dialog"); + return; + } + + uint64_t typeMask; + if (type == LOCATION_COMPONENT) { + typeMask = LOCATION_BUTTON_FIRST_USE; + } else if (type == SAVE_COMPONENT) { + typeMask = SAVE_BUTTON_FIRST_USE; + } else { + SC_LOG_INFO(LABEL, "this type need not notify dialog to user"); + return; + } + + std::unique_lock lock(useMapMutex_); + auto iter = firstUseMap_.find(tokenId); + if (iter == firstUseMap_.end()) { + SC_LOG_INFO(LABEL, "has not use record, start dialog"); + StartDialogAbility(type, callerToken); + firstUseMap_[tokenId] = typeMask; + SendSaveEventHandler(); + return; + } + + uint64_t compTypes = firstUseMap_[tokenId]; + if ((compTypes & typeMask) == typeMask) { + SC_LOG_INFO(LABEL, "no need notify again."); + return; + } + StartDialogAbility(type, callerToken); + firstUseMap_[tokenId] |= typeMask; + SendSaveEventHandler(); +} + +void FirstUseDialog::Init(std::shared_ptr secHandler) +{ + SC_LOG_DEBUG(LABEL, "Init!!"); + secHandler_ = secHandler; + LoadFirstUseRecord(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS + diff --git a/services/security_component_service/sa/sa_main/first_use_dialog.h b/services/security_component_service/sa/sa_main/first_use_dialog.h new file mode 100644 index 0000000000000000000000000000000000000000..fd04777b01dec61998d058e840c6f04b5305fe52 --- /dev/null +++ b/services/security_component_service/sa/sa_main/first_use_dialog.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 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. + */ +#ifndef FIRST_USE_DIALOG_H +#define FIRST_USE_DIALOG_H + +#include +#include +#include +#include +#include "access_token.h" +#include "iremote_object.h" +#include "nlohmann/json.hpp" +#include "sec_comp_err.h" +#include "sec_comp_info.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +constexpr uint64_t LOCATION_BUTTON_FIRST_USE = 1 << 0; +constexpr uint64_t SAVE_BUTTON_FIRST_USE = 1 << 1; + +class FirstUseDialog final { +public: + FirstUseDialog() = default; + ~FirstUseDialog() = default; + void NotifyFirstUseDialog(AccessToken::AccessTokenID tokenId, SecCompType type, sptr callerToken); + void Init(std::shared_ptr secHandler); + +private: + bool IsCfgDirExist(void); + bool IsCfgFileExist(void); + bool IsCfgFileValid(void); + bool ReadCfgContent(std::string& content); + void WriteCfgContent(const std::string& content); + bool ParseRecord(nlohmann::json& jsonRes, + AccessToken::AccessTokenID& id, uint64_t& type); + void ParseRecords(nlohmann::json& jsonRes); + void LoadFirstUseRecord(void); + void SaveFirstUseRecord(void); + void StartDialogAbility(SecCompType type, sptr callerToken); + void SendSaveEventHandler(void); + + std::mutex useMapMutex_; + std::unordered_map firstUseMap_; + std::shared_ptr secHandler_; +}; +} // namespace SecurityComponentEnhance +} // namespace Security +} // namespace OHOS +#endif // FIRST_USE_DIALOG_H + diff --git a/services/security_component_service/sa/sa_main/sec_comp_entity.cpp b/services/security_component_service/sa/sa_main/sec_comp_entity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32c18dd1a97466c89fe0088a0f9e4320a61b414e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_entity.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_entity.h" + +#include +#include "hisysevent.h" +#include "ipc_skeleton.h" +#include "sec_comp_err.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_info_helper.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEntity"}; +static constexpr uint64_t MAX_TOUCH_INTERVAL = 1000000L; // 1000ms +static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; +} + +int32_t SecCompEntity::RevokeTempPermission() +{ + if (!isGrant_) { + SC_LOG_ERROR(LABEL, "security component is not granted"); + return SC_OK; + } + isGrant_ = false; + return SecCompInfoHelper::RevokeTempPermission(tokenId_, componentInfo_); +} + +int32_t SecCompEntity::GrantTempPermission() +{ + isGrant_ = true; + return SecCompInfoHelper::GrantTempPermission(tokenId_, componentInfo_); +} + +bool SecCompEntity::CompareComponentBasicInfo(SecCompBase* other, bool isRectCheck) const +{ + return componentInfo_->CompareComponentBasicInfo(other, isRectCheck); +} + +bool SecCompEntity::CheckTouchInfo(const SecCompClickEvent& touchInfo) const +{ + auto current = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + if (touchInfo.timestamp < current - MAX_TOUCH_INTERVAL || touchInfo.timestamp > current) { + SC_LOG_ERROR(LABEL, "touch timestamp invalid touchInfo. timestamp: %{public}llu, current: %{public}llu", + static_cast(touchInfo.timestamp), static_cast(current)); + return false; + } + + if (!componentInfo_->rect_.IsInRect(touchInfo.touchX, touchInfo.touchY)) { + SC_LOG_ERROR(LABEL, "touch point is not in component rect"); + return false; + } + + int32_t res = SecCompEnhanceAdapter::CheckExtraInfo(touchInfo); + if ((res != SC_OK) && (res != SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE)) { + SC_LOG_ERROR(LABEL, "HMAC checkout failed" + "touchX:%{public}f, touchY:%{public}f, timestamp:%{public}llu, dataSize:%{public}d", + touchInfo.touchX, touchInfo.touchY, static_cast(touchInfo.timestamp), + touchInfo.extraInfo.dataSize); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CLICK_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId_, "SC_TYPE", componentInfo_->type_); + return false; + } + return true; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_entity.h b/services/security_component_service/sa/sa_main/sec_comp_entity.h new file mode 100644 index 0000000000000000000000000000000000000000..d95f6f6d64a20ed4d6a1bf7bb540d8865df4a022 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_entity.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENTITY_H +#define SECURITY_COMPONENT_ENTITY_H + +#include +#include "accesstoken_kit.h" +#include "sec_comp_base.h" +#include "sec_comp_info.h" +#include "sec_comp_perm_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEntity { +public: + SecCompEntity(std::shared_ptr component, + AccessToken::AccessTokenID token, int32_t scId) : componentInfo_(component), + tokenId_(token), scId_(scId){}; + ~SecCompEntity() = default; + int32_t RevokeTempPermission(); + int32_t GrantTempPermission(); + int32_t GetScId() const + { + return scId_; + }; + + SecCompType GetType() const + { + if (componentInfo_ == nullptr) { + return UNKNOWN_SC_TYPE; + } + return componentInfo_->type_; + }; + + bool IsGrant() const + { + return isGrant_; + } + + std::shared_ptr GetComponentInfo() const + { + return componentInfo_; + }; + + void SetComponentInfo(const std::shared_ptr& com) + { + componentInfo_ = com; + }; + + std::shared_ptr GetComponentInfo() + { + return componentInfo_; + }; + + bool CompareComponentBasicInfo(SecCompBase* other, bool isRectCheck) const; + bool CheckTouchInfo(const SecCompClickEvent& touchInfo) const; + +private: + std::shared_ptr componentInfo_; + bool isGrant_ = false; + AccessToken::AccessTokenID tokenId_; + int32_t scId_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENTITY_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp b/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7058200bbaae92dfbea3c4e77d045f86a357372e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_info_helper.h" + +#include "display.h" +#include "display_info.h" +#include "display_manager.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_service.h" +#include "sec_comp_tool.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompInfoHelper"}; +static constexpr double MAX_RECT_PERCENT = 0.1F; // 10% +static constexpr double ZERO_OFFSET = 0.0F; +static std::mutex g_renderLock; +} + +SecCompBase* SecCompInfoHelper::ParseComponent(SecCompType type, const nlohmann::json& jsonComponent) +{ + SecCompBase* comp = nullptr; + switch (type) { + case LOCATION_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + case PASTE_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + case SAVE_COMPONENT: + comp = ConstructComponent(jsonComponent); + break; + default: + SC_LOG_ERROR(LABEL, "Parse component type unknown"); + break; + } + if (comp == nullptr) { + SC_LOG_ERROR(LABEL, "Parse component failed"); + return comp; + } + + comp->SetValid(CheckComponentValid(comp)); + return comp; +} + +static bool GetScreenSize(double& width, double& height) +{ + sptr display = + OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplaySync(); + if (display == nullptr) { + SC_LOG_ERROR(LABEL, "Get display manager failed"); + return false; + } + + auto info = display->GetDisplayInfo(); + if (info == nullptr) { + SC_LOG_ERROR(LABEL, "Get display info failed"); + return false; + } + + width = static_cast(info->GetWidth()); + height = static_cast(info->GetHeight()); + SC_LOG_DEBUG(LABEL, "display manager Screen width %{public}f height %{public}f", + width, height); + return true; +} + +bool SecCompInfoHelper::CheckRectValid(const SecCompRect& rect, const SecCompRect& windowRect) +{ + double curScreenWidth = 0.0F; + double curScreenHeight = 0.0F; + if (!GetScreenSize(curScreenWidth, curScreenHeight)) { + SC_LOG_ERROR(LABEL, "Get screen size is invalid"); + return false; + } + + if (GreatOrEqual(0.0, rect.width_) || GreatOrEqual(0.0, rect.height_)) { + SC_LOG_ERROR(LABEL, "width or height is <= 0"); + return false; + } + + if (GreatNotEqual(ZERO_OFFSET, rect.x_) || GreatNotEqual(ZERO_OFFSET, rect.y_) || + GreatNotEqual(rect.x_, curScreenWidth) || GreatNotEqual(rect.y_, curScreenHeight)) { + SC_LOG_ERROR(LABEL, "start point is out of screen"); + return false; + } + + if (GreatOrEqual((rect.x_ + rect.width_), curScreenWidth) || + GreatOrEqual((rect.y_ + rect.height_), curScreenHeight)) { + SC_LOG_ERROR(LABEL, "rect is out of screen"); + return false; + } + + if (GreatNotEqual(windowRect.x_, rect.x_) || GreatNotEqual(windowRect.y_, rect.y_) || + GreatNotEqual(rect.width_, windowRect.width_) || GreatNotEqual(rect.height_, windowRect.height_)) { + SC_LOG_ERROR(LABEL, "rect is out of window"); + return false; + } + + // check rect > 10% + if (GreatOrEqual((rect.width_ * rect.height_), (curScreenWidth * curScreenHeight * MAX_RECT_PERCENT))) { + SC_LOG_ERROR(LABEL, "rect area is too large"); + return false; + } + SC_LOG_DEBUG(LABEL, "check component rect success."); + return true; +} + +static bool CheckSecCompBaseButton(const SecCompBase* comp) +{ + if ((comp->text_ < 0) && (comp->icon_ < 0)) { + SC_LOG_INFO(LABEL, "both text and icon do not exist."); + return false; + } + if ((comp->text_ >= 0) && comp->fontSize_ < MIN_FONT_SIZE) { + SC_LOG_INFO(LABEL, "font size invalid."); + return false; + } + if ((comp->icon_ >= 0) && comp->iconSize_ < MIN_ICON_SIZE) { + SC_LOG_INFO(LABEL, "icon size invalid."); + return false; + } + + if ((comp->bg_ != SecCompBackground::NO_BG_TYPE) && + (((comp->text_ != NO_TEXT) && (IsColorSimilar(comp->fontColor_, comp->bgColor_))) || + ((comp->icon_ != NO_ICON) && (IsColorSimilar(comp->iconColor_, comp->bgColor_))))) { + SC_LOG_INFO(LABEL, "fontColor or iconColor is similar whith backgroundColor."); + return false; + } + + if (comp->bg_ == SecCompBackground::NO_BG_TYPE && + ((comp->padding_.top != MIN_PADDING_WITHOUT_BG) || (comp->padding_.right != MIN_PADDING_WITHOUT_BG) || + (comp->padding_.bottom != MIN_PADDING_WITHOUT_BG) || (comp->padding_.left != MIN_PADDING_WITHOUT_BG))) { + SC_LOG_INFO(LABEL, "padding can not change without background."); + return false; + } + + return true; +} + +static bool CheckSecCompBase(const SecCompBase* comp) +{ + if (comp->parentEffect_) { + SC_LOG_ERROR(LABEL, "parentEffect is active, security component invalid."); + return false; + } + + if ((comp->padding_.top < MIN_PADDING_SIZE) || (comp->padding_.right < MIN_PADDING_SIZE) || + (comp->padding_.bottom < MIN_PADDING_SIZE) || (comp->padding_.left < MIN_PADDING_SIZE) || + (comp->textIconSpace_ < MIN_PADDING_SIZE)) { + SC_LOG_ERROR(LABEL, "size is invalid."); + return false; + } + + if (((comp->bg_ != SecCompBackground::NO_BG_TYPE) && (IsColorTransparent(comp->bgColor_))) || + ((comp->text_ != NO_TEXT) && (IsColorTransparent(comp->fontColor_))) || + ((comp->icon_ != NO_ICON) && (IsColorTransparent(comp->iconColor_)))) { + SC_LOG_ERROR(LABEL, "bgColor or fontColor or iconColor is too transparent."); + return false; + } + if (!CheckSecCompBaseButton(comp)) { + return false; + } + return true; +} + +bool SecCompInfoHelper::CheckComponentValid(const SecCompBase* comp) +{ + if ((comp == nullptr) || !IsComponentTypeValid(comp->type_)) { + SC_LOG_INFO(LABEL, "comp is null or type is invalid."); + return false; + } + + if (!CheckSecCompBase(comp)) { + SC_LOG_INFO(LABEL, "SecComp base is invalid."); + return false; + } + + return true; +} + +int32_t SecCompInfoHelper::GrantTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo) +{ + if ((tokenId <= 0) || (componentInfo == nullptr)) { + SC_LOG_ERROR(LABEL, "revoke component is null"); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + + SecCompType type = componentInfo->type_; + switch (type) { + case LOCATION_COMPONENT: + { + int32_t res = SecCompPermManager::GetInstance().GrantLocationPermission(tokenId, + "ohos.permission.APPROXIMATELY_LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if (res != SC_OK) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + res = SecCompPermManager::GetInstance().GrantLocationPermission(tokenId, "ohos.permission.LOCATION", + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if (res != SC_OK) { + SecCompPermManager::GetInstance().RevokeLocationPermission( + tokenId, "ohos.permission.APPROXIMATELY_LOCATION", + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + return SC_OK; + } + case PASTE_COMPONENT: + SC_LOG_DEBUG(LABEL, "grant paste permission"); + return SC_OK; + case SAVE_COMPONENT: + SC_LOG_DEBUG(LABEL, "grant save permission"); + return SecCompPermManager::GetInstance().GrantTempSavePermission(tokenId); + default: + SC_LOG_ERROR(LABEL, "Parse component type unknown"); + break; + } + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; +} + +int32_t SecCompInfoHelper::RevokeTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo) +{ + if (componentInfo == nullptr) { + SC_LOG_ERROR(LABEL, "revoke component is null"); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + + SecCompType type = componentInfo->type_; + switch (type) { + case LOCATION_COMPONENT: + { + int32_t locationRes = SecCompPermManager::GetInstance().RevokeLocationPermission(tokenId, + "ohos.permission.LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + int32_t approxLocationRes = SecCompPermManager::GetInstance().RevokeLocationPermission(tokenId, + "ohos.permission.APPROXIMATELY_LOCATION", AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + if ((locationRes != SC_OK) || (approxLocationRes != SC_OK)) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + return SC_OK; + } + case PASTE_COMPONENT: + SC_LOG_DEBUG(LABEL, "revoke paste permission"); + return SC_OK; + default: + SC_LOG_ERROR(LABEL, "revoke component type unknown"); + break; + } + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_info_helper.h b/services/security_component_service/sa/sa_main/sec_comp_info_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..463c9fc14c8a0c1dc25f9aea012bed6f0305abd0 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_info_helper.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 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. + */ +#ifndef I_SECURITY_COMPONENT_INFO_HELPER_H +#define I_SECURITY_COMPONENT_INFO_HELPER_H + +#include "accesstoken_kit.h" +#include "nlohmann/json.hpp" +#include "sec_comp_base.h" +#include "sec_comp_info.h" +#include "sec_comp_perm_manager.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +template +T* ConstructComponent(const nlohmann::json& jsonComponent) +{ + T *componentPtr = new (std::nothrow)T(); + if ((componentPtr != nullptr) && !componentPtr->FromJson(jsonComponent)) { + delete componentPtr; + return nullptr; + } + return componentPtr; +} + +class SecCompInfoHelper { +public: + static SecCompBase* ParseComponent(SecCompType type, const nlohmann::json& jsonComponent); + static int32_t RevokeTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo); + static int32_t GrantTempPermission(AccessToken::AccessTokenID tokenId, + const std::shared_ptr& componentInfo); + static bool CheckComponentValid(const SecCompBase* comp); + static bool CheckRectValid(const SecCompRect& rect, const SecCompRect& windowRect); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // I_SECURITY_COMPONENT_INFO_HELPER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_manager.cpp b/services/security_component_service/sa/sa_main/sec_comp_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..899e2b43c621a1d0e3963a31addf5ba5ff97fd66 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_manager.cpp @@ -0,0 +1,519 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_manager.h" + +#include "delay_exit_task.h" +#include "hisysevent.h" +#include "i_sec_comp_service.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_info_helper.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompManager"}; +static constexpr int32_t SC_ID_START = 1000; +static constexpr int32_t MAX_INT_NUM = 0x7fffffff; +static constexpr int32_t ROOT_UID = 0; +} + +SecCompManager::SecCompManager() +{ + scIdStart_ = SC_ID_START; +} + +SecCompManager& SecCompManager::GetInstance() +{ + static SecCompManager instance; + return instance; +} + +int32_t SecCompManager::CreateScId() +{ + std::lock_guard lock(scIdMtx_); + if (scIdStart_ == MAX_INT_NUM) { + scIdStart_ = SC_ID_START; + } else { + scIdStart_++; + } + return scIdStart_; +} + +int32_t SecCompManager::AddSecurityComponentToList(int32_t pid, const SecCompEntity& newEntity) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + if (isSaExit_) { + SC_LOG_ERROR(LABEL, "SA is exiting, retry..."); + return SC_SERVICE_ERROR_SERVICE_NOT_EXIST; + } + + auto iter = componentMap_.find(pid); + if (iter != componentMap_.end()) { + iter->second.isForeground = true; + iter->second.compList.emplace_back(newEntity); + SecCompEnhanceAdapter::EnableInputEnhance(); + return SC_OK; + } + + ProcessCompInfos newProcess; + newProcess.isForeground = true; + newProcess.compList.emplace_back(newEntity); + componentMap_[pid] = newProcess; + SecCompEnhanceAdapter::EnableInputEnhance(); + return SC_OK; +} + +int32_t SecCompManager::DeleteSecurityComponentFromList(int32_t pid, int32_t scId) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + SC_LOG_ERROR(LABEL, "Can not find registered process"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + if (it->GetScId() == scId) { + it->RevokeTempPermission(); + list.erase(it); + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + return SC_OK; + } + } + SC_LOG_ERROR(LABEL, "Can not find component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; +} + +bool SecCompManager::IsInMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + if (IPCSkeleton::GetCallingUid() == ROOT_UID) { + return false; + } + return (maliciousAppList_.find(pid) != maliciousAppList_.end()); +} + +void SecCompManager::AddAppToMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + maliciousAppList_.insert(pid); +} + +void SecCompManager::RemoveAppFromMaliciousAppList(int32_t pid) +{ + std::lock_guard lock(maliciousMtx_); + maliciousAppList_.erase(pid); +} + +bool SecCompManager::IsMaliciousAppListEmpty() +{ + std::lock_guard lock(maliciousMtx_); + return (maliciousAppList_.size() == 0); +} + +static std::string TransformCallBackResult(enum SCErrCode error) +{ + std::string errMsg = ""; + switch (error) { + case SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE: + errMsg = "enhance do not exist"; + break; + case SC_ENHANCE_ERROR_VALUE_INVALID: + errMsg = "value is invalid"; + break; + case SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST: + errMsg = "callback do not exist"; + break; + case SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL: + errMsg = "callback operate fail"; + break; + case SC_SERVICE_ERROR_COMPONENT_INFO_INVALID: + errMsg = "component info invalid"; + break; + case SC_ENHANCE_ERROR_CALLBACK_CHECK_FAIL: + errMsg = "callback check fail"; + break; + default: + errMsg = "unknown error"; + break; + } + return errMsg; +} + +SecCompEntity* SecCompManager::GetSecurityComponentFromList(int32_t pid, int32_t scId) +{ + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return nullptr; + } + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + if (it->GetScId() == scId) { + return std::addressof(*it); + } + } + return nullptr; +} + +bool SecCompManager::IsForegroundCompExist() +{ + return std::any_of(componentMap_.begin(), componentMap_.end(), [](const auto & iter) { + return (iter.second.isForeground) && (iter.second.compList.size() > 0); + }); +} + +void SecCompManager::NotifyProcessForeground(int32_t pid) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + iter->second.isForeground = true; + if (IsForegroundCompExist()) { + SecCompEnhanceAdapter::EnableInputEnhance(); + } + + SC_LOG_INFO(LABEL, "App pid %{public}d to foreground", pid); +} + +void SecCompManager::NotifyProcessBackground(int32_t pid) +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + + iter->second.isForeground = false; + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + SC_LOG_INFO(LABEL, "App pid %{public}d to background", pid); +} + +void SecCompManager::NotifyProcessDied(int32_t pid) +{ + // notify enhance process died. + SecCompEnhanceAdapter::NotifyProcessDied(pid); + + RemoveAppFromMaliciousAppList(pid); + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + auto iter = componentMap_.find(pid); + if (iter == componentMap_.end()) { + return; + } + SC_LOG_INFO(LABEL, "App pid %{public}d died", pid); + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + it->RevokeTempPermission(); + } + list.clear(); + componentMap_.erase(pid); + + if (!IsForegroundCompExist()) { + SecCompEnhanceAdapter::DisableInputEnhance(); + } + + DelayExitTask::GetInstance().Start(); +} + +void SecCompManager::ExitSaProcess() +{ + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + if (!componentMap_.empty() || !IsMaliciousAppListEmpty()) { + SC_LOG_INFO(LABEL, "Apps using security component still exist, no exit sa"); + return; + } + isSaExit_ = true; + SecCompEnhanceAdapter::DisableInputEnhance(); + SecCompEnhanceAdapter::ExistEnhanceService(); + + SC_LOG_INFO(LABEL, "All processes using security component died, start sa exit"); + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get SystemAbilityManager."); + return; + } + int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (ret != SC_OK) { + SC_LOG_ERROR(LABEL, "Failed to UnloadSystemAbility service! errcode=%{public}d", ret); + return; + } + SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!"); +} + +void SecCompManager::ExitWhenAppMgrDied() +{ + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) { + std::vector& list = iter->second.compList; + for (auto it = list.begin(); it != list.end(); ++it) { + it->RevokeTempPermission(); + } + list.clear(); + } + componentMap_.clear(); + + // no need exit enhance service, only disable input enhance. + SecCompEnhanceAdapter::DisableInputEnhance(); + isSaExit_ = true; + + SC_LOG_INFO(LABEL, "app mgr died, start sa exit"); + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + SC_LOG_ERROR(LABEL, "failed to get SystemAbilityManager."); + return; + } + int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE); + if (ret != SC_OK) { + SC_LOG_ERROR(LABEL, "failed to UnloadSystemAbility service! errcode=%{public}d", ret); + return; + } + SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!"); +} + +void SecCompManager::SendCheckInfoEnhanceSysEvent(int32_t scId, + SecCompType type, const std::string& scene, int32_t res) +{ + if (res == SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CHALLENGE_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", type, "CALL_SCENE", + scene); + } else { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLBACK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_TYPE", type, + "CALL_SCENE", scene, "REASON", TransformCallBackResult(static_cast(res))); + } +} + +int32_t SecCompManager::RegisterSecurityComponent(SecCompType type, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller, int32_t& scId) +{ + DelayExitTask::GetInstance().Stop(); + SC_LOG_DEBUG(LABEL, "PID: %{public}d, register security component", caller.pid); + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + SecCompBase* componentPtr = SecCompInfoHelper::ParseComponent(type, jsonComponent); + std::shared_ptr component(componentPtr); + if (component == nullptr) { + SC_LOG_ERROR(LABEL, "Parse component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "REGITSTER", "SC_TYPE", type); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, component, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(INVALID_SC_ID, type, "REGISTER", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + int32_t registerId = CreateScId(); + SecCompEntity entity(component, caller.tokenId, registerId); + int32_t ret = AddSecurityComponentToList(caller.pid, entity); + if (ret == SC_OK) { + scId = registerId; + } else { + SC_LOG_ERROR(LABEL, "Register security component failed"); + scId = INVALID_SC_ID; + } + return ret; +} + +int32_t SecCompManager::UpdateSecurityComponent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, update security component", caller.pid); + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + OHOS::Utils::UniqueWriteGuard lk(this->componentInfoLock_); + SecCompEntity* sc = GetSecurityComponentFromList(caller.pid, scId); + if (sc == nullptr) { + SC_LOG_ERROR(LABEL, "Can not find target component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent); + std::shared_ptr reportComponentInfo(report); + if (reportComponentInfo == nullptr) { + SC_LOG_ERROR(LABEL, "Update component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "UPDATE", + "SC_TYPE", sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, reportComponentInfo, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "UPDATE", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + sc->SetComponentInfo(reportComponentInfo); + return SC_OK; +} + +int32_t SecCompManager::UnregisterSecurityComponent(int32_t scId, const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, unregister security component", caller.pid); + if (scId < 0) { + SC_LOG_ERROR(LABEL, "ScId is invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + return DeleteSecurityComponentFromList(caller.pid, scId); +} + +int32_t SecCompManager::CheckClickSecurityComponentInfo(SecCompEntity* sc, int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller) +{ + SC_LOG_DEBUG(LABEL, "PID: %{public}d, Check security component", caller.pid); + SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent); + std::shared_ptr reportComponentInfo(report); + if ((reportComponentInfo == nullptr) || (!reportComponentInfo->GetValid())) { + SC_LOG_ERROR(LABEL, "report component info invalid"); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE", + sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + if ((!SecCompInfoHelper::CheckRectValid(reportComponentInfo->rect_, reportComponentInfo->windowRect_))) { + SC_LOG_ERROR(LABEL, "compare component info failed."); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE", + sc->GetType()); + return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID; + } + int32_t enhanceRes = + SecCompEnhanceAdapter::CheckComponentInfoEnhnace(caller.pid, reportComponentInfo, jsonComponent); + if (enhanceRes != SC_OK) { + SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "CLICK", enhanceRes); + SC_LOG_ERROR(LABEL, "enhance check failed"); + AddAppToMaliciousAppList(caller.pid); + return enhanceRes; + } + + sc->SetComponentInfo(reportComponentInfo); + return SC_OK; +} + +int32_t SecCompManager::ReportSecurityComponentClickEvent(int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller, + const SecCompClickEvent& touchInfo, sptr callerToken) +{ + if (IsInMaliciousAppList(caller.pid)) { + SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it"); + return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST; + } + + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + SecCompEntity* sc = GetSecurityComponentFromList(caller.pid, scId); + if (sc == nullptr) { + SC_LOG_ERROR(LABEL, "Can not find target component"); + return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST; + } + + int32_t res = CheckClickSecurityComponentInfo(sc, scId, jsonComponent, caller); + if (res != SC_OK) { + return res; + } + + if (!sc->CheckTouchInfo(touchInfo)) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CLICK_INFO_CHECK_FAILED", + HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + AddAppToMaliciousAppList(caller.pid); + return SC_SERVICE_ERROR_CLICK_EVENT_INVALID; + } + res = sc->GrantTempPermission(); + if (res != SC_OK) { + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "TEMP_GRANT_FAILED", + HiviewDFX::HiSysEvent::EventType::FAULT, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + return res; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "TEMP_GRANT_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(), + "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType()); + firstUseDialog_.NotifyFirstUseDialog(caller.tokenId, sc->GetType(), callerToken); + return res; +} + +bool SecCompManager::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + if (SecCompPermManager::GetInstance().RevokeTempSavePermission(tokenId) == SC_OK) { + return true; + } + return false; +} + +void SecCompManager::DumpSecComp(std::string& dumpStr) +{ + OHOS::Utils::UniqueReadGuard lk(this->componentInfoLock_); + for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) { + dumpStr.append("pid:" + std::to_string(iter->first) + "\n"); + for (auto compIter = iter->second.compList.begin(); compIter != iter->second.compList.end(); compIter ++) { + nlohmann::json json; + compIter->GetComponentInfo()->ToJson(json); + dumpStr.append(" scId:" + std::to_string(compIter->GetScId()) + + ", isGrant:" + std::to_string(compIter->IsGrant()) + ", " + json.dump() + "\n"); + } + } +} + +bool SecCompManager::Initialize() +{ + SC_LOG_DEBUG(LABEL, "Initialize!!"); + SecCompEnhanceAdapter::StartEnhanceService(); + + secRunner_ = AppExecFwk::EventRunner::Create(true); + if (!secRunner_) { + SC_LOG_ERROR(LABEL, "failed to create a recvRunner."); + return false; + } + + secHandler_ = std::make_shared(secRunner_); + DelayExitTask::GetInstance().Init(secHandler_); + firstUseDialog_.Init(secHandler_); + + return SecCompPermManager::GetInstance().InitEventHandler(secHandler_); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_manager.h b/services/security_component_service/sa/sa_main/sec_comp_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..3c0848c8b21a8ab54a46654ccf0b53983d2aa4f7 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_manager.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_MANAGER_H +#define SECURITY_COMPONENT_MANAGER_H + +#include +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "app_state_observer.h" +#include "first_use_dialog.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "sec_comp_base.h" +#include "sec_comp_entity.h" +#include "sec_comp_info.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompCallerInfo { + AccessToken::AccessTokenID tokenId; + int32_t uid; + int32_t pid; +}; + +struct ProcessCompInfos { + std::vector compList; + bool isForeground = false; +}; + +class SecCompManager { +public: + static SecCompManager& GetInstance(); + virtual ~SecCompManager() = default; + + int32_t RegisterSecurityComponent(SecCompType type, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller, int32_t& scId); + int32_t UpdateSecurityComponent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller); + int32_t UnregisterSecurityComponent(int32_t scId, const SecCompCallerInfo& caller); + int32_t ReportSecurityComponentClickEvent(int32_t scId, const nlohmann::json& jsonComponent, + const SecCompCallerInfo& caller, const SecCompClickEvent& touchInfo, sptr callerToken); + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); + void NotifyProcessForeground(int32_t pid); + void NotifyProcessBackground(int32_t pid); + void NotifyProcessDied(int32_t pid); + void DumpSecComp(std::string& dumpStr); + bool Initialize(); + void ExitSaProcess(); + void ExitWhenAppMgrDied(); + +private: + SecCompManager(); + bool IsForegroundCompExist(); + int32_t AddSecurityComponentToList(int32_t pid, const SecCompEntity& newEntity); + int32_t DeleteSecurityComponentFromList(int32_t pid, int32_t scId); + SecCompEntity* GetSecurityComponentFromList(int32_t pid, int32_t scId); + int32_t CheckClickSecurityComponentInfo(SecCompEntity* sc, int32_t scId, + const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller); + bool IsInMaliciousAppList(int32_t pid); + void AddAppToMaliciousAppList(int32_t pid); + void RemoveAppFromMaliciousAppList(int32_t pid); + bool IsMaliciousAppListEmpty(); + void SendCheckInfoEnhanceSysEvent(int32_t scId, + SecCompType type, const std::string& scene, int32_t res); + int32_t CreateScId(); + + OHOS::Utils::RWLock componentInfoLock_; + std::mutex scIdMtx_; + std::unordered_map componentMap_; + int32_t scIdStart_; + bool isSaExit_ = false; + + std::shared_ptr secRunner_; + std::shared_ptr secHandler_; + std::set maliciousAppList_; // pid set + std::mutex maliciousMtx_; + FirstUseDialog firstUseDialog_; + + DISALLOW_COPY_AND_MOVE(SecCompManager); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_MANAGER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23f9d1a215a737f964e9995f2eebb6fff32d9771 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_perm_manager.h" + +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_service.h" +#include "sec_comp_tool.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompPermManager"}; +static const int32_t WAIT_MILLISECONDS = 5 * 1000; +} + +SecCompPermManager& SecCompPermManager::GetInstance() +{ + static SecCompPermManager instance; + return instance; +} + +bool SecCompPermManager::DelayRevokePermission(AccessToken::AccessTokenID tokenId, const std::string& taskName) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return false; + } + + std::function delayed = ([tokenId]() { + SC_LOG_DEBUG(LABEL, "delay revoke save permission"); + SecCompPermManager::GetInstance().RevokeTempSavePermission(tokenId); + }); + + SC_LOG_DEBUG(LABEL, "revoke save permission after %{public}d ms", WAIT_MILLISECONDS); + secHandler_->ProxyPostTask(delayed, taskName, WAIT_MILLISECONDS); + return true; +} + +bool SecCompPermManager::RevokeSavePermissionTask(const std::string& taskName) +{ + if (secHandler_ == nullptr) { + SC_LOG_ERROR(LABEL, "fail to get EventHandler"); + return false; + } + + SC_LOG_DEBUG(LABEL, "revoke save permission task name:%{public}s", taskName.c_str()); + secHandler_->ProxyRemoveTask(taskName); + return true; +} + +int32_t SecCompPermManager::GrantLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag) +{ + int32_t res = AccessToken::AccessTokenKit::GrantPermission(tokenId, permissionName, + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + SC_LOG_INFO(LABEL, "grant permission: %{public}s, tokenId:%{public}d", permissionName.c_str(), tokenId); + return res; +} + +int32_t SecCompPermManager::RevokeLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag) +{ + int32_t res = AccessToken::AccessTokenKit::RevokePermission(tokenId, permissionName, + AccessToken::PermissionFlag::PERMISSION_COMPONENT_SET); + SC_LOG_INFO(LABEL, "revoke permission: %{public}s, tokenId:%{public}d", permissionName.c_str(), tokenId); + return res; +} + +int32_t SecCompPermManager::GrantTempSavePermission(AccessToken::AccessTokenID tokenId) +{ + auto current = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()); + std::string taskName = std::to_string(tokenId) + std::to_string(current); + if (!DelayRevokePermission(tokenId, taskName)) { + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + std::lock_guard lock(mutex_); + taskQue_.push_back(taskName); + applySaveCountMap_[tokenId]++; + SC_LOG_DEBUG(LABEL, "tokenId: %{public}d current permission apply counts is: %{public}d.", + tokenId, applySaveCountMap_[tokenId]); + return SC_OK; +} + +int32_t SecCompPermManager::RevokeTempSavePermission(AccessToken::AccessTokenID tokenId) +{ + std::lock_guard lock(mutex_); + auto iter = applySaveCountMap_.find(tokenId); + if (iter == applySaveCountMap_.end() || applySaveCountMap_[tokenId] == 0) { + SC_LOG_ERROR(LABEL, "This hap has no permissions to save files."); + return SC_SERVICE_ERROR_PERMISSION_OPER_FAIL; + } + std::string taskName = taskQue_.front(); + if (!RevokeSavePermissionTask(taskName)) { + return false; + } + taskQue_.pop_front(); + SC_LOG_DEBUG(LABEL, "tokenId: %{public}d current permission apply counts is: %{public}d.", + tokenId, applySaveCountMap_[tokenId]); + if ((--applySaveCountMap_[tokenId]) == 0) { + applySaveCountMap_.erase(tokenId); + } + return SC_OK; +} + +bool SecCompPermManager::InitEventHandler(const std::shared_ptr& secHandler) +{ + secHandler_ = secHandler; + return true; +} + +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..0cd7f76808ca4a3777a2638a5287da914ba723c4 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_perm_manager.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_PERMISSION_MANAGER_H +#define SECURITY_COMPONENT_PERMISSION_MANAGER_H + +#include +#include +#include "accesstoken_kit.h" +#include "rwlock.h" +#include "sec_comp_base.h" +#include "sec_event_handler.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompPermManager { +public: + SecCompPermManager() = default; + virtual ~SecCompPermManager() = default; + static SecCompPermManager& GetInstance(); + + int32_t GrantLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag); + int32_t RevokeLocationPermission(AccessToken::AccessTokenID tokenId, + const std::string& permissionName, int flag); + + int32_t GrantTempSavePermission(AccessToken::AccessTokenID tokenId); + int32_t RevokeTempSavePermission(AccessToken::AccessTokenID tokenId); + + bool InitEventHandler(const std::shared_ptr& secHandler); + std::shared_ptr GetSecEventHandler() const; + +private: + bool DelayRevokePermission(AccessToken::AccessTokenID tokenId, const std::string& taskName); + bool RevokeSavePermissionTask(const std::string& taskName); + + std::unordered_map applySaveCountMap_; + std::deque taskQue_; + std::mutex mutex_; + std::shared_ptr secHandler_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_PERMISSION_MANAGER_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_service.cpp b/services/security_component_service/sa/sa_main/sec_comp_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40aad2dae403765f53eb9eb108b83f929d133f5a --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_service.cpp @@ -0,0 +1,284 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_service.h" + +#include + +#include "app_mgr_death_recipient.h" +#include "hisysevent.h" +#include "hitrace_meter.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_manager.h" +#include "sec_comp_log.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompService"}; +static const int32_t ROOT_UID = 0; +} + +REGISTER_SYSTEM_ABILITY_BY_ID(SecCompService, SA_ID_SECURITY_COMPONENT_SERVICE, true); + +SecCompService::SecCompService(int32_t saId, bool runOnCreate) + : SystemAbility(saId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START) +{ +} + +SecCompService::~SecCompService() +{ +} + +void SecCompService::OnStart() +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentOnStart"); + if (state_ == ServiceRunningState::STATE_RUNNING) { + SC_LOG_INFO(LABEL, "SecCompService has already started!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + SC_LOG_INFO(LABEL, "SecCompService is starting"); + if (!RegisterAppStateObserver()) { + SC_LOG_ERROR(LABEL, "Failed to register app state observer!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + if (!Initialize()) { + SC_LOG_ERROR(LABEL, "Failed to initialize"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + + state_ = ServiceRunningState::STATE_RUNNING; + bool ret = Publish(this); + if (!ret) { + SC_LOG_ERROR(LABEL, "Failed to publish service!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return; + } + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "SERVICE_INIT_SUCCESS", + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", getpid()); + SC_LOG_INFO(LABEL, "Congratulations, SecCompService start successfully!"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); +} + +void SecCompService::OnStop() +{ + SC_LOG_INFO(LABEL, "Stop service"); + state_ = ServiceRunningState::STATE_NOT_START; + UnregisterAppStateObserver(); + iAppMgr_ = nullptr; + appStateObserver_ = nullptr; +} + +bool SecCompService::RegisterAppStateObserver() +{ + if (appStateObserver_ != nullptr) { + SC_LOG_INFO(LABEL, "AppStateObserver instance already create"); + return true; + } + appStateObserver_ = new (std::nothrow) AppStateObserver(); + if (appStateObserver_ == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to create AppStateObserver instance"); + return false; + } + sptr samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrClient == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get system ability manager"); + appStateObserver_ = nullptr; + return false; + } + auto remoteObject = samgrClient->GetSystemAbility(APP_MGR_SERVICE_ID); + iAppMgr_ = iface_cast(remoteObject); + if (iAppMgr_ == nullptr) { + SC_LOG_ERROR(LABEL, "Failed to get ability manager service"); + appStateObserver_ = nullptr; + return false; + } + + if (iAppMgr_->RegisterApplicationStateObserver(appStateObserver_) != ERR_OK) { + SC_LOG_ERROR(LABEL, "Failed to Register app state observer"); + iAppMgr_ = nullptr; + appStateObserver_ = nullptr; + return false; + } + + sptr appMgrDeathRecipient = new (std::nothrow) AppMgrDeathRecipient(); + if (appMgrDeathRecipient == nullptr) { + SC_LOG_ERROR(LABEL, "Alloc appMgr death observer fail"); + return false; + } + + if (!remoteObject->AddDeathRecipient(appMgrDeathRecipient)) { + SC_LOG_ERROR(LABEL, "Add service death observer fail"); + return false; + } + + std::vector list; + if (iAppMgr_->GetForegroundApplications(list) == ERR_OK) { + for (auto it = list.begin(); it != list.end(); ++it) { + appStateObserver_->AddProcessToForegroundSet(*it); + } + } + SC_LOG_ERROR(LABEL, "Register app state observer success"); + return true; +} + +void SecCompService::UnregisterAppStateObserver() +{ + if (iAppMgr_ != nullptr && appStateObserver_ != nullptr) { + iAppMgr_->UnregisterApplicationStateObserver(appStateObserver_); + } +} + +bool SecCompService::GetCallerInfo(SecCompCallerInfo& caller) +{ + AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); + int32_t pid = IPCSkeleton::GetCallingPid(); + int32_t uid = IPCSkeleton::GetCallingUid(); + if ((uid != ROOT_UID) && (AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) != AccessToken::TOKEN_HAP)) { + SC_LOG_ERROR(LABEL, "Get caller tokenId invalid"); + return false; + } + if ((uid != ROOT_UID) && (!appStateObserver_->IsProcessForeground(pid, uid))) { + SC_LOG_ERROR(LABEL, "caller pid is not in foreground"); + return false; + } + caller.tokenId = tokenId; + caller.pid = pid; + caller.uid = uid; + return true; +} + +int32_t SecCompService::RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentRegister"); + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + int32_t res = SecCompManager::GetInstance().RegisterSecurityComponent(type, jsonRes, caller, scId); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return res; +} + +int32_t SecCompService::UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) +{ + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + return SecCompManager::GetInstance().UpdateSecurityComponent(scId, jsonRes, caller); +} + +int32_t SecCompService::UnregisterSecurityComponent(int32_t scId) +{ + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + return SecCompManager::GetInstance().UnregisterSecurityComponent(scId, caller); +} + +int32_t SecCompService::ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) +{ + StartTrace(HITRACE_TAG_ACCESS_CONTROL, "SecurityComponentClick"); + SecCompCallerInfo caller; + if (!GetCallerInfo(caller)) { + SC_LOG_ERROR(LABEL, "Check caller failed"); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + nlohmann::json jsonRes = nlohmann::json::parse(componentInfo, nullptr, false); + if (jsonRes.is_discarded()) { + SC_LOG_ERROR(LABEL, "component info invalid %{public}s", componentInfo.c_str()); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + int32_t res = + SecCompManager::GetInstance().ReportSecurityComponentClickEvent(scId, jsonRes, caller, touchInfo, callerToken); + FinishTrace(HITRACE_TAG_ACCESS_CONTROL); + return res; +} + +bool SecCompService::ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) +{ + return SecCompManager::GetInstance().ReduceAfterVerifySavePermission(tokenId); +} + +sptr SecCompService::GetEnhanceRemoteObject() +{ + return SecCompEnhanceAdapter::GetEnhanceRemoteObject(); +} + +int SecCompService::Dump(int fd, const std::vector& args) +{ + if (fd < 0) { + return ERR_INVALID_VALUE; + } + + dprintf(fd, "SecCompService Dump:\n"); + std::string arg0 = ((args.size() == 0)? "" : Str16ToStr8(args.at(0))); + if (arg0.compare("-h") == 0) { + dprintf(fd, "Usage:\n"); + dprintf(fd, " -h: command help\n"); + dprintf(fd, " -a: dump all sec component\n"); + dprintf(fd, " -p: dump foreground processes\n"); + } else if (arg0.compare("-p") == 0) { + std::string dumpStr; + appStateObserver_->DumpProcess(dumpStr); + dprintf(fd, "%s\n", dumpStr.c_str()); + } else if (arg0.compare("-a") == 0 || arg0 == "") { + std::string dumpStr; + SecCompManager::GetInstance().DumpSecComp(dumpStr); + dprintf(fd, "%s\n", dumpStr.c_str()); + } + return ERR_OK; +} + +bool SecCompService::Initialize() const +{ + return SecCompManager::GetInstance().Initialize(); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_service.h b/services/security_component_service/sa/sa_main/sec_comp_service.h new file mode 100644 index 0000000000000000000000000000000000000000..99d21f2ba6d0369929f964dc88d7bbf84933266e --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_service.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_SERVICE_H +#define SECURITY_COMPONENT_SERVICE_H + +#include +#include +#include "app_state_observer.h" +#include "iremote_object.h" +#include "nocopyable.h" +#include "sec_comp_manager.h" +#include "sec_comp_stub.h" +#include "singleton.h" +#include "system_ability.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +class SecCompService final : public SystemAbility, public SecCompStub { + DECLARE_DELAYED_SINGLETON(SecCompService); + DECLEAR_SYSTEM_ABILITY(SecCompService); + +public: + SecCompService(int32_t saId, bool runOnCreate); + + void OnStart() override; + void OnStop() override; + + int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId) override; + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override; + int32_t UnregisterSecurityComponent(int32_t scId) override; + int32_t ReportSecurityComponentClickEvent(int32_t scId, + const std::string& componentInfo, const SecCompClickEvent& touchInfo, sptr callerToken) override; + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override; + sptr GetEnhanceRemoteObject() override; + + int Dump(int fd, const std::vector& args) override; + +private: + bool Initialize() const; + bool RegisterAppStateObserver(); + void UnregisterAppStateObserver(); + bool GetCallerInfo(SecCompCallerInfo& caller); + + ServiceRunningState state_; + sptr iAppMgr_; + sptr appStateObserver_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_SERVICE_H diff --git a/services/security_component_service/sa/sa_main/sec_comp_stub.cpp b/services/security_component_service/sa/sa_main/sec_comp_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c492afd7e0ed0413e42133b2d19a2c098979c552 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_stub.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_stub.h" + +#include "ipc_skeleton.h" +#include "sec_comp_click_event_parcel.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompStub"}; +} // namespace + +int32_t SecCompStub::OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) +{ + std::u16string descripter = SecCompStub::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (descripter != remoteDescripter) { + SC_LOG_ERROR(LABEL, "Deal remote request fail, descriptor is not matched"); + return SC_SERVICE_ERROR_IPC_REQUEST_FAIL; + } + + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t SecCompStub::RegisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t type; + if (!data.ReadUint32(type)) { + SC_LOG_ERROR(LABEL, "Read component type fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (type <= UNKNOWN_SC_TYPE || type >= MAX_SC_TYPE) { + SC_LOG_ERROR(LABEL, "Security component type invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + int32_t scId = INVALID_SC_ID; + int32_t res = this->RegisterSecurityComponent(static_cast(type), componentInfo, scId); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (!reply.WriteInt32(scId)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + return SC_OK; +} + +int32_t SecCompStub::UpdateSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + int32_t res = this->UpdateSecurityComponent(scId, componentInfo); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Update security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + return res; +} + +int32_t SecCompStub::UnregisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + int32_t res = this->UnregisterSecurityComponent(scId); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Unregister security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::ReportSecurityComponentClickEventInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t scId; + if (!data.ReadInt32(scId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (scId < 0) { + SC_LOG_ERROR(LABEL, "Security component id invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + std::string componentInfo; + if (!data.ReadString(componentInfo)) { + SC_LOG_ERROR(LABEL, "Read component info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + sptr touchInfoParcel = data.ReadParcelable(); + if (touchInfoParcel == nullptr) { + SC_LOG_ERROR(LABEL, "Read touchInfo info fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + sptr callerToken = data.ReadRemoteObject(); + int32_t res = + this->ReportSecurityComponentClickEvent(scId, componentInfo, touchInfoParcel->touchInfoParams_, callerToken); + if (!reply.WriteInt32(res)) { + SC_LOG_ERROR(LABEL, "Register security component result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::ReduceAfterVerifySavePermissionInner(MessageParcel& data, MessageParcel& reply) +{ + uint32_t tokenId; + if (!data.ReadUint32(tokenId)) { + SC_LOG_ERROR(LABEL, "Read component id fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + + if (tokenId == 0) { + SC_LOG_ERROR(LABEL, "AccessTokenId invalid"); + return SC_SERVICE_ERROR_VALUE_INVALID; + } + + bool res = this->ReduceAfterVerifySavePermission(tokenId); + if (!reply.WriteBool(res)) { + SC_LOG_ERROR(LABEL, "verify temp save permission result fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +int32_t SecCompStub::GetEnhanceRemoteObjectInner(MessageParcel& data, MessageParcel& reply) +{ + auto res = this->GetEnhanceRemoteObject(); + if (!reply.WriteRemoteObject(res)) { + SC_LOG_ERROR(LABEL, "Register security component enhance remote object fail"); + return SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL; + } + return SC_OK; +} + +SecCompStub::SecCompStub() +{ + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT)] = + &SecCompStub::RegisterSecurityComponentInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT)] = + &SecCompStub::UpdateSecurityComponentInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT)] = + &SecCompStub::UnregisterSecurityComponentInner; + requestFuncMap_[static_cast( + SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT)] = + &SecCompStub::ReportSecurityComponentClickEventInner; + requestFuncMap_[static_cast(SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION)] = + &SecCompStub::ReduceAfterVerifySavePermissionInner; + requestFuncMap_[static_cast( + SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT)] = + &SecCompStub::GetEnhanceRemoteObjectInner; +} + +SecCompStub::~SecCompStub() +{ + SC_LOG_ERROR(LABEL, "~SecCompStub"); + requestFuncMap_.clear(); + SC_LOG_ERROR(LABEL, "~SecCompStub end"); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/sa_main/sec_comp_stub.h b/services/security_component_service/sa/sa_main/sec_comp_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..c435876f0855c8ecb10e01ccdff86a2d0a29be8c --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_comp_stub.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_STUB_H +#define SECURITY_COMPONENT_STUB_H + +#include +#include "i_sec_comp_service.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompStub : public IRemoteStub { +public: + SecCompStub(); + virtual ~SecCompStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + +private: + int32_t RegisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t UpdateSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t UnregisterSecurityComponentInner(MessageParcel& data, MessageParcel& reply); + int32_t ReportSecurityComponentClickEventInner(MessageParcel& data, MessageParcel& reply); + int32_t ReduceAfterVerifySavePermissionInner(MessageParcel& data, MessageParcel& reply); + int32_t GetEnhanceRemoteObjectInner(MessageParcel& data, MessageParcel& reply); + + using RequestFuncType = int32_t (SecCompStub::*)(MessageParcel& data, MessageParcel& reply); + std::map requestFuncMap_; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_STUB_H diff --git a/services/security_component_service/sa/sa_main/sec_event_handler.cpp b/services/security_component_service/sa/sa_main/sec_event_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..32e3d8bc6ba1df57ba02ef3101fc9a52cdbbb169 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_event_handler.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 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. + */ +#include "sec_event_handler.h" + +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +SecEventHandler::SecEventHandler( + const std::shared_ptr& runner) + : AppExecFwk::EventHandler(runner) {} + +SecEventHandler::~SecEventHandler() = default; + +bool SecEventHandler::ProxyPostTask( + const Callback &callback, const std::string &name, int64_t delayTime) +{ + return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); +} + +void SecEventHandler::ProxyRemoveTask(const std::string &name) +{ + AppExecFwk::EventHandler::RemoveTask(name); +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/security_component_service/sa/sa_main/sec_event_handler.h b/services/security_component_service/sa/sa_main/sec_event_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..86b07342a3a82cd06d8c026df6f0904ee0054a01 --- /dev/null +++ b/services/security_component_service/sa/sa_main/sec_event_handler.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 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. + */ +#ifndef SEC_EVENT_HANDLER_H +#define SEC_EVENT_HANDLER_H + +#include +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecEventHandler : public AppExecFwk::EventHandler { +public: + explicit SecEventHandler(const std::shared_ptr& runner); + ~SecEventHandler() override; + + bool ProxyPostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + + void ProxyRemoveTask(const std::string &name); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_EVENT_HANDLER_H diff --git a/services/security_component_service/sa/sa_profile/3506.json b/services/security_component_service/sa/sa_profile/3506.json new file mode 100644 index 0000000000000000000000000000000000000000..83650d44babc580266f8422199d2c9e64be7be46 --- /dev/null +++ b/services/security_component_service/sa/sa_profile/3506.json @@ -0,0 +1,12 @@ +{ + "process": "security_component_service", + "systemability": [ + { + "name": 3506, + "libpath": "libsecurity_component_service.z.so", + "run-on-create": false, + "distributed": false, + "dump_level": 1 + } + ] +} \ No newline at end of file diff --git a/services/security_component_service/sa/sa_profile/BUILD.gn b/services/security_component_service/sa/sa_profile/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dc0c6d9bdd6554c72a3d5af28e337a35bfb45677 --- /dev/null +++ b/services/security_component_service/sa/sa_profile/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 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("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("security_component_sa_profile_standard") { + sources = [ "3506.json" ] + part_name = "security_component" +} diff --git a/services/security_component_service/sa/security_component_service.cfg b/services/security_component_service/sa/security_component_service.cfg new file mode 100644 index 0000000000000000000000000000000000000000..009ac034141ee3973516318ec955cec7c5d6b0b7 --- /dev/null +++ b/services/security_component_service/sa/security_component_service.cfg @@ -0,0 +1,24 @@ +{ + "jobs" : [{ + "name" : "post-fs-data", + "cmds" : [ + "mkdir /data/service/el1/public/security_component_service 0750 security_component security_component" + ] + } + ], + "services" : [{ + "name" : "security_component_service", + "path" : ["/system/bin/sa_main", "/system/profile/security_component_service.json"], + "ondemand" : true, + "start-mode" : "condition", + "uid" : "security_component", + "gid" : ["security_component"], + "apl" : "system_basic", + "permission" : [ + "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", + "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS" + ], + "secon" : "u:r:security_component_service:s0" + } + ] +} diff --git a/services/security_component_service/sa/security_component_service.rc b/services/security_component_service/sa/security_component_service.rc new file mode 100644 index 0000000000000000000000000000000000000000..68b6fbc01a098231e8f7bd4c342d90dd98e964a0 --- /dev/null +++ b/services/security_component_service/sa/security_component_service.rc @@ -0,0 +1,19 @@ +# Copyright (c) 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. + +service security_component_service /system/bin/sa_main /system/profile/security_component.json + class security_component_service + priority -20 + user security_component + group security_component + seclabel u:r:security_component_service:s0 diff --git a/services/security_component_service/sa/test/BUILD.gn b/services/security_component_service/sa/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..04537f303379dd49ce1eca29627896c53a27bb52 --- /dev/null +++ b/services/security_component_service/sa/test/BUILD.gn @@ -0,0 +1,145 @@ +# Copyright (c) 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("//build/test.gni") + +sec_comp_root_dir = "../../../.." + +ohos_unittest("sec_comp_service_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/include", + "//third_party/json/include", + ] + + sources = [ + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_state_observer.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/delay_exit_task.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/first_use_dialog.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_entity.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_service.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_stub.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_event_handler.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp", + "unittest/src/app_state_observer_test.cpp", + "unittest/src/sec_comp_entity_test.cpp", + "unittest/src/sec_comp_info_helper_test.cpp", + "unittest/src/sec_comp_manager_test.cpp", + "unittest/src/sec_comp_service_test.cpp", + "unittest/src/sec_comp_stub_test.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_enhance_adapter", + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "//third_party/googletest:gmock_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "access_token:libtoken_setproc", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "window_manager:libdm", + ] +} + +ohos_unittest("sec_comp_service_mock_test") { + subsystem_name = "security" + part_name = "security_component" + module_out_path = part_name + "/" + part_name + + include_dirs = [ + "${sec_comp_root_dir}/frameworks/common/include", + "${sec_comp_root_dir}/frameworks/security_component/include", + "${sec_comp_root_dir}/frameworks/enhance_adapter/include", + "${sec_comp_root_dir}/interfaces/inner_api/security_component/include", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/include", + "//third_party/json/include", + ] + + sources = [ + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_mgr_death_recipient.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/app_state_observer.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/delay_exit_task.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/first_use_dialog.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_entity.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_perm_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_info_helper.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_manager.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_service.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_comp_stub.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/sa_main/sec_event_handler.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp", + "${sec_comp_root_dir}/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp", + "unittest/src/sec_comp_service_mock_test.cpp", + ] + + configs = [ "${sec_comp_root_dir}/config:coverage_flags" ] + cflags_cc = [ "-DHILOG_ENABLE" ] + + deps = [ + "${sec_comp_root_dir}/frameworks:libsecurity_component_framework", + "//third_party/googletest:gmock_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:runtime", + "access_token:libtoken_setproc", + "c_utils:utils", + "eventhandler:libeventhandler", + "graphic_2d:librender_service_client", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "window_manager:libdm", + ] +} + +group("unittest") { + testonly = true + deps = [ + ":sec_comp_service_test", + ":sec_comp_service_mock_test", + ] +} diff --git a/services/security_component_service/sa/test/mock/include/access_token.h b/services/security_component_service/sa/test/mock/include/access_token.h new file mode 100644 index 0000000000000000000000000000000000000000..654bb5bcf506d359484a7cbcd762b048bff72878 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/access_token.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H +#define SECURITY_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +typedef unsigned int AccessTokenID; +static const AccessTokenID INVALID_TOKENID = 0; + +enum AccessTokenKitRet { + RET_FAILED = -1, + RET_SUCCESS = 0, +}; + +typedef enum TypeATokenTypeEnum { + TOKEN_INVALID = -1, + TOKEN_HAP = 0, + TOKEN_NATIVE, + TOKEN_SHELL, + TOKEN_TYPE_BUTT, +} ATokenTypeEnum; + +typedef enum TypePermissionFlag { + PERMISSION_DEFAULT_FLAG = 0, + PERMISSION_USER_SET = 1 << 0, + PERMISSION_USER_FIXED = 1 << 1, + PERMISSION_SYSTEM_FIXED = 1 << 2, + PERMISSION_GRANTED_BY_POLICY = 1 << 3, + PERMISSION_COMPONENT_SET = 1 << 4, + PERMISSION_POLICY_FIXED = 1 << 5, +} PermissionFlag; + +typedef struct { + unsigned int tokenUniqueID : 20; + unsigned int res : 6; + unsigned int dlpFlag : 1; + unsigned int type : 2; + unsigned int version : 3; +} AccessTokenIDInner; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ACCESS_TOKEN_DEF_H diff --git a/services/security_component_service/sa/test/mock/include/accesstoken_kit.h b/services/security_component_service/sa/test/mock/include/accesstoken_kit.h new file mode 100644 index 0000000000000000000000000000000000000000..f4a2af765841197735074308ecc879e47eb29f5e --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/accesstoken_kit.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +#define SECURITY_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H + +#include +#include "access_token.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfo { +}; + +class AccessTokenKit { +public: + static int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag) + { + return 0; + }; + + static int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag) + { + return 0; + }; + + static int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes) + { + return 0; + }; + + static ATokenTypeEnum GetTokenTypeFlag(AccessTokenID tokenID) + { + AccessTokenIDInner *idInner = reinterpret_cast(&tokenID); + return static_cast(idInner->type); + }; +}; +} // namespace SECURITY_COMPONENT_INTERFACES_INNER_KITS_ACCESSTOKEN_KIT_H +} // namespace Security +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/app_mgr_interface.h b/services/security_component_service/sa/test/mock/include/app_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..b0a36ec60602865e1e850bc854dbaf2d3a2b85fd --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/app_mgr_interface.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H +#define SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "application_state_observer_stub.h" + +namespace OHOS { +namespace AppExecFwk { + +class IAppMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.mock.AppMgr"); + + virtual int32_t RegisterApplicationStateObserver(const sptr &observer, + const std::vector &bundleNameList = {}) = 0; + + virtual int32_t UnregisterApplicationStateObserver(const sptr &observer) = 0; + + virtual int32_t GetForegroundApplications(std::vector &list) = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APP_MGR_INTERFACE_H diff --git a/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h b/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..9271160512de5d5ad6d8bd52177b88b095a2623d --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/application_state_observer_stub.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H +#define SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H + +#include +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +enum class AppProcessState { + APP_STATE_BEGIN = 0, + APP_STATE_CREATE = APP_STATE_BEGIN, + APP_STATE_READY, + APP_STATE_FOREGROUND, + APP_STATE_FOCUS, + APP_STATE_BACKGROUND, + APP_STATE_TERMINATED, + APP_STATE_END, +}; + +struct ProcessData { + std::string bundleName; + int32_t pid = 0; + int32_t uid = 0; + AppProcessState state; + bool isContinuousTask = false; + bool isKeepAlive = false; + bool isFocused = false; + int32_t requestProcCode = 0; +}; + +struct AppStateData { + std::string bundleName; + int32_t pid = -1; + int32_t uid = 0; + int32_t state = 0; + int32_t accessTokenId = 0; + bool isFocused = false; +}; + +class IApplicationStateObserver : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IApplicationStateObserver"); + virtual void OnProcessStateChanged(const ProcessData &processData) {} + virtual void OnProcessDied(const ProcessData &processData) = 0; +}; + +class ApplicationStateObserverStub : public IRemoteStub { +public: + ApplicationStateObserverStub() = default; + virtual ~ApplicationStateObserverStub() = default; + DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // SECURITY_COMPONENT_MOCK_ABILITY_RUNTIME_APPLICATION_STATE_OBSERVER_STUB_H diff --git a/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h b/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..eee66c0b67d0e67a3eadd84f958ab404be7770cc --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/if_system_ability_manager.h @@ -0,0 +1,51 @@ +/* +* Copyright (c) 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. +*/ +#ifndef SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H +#define SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "mock_app_mgr_proxy.h" + +namespace OHOS { +class MockIRemoteObject : public virtual RefBase { +public: + bool AddDeathRecipient(const sptr& recipient) + { + (void)recipient; + return addResult; + } + bool addResult = true; +}; + +template inline sptr iface_cast(const sptr &object) +{ + if (object == nullptr) { + return nullptr; + } + const std::u16string descriptor = INTERFACE::GetDescriptor(); + if (descriptor == u"ohos.appexecfwk.mock.AppMgr") { + return static_cast(MockAppMgrProxy::g_MockAppMgrProxy); + } + return nullptr; +} + +class ISystemAbilityManager : public IRemoteBroker { +public: + virtual sptr GetSystemAbility(int32_t systemAbilityId) = 0; + virtual int32_t UnloadSystemAbility(int32_t systemAbilityId) = 0; +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_SYSTEM_ABILITY_IF_MANAGER_CLINET_INCLUDE_H diff --git a/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h b/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h new file mode 100644 index 0000000000000000000000000000000000000000..f1ca97c0f156ca84c72a8cc45be81fe370772f06 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/ipc_mock_skeleton.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 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. +*/ +#ifndef SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H +#define SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H +#include + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + static uint32_t GetCallingTokenID() + { + return tokenID; + }; + + static pid_t GetCallingPid() + { + return pid; + }; + + static uint32_t tokenID; + static pid_t pid; +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_IPC_SKELETON_INCLUDE_H diff --git a/services/security_component_service/sa/test/mock/include/iservice_registry.h b/services/security_component_service/sa/test/mock/include/iservice_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..8a4aa3d665598fbd0ba1cd1dc2d96be819fffdd7 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/iservice_registry.h @@ -0,0 +1,33 @@ +/* +* Copyright (c) 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. +*/ +#ifndef SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H +#define SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H +#include +#include "if_system_ability_manager.h" + +namespace OHOS { +class SystemAbilityManagerClient { +public: + static SystemAbilityManagerClient& GetInstance(); + SystemAbilityManagerClient() = default; + ~SystemAbilityManagerClient() = default; + + static SystemAbilityManagerClient* clientInstance; + static SystemAbilityManagerClient defaultInstance; + static std::mutex instanceMtx; + MOCK_METHOD0(GetSystemAbilityManager, sptr()); +}; +} // namespace OHOS +#endif // SEC_COMP_MOCK_SYSTEM_ABILITY_MANAGER_CLINET_INCLUDE_H \ No newline at end of file diff --git a/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h b/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..eab8644c5eb1cb32b7ea63e29969d3cd295eec1f --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/mock_app_mgr_proxy.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONET_MOCK_APP_MGR_PROXY_H +#define SECURITY_COMPONET_MOCK_APP_MGR_PROXY_H +#include +#include +#include "app_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +class MockAppMgrProxy : public IRemoteProxy { +public: + explicit MockAppMgrProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~MockAppMgrProxy() = default; + + static MockAppMgrProxy* g_MockAppMgrProxy; + + MOCK_METHOD2(RegisterApplicationStateObserver, + int32_t(const sptr&, const std::vector&)); + MOCK_METHOD1(UnregisterApplicationStateObserver, int32_t(const sptr &)); + MOCK_METHOD1(GetForegroundApplications, int32_t(std::vector&)); +}; +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h b/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..ee833e69215ad68403c3722089f1ec0c1cacee2f --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/mock_system_ability_proxy.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_MOCK_SYSTEM_ABILITY_MANAGER_PROXY +#define SECURITY_COMPONENT_MOCK_SYSTEM_ABILITY_MANAGER_PROXY +#include +#include +#include "if_system_ability_manager.h" + +namespace OHOS { +class SystemAbilityManagerProxy : public IRemoteProxy { +public: + explicit SystemAbilityManagerProxy(const sptr& impl) + : IRemoteProxy(impl) {} + ~SystemAbilityManagerProxy() = default; + + MOCK_METHOD1(GetSystemAbility, sptr(int32_t)); + MOCK_METHOD1(UnloadSystemAbility, int32_t(int32_t)); +}; +} // namespace OHOS +#endif diff --git a/services/security_component_service/sa/test/mock/include/sec_comp_enhance_adapter.h b/services/security_component_service/sa/test/mock/include/sec_comp_enhance_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..36bbaaa5505326ec3ccfee16d805f99c58c90a87 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/sec_comp_enhance_adapter.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 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. + */ +#ifndef SECURITY_COMPONENT_ENHANCE_ADAPTER_H +#define SECURITY_COMPONENT_ENHANCE_ADAPTER_H +#include +#include "parcel.h" +#include "sec_comp_info.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +struct SecCompEnhanceAdapter { + static int32_t SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen); + static int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen); + static int32_t CheckExtraInfo(const SecCompClickEvent& touchInfo); + + static int32_t EnableInputEnhance(); + static int32_t DisableInputEnhance(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SECURITY_COMPONENT_ENHANCE_ADAPTER_H diff --git a/services/security_component_service/sa/test/mock/include/system_ability.h b/services/security_component_service/sa/test/mock/include/system_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..9127f3a1d434f0085660bced523e1c471d88ed08 --- /dev/null +++ b/services/security_component_service/sa/test/mock/include/system_ability.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 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. + */ +#ifndef MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H +#define MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H + +#include +#include "if_system_ability_manager.h" +#include "iremote_object.h" + +namespace OHOS { +#define DECLEAR_SYSTEM_ABILITY(className) +#define SA_ID_SECURITY_COMPONENT_SERVICE 1000 +#define REGISTER_SYSTEM_ABILITY_BY_ID(a, b, c) + +class SystemAbility { +public: + static bool MakeAndRegisterAbility(SystemAbility*) + { + return true; + } + + virtual void OnStart() {}; + + virtual void OnStop() {}; + + MOCK_METHOD1(Publish, bool(sptr)); + + SystemAbility(bool runOnCreate = false) {}; + + SystemAbility(const int32_t serviceId, bool runOnCreate = false) {}; + + virtual ~SystemAbility() = default; +}; +} // namespace OHOS +#endif // MOCK_SECURITY_COMPONENT_SYSTEM_ABILITY_H diff --git a/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp b/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d83e9f01b665b7f20f49db9d9cb4463e35b095f8 --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_app_mgr_proxy.cpp @@ -0,0 +1,20 @@ +/* +* Copyright (c) 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. +*/ + +#include "mock_app_mgr_proxy.h" + +namespace OHOS { +MockAppMgrProxy* MockAppMgrProxy::g_MockAppMgrProxy = nullptr; +} diff --git a/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp b/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62174e8997770d3412923f75a6bb868a1efe5a02 --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_ipc_skeleton.cpp @@ -0,0 +1,20 @@ +/* +* Copyright (c) 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. +*/ +#include "ipc_skeleton.h" + +namespace OHOS { +uint32_t IPCSkeleton::tokenID = 0; +pid_t IPCSkeleton::pid = -1; +} // namespace OHOS diff --git a/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp b/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7abc1fa0b728dcc88d95b324286181ca7d2a84bf --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/mock_iservice_registry.cpp @@ -0,0 +1,34 @@ + /* + * Copyright (c) 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. + */ + +#include "iservice_registry.h" + +namespace OHOS { +SystemAbilityManagerClient* SystemAbilityManagerClient::clientInstance = nullptr; +SystemAbilityManagerClient SystemAbilityManagerClient::defaultInstance; +std::mutex SystemAbilityManagerClient::instanceMtx; + +SystemAbilityManagerClient& SystemAbilityManagerClient::GetInstance() +{ + std::lock_guard lock(instanceMtx); + if (clientInstance == nullptr) { + clientInstance = new (std::nothrow)SystemAbilityManagerClient(); + if (clientInstance == nullptr) { + return defaultInstance; + } + } + return *clientInstance; +} +} // namespace OHOS diff --git a/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp b/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c5538ef39a91bf4a393e73ae15ff7bb29591ff5 --- /dev/null +++ b/services/security_component_service/sa/test/mock/src/sec_comp_enhance_adapter.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_enhance_adapter.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "MockSecCompEnhanceAdapter"}; +} + +int32_t SecCompEnhanceAdapter::SetEnhanceCfg(uint8_t* cfg, uint32_t cfgLen) +{ + SC_LOG_DEBUG(LABEL, "SetEnhanceCfg success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::GetPointerEventEnhanceData(void* data, uint32_t dataLen, + uint8_t* enhanceData, uint32_t& enHancedataLen) +{ + SC_LOG_DEBUG(LABEL, "GetPointerEventEnhanceData success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::CheckExtraInfo(const SecCompClickEvent& touchInfo) +{ + SC_LOG_DEBUG(LABEL, "CheckExtraInfo success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::EnableInputEnhance() +{ + SC_LOG_DEBUG(LABEL, "EnableInputEnhance success"); + return SC_OK; +} + +int32_t SecCompEnhanceAdapter::DisableInputEnhance() +{ + SC_LOG_DEBUG(LABEL, "DisableInputEnhance success"); + return SC_OK; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(std::string& componentInfo) +{ + SC_LOG_DEBUG(LABEL, "EnhanceDataPreprocess success"); + return true; +} + +bool SecCompEnhanceAdapter::EnhanceDataPreprocess(int32_t scId, std::string& componentInfo) +{ + SC_LOG_DEBUG(LABEL, "EnhanceDataPreprocess success"); + return true; +} + +void SecCompEnhanceAdapter::RegisterScIdEnhance(int32_t scId) +{ + SC_LOG_DEBUG(LABEL, "RegisterScIdEnhance success"); +} + +void SecCompEnhanceAdapter::UnregisterScIdEnhance(int32_t scId) +{ + SC_LOG_DEBUG(LABEL, "UnregisterScIdEnhance success"); +} + +void SecCompEnhanceAdapter::StartEnhanceService() +{ + SC_LOG_DEBUG(LABEL, "StartEnhanceService success"); +} + +void SecCompEnhanceAdapter::ExistEnhanceService() +{ + SC_LOG_DEBUG(LABEL, "ExistEnhanceService success"); +} + +void SecCompEnhanceAdapter::NotifyProcessDied(int32_t pid) +{ + SC_LOG_DEBUG(LABEL, "NotifyProcessDied success"); +} + +int32_t SecCompEnhanceAdapter::CheckComponentInfoEnhnace(int32_t pid, + std::shared_ptr& compInfo, const nlohmann::json& jsonComponent) +{ + SC_LOG_DEBUG(LABEL, "CheckComponentInfoEnhnace success"); + return SC_OK; +} + +sptr SecCompEnhanceAdapter::GetEnhanceRemoteObject() +{ + SC_LOG_DEBUG(LABEL, "GetEnhanceRemoteObject success"); + return nullptr; +} +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS diff --git a/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4923cdb83f168b09662c888907b0e539383e142e --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 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. + */ +#include "app_state_observer_test.h" +#include "sec_comp_log.h" +#include "sec_comp_err.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "AppStateObserverTest"}; + +static constexpr int32_t TEST_UID = 1; +static constexpr int32_t TEST_UID_2 = 2; +static constexpr int32_t TEST_PID = 1; +static constexpr int32_t TEST_PID_2 = 2; +} + +void AppStateObserverTest::SetUpTestCase() +{} + +void AppStateObserverTest::TearDownTestCase() +{} + +void AppStateObserverTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (observer_ != nullptr) { + return; + } + + observer_ = std::make_shared(); + ASSERT_NE(nullptr, observer_); +} + +void AppStateObserverTest::TearDown() +{ + observer_ = nullptr; +} + +/** + * @tc.name: IsProcessForeground001 + * @tc.desc: Test is process foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, IsProcessForeground001, TestSize.Level1) +{ + ASSERT_FALSE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + AppExecFwk::AppStateData stateData = { + .pid = TEST_PID, + .uid = TEST_UID, + }; + observer_->AddProcessToForegroundSet(stateData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); +} + +/** + * @tc.name: AddProcessToForegroundSet001 + * @tc.desc: Test add process to foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, AddProcessToForegroundSet001, TestSize.Level1) +{ + AppExecFwk::AppStateData stateData = { + .pid = TEST_PID, + .uid = TEST_UID, + }; + observer_->AddProcessToForegroundSet(stateData); + observer_->AddProcessToForegroundSet(stateData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + + AppExecFwk::ProcessData procData = { + .pid = TEST_PID_2, + .uid = TEST_UID_2, + }; + observer_->AddProcessToForegroundSet(procData); + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID_2, TEST_UID_2)); +} + +/** + * @tc.name: RemoveProcessFromForegroundSet001 + * @tc.desc: Test remove process from foreground + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, RemoveProcessFromForegroundSet001, TestSize.Level1) +{ + AppExecFwk::ProcessData procData = { + .pid = TEST_PID, + .uid = TEST_UID, + }; + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + observer_->RemoveProcessFromForegroundSet(procData); + observer_->RemoveProcessFromForegroundSet(procData); + ASSERT_FALSE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); +} + +/** + * @tc.name: RemoveProcessFromForegroundSet002 + * @tc.desc: Test remove process with different uid + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, RemoveProcessFromForegroundSet002, TestSize.Level1) +{ + AppExecFwk::ProcessData procData = { + .pid = TEST_PID, + .uid = TEST_UID, + }; + observer_->AddProcessToForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + procData.pid = TEST_PID_2; + observer_->RemoveProcessFromForegroundSet(procData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); +} + +/** + * @tc.name: OnProcessStateChanged001 + * @tc.desc: Test recieve process state changed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, OnProcessStateChanged001, TestSize.Level1) +{ + AppExecFwk::ProcessData processData; + processData.state = AppExecFwk::AppProcessState::APP_STATE_CREATE; + observer_->OnProcessStateChanged(processData); + ASSERT_EQ(observer_->foregrandProcList_.size(), static_cast(0)); + + processData.state = AppExecFwk::AppProcessState::APP_STATE_FOREGROUND; + processData.pid = TEST_PID; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + + processData.state = AppExecFwk::AppProcessState::APP_STATE_BACKGROUND; + processData.pid = TEST_PID; + observer_->OnProcessStateChanged(processData); + ASSERT_FALSE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); +} + +/** + * @tc.name: OnProcessDied001 + * @tc.desc: Test recieve process state died + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(AppStateObserverTest, OnProcessDied001, TestSize.Level1) +{ + AppExecFwk::ProcessData processData; + processData.state = AppExecFwk::AppProcessState::APP_STATE_FOREGROUND; + processData.pid = TEST_PID; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); + + // if last process died, the sec_comp service will exit. + processData.pid = TEST_PID_2; + observer_->OnProcessStateChanged(processData); + ASSERT_TRUE(observer_->IsProcessForeground(TEST_PID_2, TEST_UID_2)); + + // notify process 1 died + processData.pid = TEST_PID; + observer_->OnProcessDied(processData); + ASSERT_FALSE(observer_->IsProcessForeground(TEST_PID, TEST_UID)); +} diff --git a/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7195cf2b88d3f55ff06aa59a8a1494689a580446 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/app_state_observer_test.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 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. + */ +#ifndef APP_STATE_OBSERVER_TEST_H +#define APP_STATE_OBSERVER_TEST_H + +#include +#define private public +#include "app_state_observer.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class AppStateObserverTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + std::shared_ptr observer_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // APP_STATE_OBSERVER_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66d2831b294ff79601e4955bae1d60add2e7b11d --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_entity_test.h" +#include "sec_comp_log.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_tool.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompEntityTest"}; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_DIFF_COORDINATE = 200.0; +static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; +} + +void SecCompEntityTest::SetUpTestCase() +{} + +void SecCompEntityTest::TearDownTestCase() +{} + +void SecCompEntityTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (entity_ != nullptr) { + return; + } + + std::shared_ptr component = std::make_shared(); + ASSERT_NE(nullptr, component); + + entity_ = std::make_shared(component, 1, 1); + ASSERT_NE(nullptr, entity_); +} + +void SecCompEntityTest::TearDown() +{ + entity_ = nullptr; +} + +/** + * @tc.name: RevokeTempPermission001 + * @tc.desc: Test revoke temp permission + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, RevokeTempPermission001, TestSize.Level1) +{ + entity_->isGrant_ = false; + ASSERT_EQ(entity_->RevokeTempPermission(), SC_OK); + + entity_->isGrant_ = true; + entity_->componentInfo_->type_ = UNKNOWN_SC_TYPE; + ASSERT_EQ(entity_->RevokeTempPermission(), SC_SERVICE_ERROR_PERMISSION_OPER_FAIL); + ASSERT_FALSE(entity_->isGrant_); + + entity_->isGrant_ = true; + entity_->componentInfo_->type_ = LOCATION_COMPONENT; + ASSERT_EQ(entity_->RevokeTempPermission(), SC_OK); + ASSERT_FALSE(entity_->isGrant_); +} + +/** + * @tc.name: GrantTempPermission001 + * @tc.desc: Test grant location permission + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, GrantTempPermission001, TestSize.Level1) +{ + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = UNKNOWN_SC_TYPE; + ASSERT_EQ(entity_->GrantTempPermission(), SC_SERVICE_ERROR_PERMISSION_OPER_FAIL); + ASSERT_TRUE(entity_->isGrant_); + + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = LOCATION_COMPONENT; + ASSERT_EQ(entity_->GrantTempPermission(), SC_OK); + ASSERT_TRUE(entity_->isGrant_); + + entity_->isGrant_ = false; + entity_->componentInfo_->type_ = PASTE_COMPONENT; + ASSERT_EQ(entity_->GrantTempPermission(), SC_OK); + ASSERT_TRUE(entity_->isGrant_); +} + +/** + * @tc.name: GrantTempPermission002 + * @tc.desc: Test grant paste permission with invalid tokenId. + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, GrantTempPermission002, TestSize.Level1) +{ + std::shared_ptr pasteComponent = std::make_shared(); + ASSERT_NE(nullptr, pasteComponent); + + entity_ = std::make_shared(pasteComponent, 0, 1); + ASSERT_NE(nullptr, entity_); + + ASSERT_EQ(entity_->GrantTempPermission(), SC_SERVICE_ERROR_PERMISSION_OPER_FAIL); + ASSERT_EQ(entity_->RevokeTempPermission(), SC_SERVICE_ERROR_PERMISSION_OPER_FAIL); +} + +/** + * @tc.name: CheckTouchInfo001 + * @tc.desc: Test touch info + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompEntityTest, CheckTouchInfo001, TestSize.Level1) +{ + SecCompClickEvent touch = { + .touchX = TEST_COORDINATE, + .touchY = TEST_COORDINATE, + .timestamp = 0, + }; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + uint64_t current = static_cast(std::chrono::high_resolution_clock::now().time_since_epoch().count()); + touch.timestamp = current + 10000L; // 10s + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + entity_->componentInfo_->rect_.x_ = TEST_DIFF_COORDINATE; // click event will not hit this rect + entity_->componentInfo_->rect_.y_ = TEST_DIFF_COORDINATE; + entity_->componentInfo_->rect_.width_ = TEST_DIFF_COORDINATE; + entity_->componentInfo_->rect_.height_ = TEST_DIFF_COORDINATE; + touch.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); + + entity_->componentInfo_->rect_.x_ = TEST_COORDINATE; + entity_->componentInfo_->rect_.y_ = TEST_COORDINATE; + touch.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_FALSE(entity_->CheckTouchInfo(touch)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h new file mode 100644 index 0000000000000000000000000000000000000000..c65cf377d77180ea4843c551596866f4d12cf09f --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_entity_test.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_ENTITY_TEST_H +#define SEC_COMP_ENTITY_TEST_H + +#include +#define private public +#include "sec_comp_entity.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompEntityTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + std::shared_ptr entity_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_ENTITY_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac86c7feb30145510cd8e3e4eb4f612393a7ff33 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.cpp @@ -0,0 +1,713 @@ +/* + * Copyright (c) 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. + */ + +#include "sec_comp_info_helper_test.h" +#include "location_button.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "display.h" +#include "display_info.h" +#include "display_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompInfoHelperTest"}; + +static constexpr float TEST_SIZE = 100.0; +static constexpr double TEST_DIMENSION = 100.0; +static constexpr double TEST_INVALID_DIMENSION = -100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0xff7fff00; +static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; +static constexpr uint32_t TEST_COLOR_INVALID = 0x66000000; +static constexpr uint32_t TEST_COLOR_BLACK = 0x00000000; +static constexpr uint32_t TEST_COLOR_WHITE = 0xffffffff; +static constexpr uint32_t QUARTER = 4; +static constexpr double ZERO_OFFSET = 0.0F; +static double g_curScreenWidth = 0.0F; +static double g_curScreenHeight = 0.0F; +static double g_testWidth = 0.0F; +static double g_testHeight = 0.0F; + +static bool GetScreenSize() +{ + sptr display = + OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplaySync(); + if (display == nullptr) { + return false; + } + + auto info = display->GetDisplayInfo(); + if (info == nullptr) { + return false; + } + + g_curScreenWidth = static_cast(info->GetWidth()); + g_curScreenHeight = static_cast(info->GetHeight()); + return true; +} + +static void BuildLocationComponentInfo(nlohmann::json& jsonComponent) +{ + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = LOCATION_COMPONENT; + jsonComponent[JsonTagConstants::JSON_NODE_ID] = 0; + jsonComponent[JsonTagConstants::JSON_RECT] = nlohmann::json { + {JsonTagConstants::JSON_RECT_X, g_testWidth }, + {JsonTagConstants::JSON_RECT_Y, g_testHeight }, + {JsonTagConstants::JSON_RECT_WIDTH, g_testWidth }, + {JsonTagConstants::JSON_RECT_HEIGHT, g_testHeight } + }; + jsonComponent[JsonTagConstants::JSON_WINDOW_RECT] = nlohmann::json { + { JsonTagConstants::JSON_RECT_X, g_testWidth }, + { JsonTagConstants::JSON_RECT_Y, g_testHeight }, + { JsonTagConstants::JSON_RECT_WIDTH, g_testWidth }, + { JsonTagConstants::JSON_RECT_HEIGHT, g_testHeight } + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + + jsonComponent[JsonTagConstants::JSON_BORDER_TAG] = nlohmann::json { + { JsonTagConstants::JSON_BORDER_WIDTH_TAG, TEST_SIZE }, + }; + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, false }, + }; + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; +} +} + +void SecCompInfoHelperTest::SetUpTestCase() +{ + ASSERT_TRUE(GetScreenSize()); + g_testWidth = (ZERO_OFFSET + g_curScreenWidth) / QUARTER; + g_testHeight = (ZERO_OFFSET + g_curScreenHeight) / QUARTER; +} + +void SecCompInfoHelperTest::TearDownTestCase() +{} + +void SecCompInfoHelperTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SecCompInfoHelperTest::TearDown() +{} + +/** + * @tc.name: ParseComponent001 + * @tc.desc: Test parse component info success + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_NE(comp, nullptr); + ASSERT_TRUE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent002 + * @tc.desc: Test parse component info with empty json + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + ASSERT_EQ(SecCompInfoHelper::ParseComponent(UNKNOWN_SC_TYPE, jsonComponent), nullptr); + + ASSERT_EQ(SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent), nullptr); + ASSERT_EQ(SecCompInfoHelper::ParseComponent(PASTE_COMPONENT, jsonComponent), nullptr); + ASSERT_EQ(SecCompInfoHelper::ParseComponent(SAVE_COMPONENT, jsonComponent), nullptr); +} + +/** + * @tc.name: ParseComponent003 + * @tc.desc: Test parse component info with invalid type + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_SC_TYPE] = UNKNOWN_SC_TYPE; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_EQ(comp, nullptr); +} + +/** + * @tc.name: ParseComponent004 + * @tc.desc: Test parse component info with invalid rect + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent004, TestSize.Level1) +{ + SecCompRect rect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + SecCompRect windowRect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + ASSERT_TRUE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + + rect.x_ = TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.x_ = g_curScreenWidth + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = g_curScreenHeight + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.width_ = g_curScreenWidth; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.height_ = g_curScreenHeight; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.x_ = g_curScreenWidth - g_testWidth; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + rect.y_ = g_curScreenHeight - g_testHeight; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); +} + +/** + * @tc.name: ParseComponent005 + * @tc.desc: Test parse component info with windowRect invalid + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent005, TestSize.Level1) +{ + SecCompRect rect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + SecCompRect windowRect = { + .x_ = g_testWidth, + .y_ = g_testHeight, + .width_ = g_testWidth, + .height_ = g_testHeight + }; + ASSERT_TRUE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + + windowRect.x_ = g_testWidth + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.y_ = g_testHeight + 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.width_ = g_testWidth - 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.height_ = g_testHeight - 1; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.width_ = TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); + windowRect.height_ = TEST_INVALID_DIMENSION; + ASSERT_FALSE(SecCompInfoHelper::CheckRectValid(rect, windowRect)); +} + +/** + * @tc.name: ParseComponent006 + * @tc.desc: Test parse component info with parentEffect active + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent006, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_PARENT_TAG] = nlohmann::json { + { JsonTagConstants::JSON_PARENT_EFFECT_TAG, true }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent007 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent007, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent008 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent008, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent009 + * @tc.desc: Test parse component info with invalid size + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent009, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_INVALID_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_INVALID_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent010 + * @tc.desc: Test parse component info with invalid color + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent010, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_INVALID }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_INVALID }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_INVALID } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent011 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent011, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, NO_TEXT }, + { JsonTagConstants::JSON_ICON_TAG, NO_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent012 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent012, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLUE }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::CIRCLE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_YELLOW }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_YELLOW } + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent013 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent013, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + +/** + * @tc.name: ParseComponent014 + * @tc.desc: Test parse component info with invalid style + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, ParseComponent014, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + + jsonComponent[JsonTagConstants::JSON_STYLE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_TEXT_TAG, LocationDesc::SELECT_LOCATION }, + { JsonTagConstants::JSON_ICON_TAG, LocationIcon::LINE_ICON }, + { JsonTagConstants::JSON_BG_TAG, SecCompBackground::NO_BG_TYPE }, + }; + + nlohmann::json jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, TEST_DIMENSION }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, MIN_PADDING_WITHOUT_BG }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); + + jsonPadding = nlohmann::json { + { JsonTagConstants::JSON_PADDING_TOP_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_RIGHT_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_BOTTOM_TAG, MIN_PADDING_WITHOUT_BG }, + { JsonTagConstants::JSON_PADDING_LEFT_TAG, TEST_DIMENSION }, + }; + + jsonComponent[JsonTagConstants::JSON_SIZE_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_ICON_SIZE_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_TEXT_ICON_PADDING_TAG, TEST_SIZE }, + { JsonTagConstants::JSON_PADDING_SIZE_TAG, jsonPadding }, + }; + comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_FALSE(comp->GetValid()); +} + + +/** + * @tc.name: CheckComponentValid001 + * @tc.desc: Test CheckComponentValid with invalid color + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid001, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + ASSERT_TRUE(comp->GetValid()); + jsonComponent[JsonTagConstants::JSON_COLORS_TAG] = nlohmann::json { + { JsonTagConstants::JSON_FONT_COLOR_TAG, TEST_COLOR_RED }, + { JsonTagConstants::JSON_ICON_COLOR_TAG, TEST_COLOR_BLACK }, + { JsonTagConstants::JSON_BG_COLOR_TAG, TEST_COLOR_WHITE } + }; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); +} + +/** + * @tc.name: CheckComponentValid002 + * @tc.desc: Test CheckComponentValid with invalid text or icon + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid002, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + comp->text_ = UNKNOWN_TEXT; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->text_ = static_cast(LocationDesc::SELECT_LOCATION); + comp->icon_ = UNKNOWN_ICON; + ASSERT_TRUE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->text_ = UNKNOWN_TEXT; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); +} + +/** + * @tc.name: CheckComponentValid003 + * @tc.desc: Test CheckComponentValid with invalid type + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompInfoHelperTest, CheckComponentValid003, TestSize.Level1) +{ + nlohmann::json jsonComponent; + BuildLocationComponentInfo(jsonComponent); + SecCompBase* comp = SecCompInfoHelper::ParseComponent(LOCATION_COMPONENT, jsonComponent); + comp->type_ = SecCompType::UNKNOWN_SC_TYPE; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); + + comp->type_ = SecCompType::MAX_SC_TYPE; + ASSERT_FALSE(SecCompInfoHelper::CheckComponentValid(comp)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h new file mode 100644 index 0000000000000000000000000000000000000000..a9d845964b1791d69009082178f2339c7c47b3de --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_info_helper_test.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 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. + */ +#ifndef SEC_COMP_INFO_HELPER_TEST_H +#define SEC_COMP_INFO_HELPER_TEST_H + +#include +#include "sec_comp_info_helper.h" + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompInfoHelperTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_ENTITY_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..737c9388c8de0eeaee0391a8f6c2674ea034b90d --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.cpp @@ -0,0 +1,361 @@ +/* + * Copyright (c) 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. + */ + +#include "sec_comp_manager_test.h" +#include "sec_comp_log.h" +#include "location_button.h" +#include "save_button.h" +#include "sec_comp_err.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompManagerTest"}; + +static constexpr double TEST_SIZE = 100.0; +static constexpr uint32_t TEST_INVALID_SIZE = 0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr uint32_t TEST_COLOR = 0xffffffff; +static constexpr uint32_t TEST_COLOR_YELLOW = 0xff7fff00; +static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; + +static constexpr int32_t TEST_PID_1 = 1; +static constexpr int32_t TEST_PID_2 = 2; +static constexpr int32_t TEST_PID_3 = 3; + +static constexpr AccessTokenID TEST_TOKEN_ID = 1; +static constexpr int32_t TEST_SC_ID_1 = 1; +static constexpr int32_t TEST_SC_ID_2 = 2; +static constexpr int32_t TEST_INVALID_SC_ID = -1; + +static constexpr int32_t MAX_INT_NUM = 0x7fffffff; +static constexpr int32_t SC_ID_START = 1000; + +static LocationButton BuildInvalidLocationComponent() +{ + LocationButton button; + button.fontSize_ = TEST_INVALID_SIZE; + button.iconSize_ = TEST_INVALID_SIZE; + button.padding_.top = TEST_INVALID_SIZE; + button.padding_.right = TEST_INVALID_SIZE; + button.padding_.bottom = TEST_INVALID_SIZE; + button.padding_.left = TEST_INVALID_SIZE; + button.textIconSpace_ = TEST_INVALID_SIZE; + button.fontColor_.value = TEST_COLOR; + button.iconColor_.value = TEST_COLOR; + button.bgColor_.value = TEST_COLOR; + button.borderWidth_ = TEST_INVALID_SIZE; + button.type_ = LOCATION_COMPONENT; + button.rect_.x_ = TEST_COORDINATE; + button.rect_.y_ = TEST_COORDINATE; + button.rect_.width_ = TEST_COORDINATE; + button.rect_.height_ = TEST_COORDINATE; + button.windowRect_.x_ = TEST_COORDINATE; + button.windowRect_.y_ = TEST_COORDINATE; + button.windowRect_.width_ = TEST_COORDINATE; + button.windowRect_.height_ = TEST_COORDINATE; + button.text_ = UNKNOWN_TEXT; + button.icon_ = UNKNOWN_ICON; + button.bg_ = SecCompBackground::UNKNOWN_BG; + return button; +} + +static LocationButton BuildValidLocationComponent() +{ + LocationButton button; + button.fontSize_ = TEST_SIZE; + button.iconSize_ = TEST_SIZE; + button.padding_.top = TEST_SIZE; + button.padding_.right = TEST_SIZE; + button.padding_.bottom = TEST_SIZE; + button.padding_.left = TEST_SIZE; + button.textIconSpace_ = TEST_SIZE; + button.fontColor_.value = TEST_COLOR_YELLOW; + button.iconColor_.value = TEST_COLOR_RED; + button.bgColor_.value = TEST_COLOR_BLUE; + button.borderWidth_ = TEST_SIZE; + button.type_ = LOCATION_COMPONENT; + button.rect_.x_ = TEST_COORDINATE; + button.rect_.y_ = TEST_COORDINATE; + button.rect_.width_ = TEST_COORDINATE; + button.rect_.height_ = TEST_COORDINATE; + button.windowRect_.x_ = TEST_COORDINATE; + button.windowRect_.y_ = TEST_COORDINATE; + button.windowRect_.width_ = TEST_COORDINATE; + button.windowRect_.height_ = TEST_COORDINATE; + button.text_ = static_cast(LocationDesc::SELECT_LOCATION); + button.icon_ = static_cast(LocationIcon::LINE_ICON); + button.bg_ = SecCompBackground::CIRCLE; + return button; +} +} + +void SecCompManagerTest::SetUpTestCase() +{} + +void SecCompManagerTest::TearDownTestCase() +{} + +void SecCompManagerTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); +} + +void SecCompManagerTest::TearDown() +{ + SecCompManager::GetInstance().componentMap_.clear(); +} + + +/** + * @tc.name: CreateScId001 + * @tc.desc: Test create sc id + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, CreateScId001, TestSize.Level1) +{ + SecCompManager::GetInstance().scIdStart_ = MAX_INT_NUM; + ASSERT_EQ(SecCompManager::GetInstance().CreateScId(), SC_ID_START); + + SecCompManager::GetInstance().scIdStart_ = SC_ID_START; + ASSERT_EQ(SecCompManager::GetInstance().CreateScId(), SC_ID_START + 1); +} + +/** + * @tc.name: AddSecurityComponentToList001 + * @tc.desc: Test add security component to list + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, AddSecurityComponentToList001, TestSize.Level1) +{ + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(compPtr, nullptr); + compPtr->rect_.x_ = TEST_COORDINATE; + compPtr->rect_.y_ = TEST_COORDINATE; + compPtr->rect_.width_ = TEST_COORDINATE; + compPtr->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity(compPtr, TEST_TOKEN_ID, TEST_SC_ID_1); + + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(1, entity), SC_OK); + + std::shared_ptr compPtrNew = std::make_shared(); + ASSERT_NE(compPtrNew, nullptr); + compPtrNew->rect_.x_ = TEST_COORDINATE * 2; // not overlap + compPtrNew->rect_.y_ = TEST_COORDINATE * 2; // not overlap + compPtrNew->rect_.width_ = TEST_COORDINATE; + compPtrNew->rect_.height_ = TEST_COORDINATE; + SecCompEntity entityNew(compPtrNew, TEST_TOKEN_ID, TEST_SC_ID_2); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(1, entityNew), SC_OK); +} + +/** + * @tc.name: DeleteSecurityComponentFromList001 + * @tc.desc: Test delete security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, DeleteSecurityComponentFromList001, TestSize.Level1) +{ + ASSERT_EQ(SecCompManager::GetInstance().DeleteSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), + SC_SERVICE_ERROR_COMPONENT_NOT_EXIST); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(compPtr, nullptr); + compPtr->rect_.x_ = TEST_COORDINATE; + compPtr->rect_.y_ = TEST_COORDINATE; + compPtr->rect_.width_ = TEST_COORDINATE; + compPtr->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity(compPtr, TEST_TOKEN_ID, TEST_SC_ID_1); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(TEST_PID_1, entity), SC_OK); + + ASSERT_EQ(SecCompManager::GetInstance().DeleteSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_2), + SC_SERVICE_ERROR_COMPONENT_NOT_EXIST); + + ASSERT_EQ(SecCompManager::GetInstance().DeleteSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), SC_OK); +} + +/** + * @tc.name: GetSecurityComponentFromList001 + * @tc.desc: Test get security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, GetSecurityComponentFromList001, TestSize.Level1) +{ + ASSERT_EQ(SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), nullptr); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(compPtr, nullptr); + compPtr->rect_.x_ = TEST_COORDINATE; + compPtr->rect_.y_ = TEST_COORDINATE; + compPtr->rect_.width_ = TEST_COORDINATE; + compPtr->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity(compPtr, TEST_TOKEN_ID, TEST_SC_ID_1); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(TEST_PID_1, entity), SC_OK); + ASSERT_EQ(SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_2), nullptr); + ASSERT_NE(SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), nullptr); +} + +/** + * @tc.name: NotifyProcessBackground001 + * @tc.desc: Test notify process background + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, NotifyProcessBackground001, TestSize.Level1) +{ + SecCompManager::GetInstance().NotifyProcessBackground(TEST_PID_1); + + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(compPtr, nullptr); + compPtr->rect_.x_ = TEST_COORDINATE; + compPtr->rect_.y_ = TEST_COORDINATE; + compPtr->rect_.width_ = TEST_COORDINATE; + compPtr->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity(compPtr, TEST_TOKEN_ID, TEST_SC_ID_1); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(TEST_PID_1, entity), SC_OK); + auto component = SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1); + ASSERT_NE(component, nullptr); + SecCompManager::GetInstance().NotifyProcessForeground(TEST_PID_1); + ASSERT_TRUE(SecCompManager::GetInstance().IsForegroundCompExist()); + + SecCompManager::GetInstance().NotifyProcessBackground(TEST_PID_1); + ASSERT_FALSE(SecCompManager::GetInstance().IsForegroundCompExist()); +} + +/** + * @tc.name: NotifyProcessDied001 + * @tc.desc: Test notify process died + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, NotifyProcessDied001, TestSize.Level1) +{ + std::shared_ptr compPtr = std::make_shared(); + ASSERT_NE(compPtr, nullptr); + compPtr->rect_.x_ = TEST_COORDINATE; + compPtr->rect_.y_ = TEST_COORDINATE; + compPtr->rect_.width_ = TEST_COORDINATE; + compPtr->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity(compPtr, TEST_TOKEN_ID, TEST_SC_ID_1); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(TEST_PID_1, entity), SC_OK); + + std::shared_ptr compPtr2 = std::make_shared(); + ASSERT_NE(compPtr2, nullptr); + compPtr2->rect_.x_ = TEST_COORDINATE * 2; // not overlap + compPtr2->rect_.y_ = TEST_COORDINATE * 2; // not overlap + compPtr2->rect_.width_ = TEST_COORDINATE; + compPtr2->rect_.height_ = TEST_COORDINATE; + SecCompEntity entity2(compPtr2, TEST_TOKEN_ID, TEST_SC_ID_2); + ASSERT_EQ(SecCompManager::GetInstance().AddSecurityComponentToList(TEST_PID_2, entity2), SC_OK); + + SecCompManager::GetInstance().NotifyProcessDied(TEST_PID_3); + ASSERT_NE(SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), nullptr); + + SecCompManager::GetInstance().NotifyProcessDied(TEST_PID_1); + ASSERT_EQ(SecCompManager::GetInstance().GetSecurityComponentFromList(TEST_PID_1, TEST_SC_ID_1), nullptr); +} + +/** + * @tc.name: RegisterSecurityComponent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, RegisterSecurityComponent001, TestSize.Level1) +{ + nlohmann::json jsonInvalid; + LocationButton buttonInvalid = BuildInvalidLocationComponent(); + buttonInvalid.ToJson(jsonInvalid); + int32_t scId; + SecCompCallerInfo caller = { + .tokenId = TEST_TOKEN_ID, + .pid = TEST_PID_1 + }; + ASSERT_EQ(SecCompManager::GetInstance().RegisterSecurityComponent(LOCATION_COMPONENT, jsonInvalid, caller, scId), + SC_SERVICE_ERROR_COMPONENT_INFO_INVALID); + + nlohmann::json jsonValid; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonValid); + + // callback check failed + ASSERT_EQ(SecCompManager::GetInstance().RegisterSecurityComponent( + LOCATION_COMPONENT, jsonValid, caller, scId), SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST); + SecCompManager::GetInstance().maliciousAppList_.clear(); +} + +/** + * @tc.name: UpdateSecurityComponent001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, UpdateSecurityComponent001, TestSize.Level1) +{ + nlohmann::json jsonValid; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonValid); + SecCompCallerInfo caller = { + .tokenId = TEST_TOKEN_ID, + .pid = TEST_PID_1 + }; + ASSERT_NE(SecCompManager::GetInstance().UpdateSecurityComponent(TEST_SC_ID_1, jsonValid, caller), + SC_OK); +} + +/** + * @tc.name: UnregisterSecurityComponent001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, UnregisterSecurityComponent001, TestSize.Level1) +{ + SecCompCallerInfo caller = { + .tokenId = TEST_TOKEN_ID, + .pid = TEST_PID_1 + }; + + ASSERT_EQ(SecCompManager::GetInstance().UnregisterSecurityComponent(TEST_INVALID_SC_ID, caller), + SC_SERVICE_ERROR_VALUE_INVALID); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test report security component click + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompManagerTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + SecCompCallerInfo caller = { + .tokenId = TEST_TOKEN_ID, + .pid = TEST_PID_1 + }; + SecCompClickEvent touchInfo; + nlohmann::json jsonVaild; + LocationButton buttonValid = BuildValidLocationComponent(); + buttonValid.ToJson(jsonVaild); + ASSERT_NE(SecCompManager::GetInstance(). + ReportSecurityComponentClickEvent(1, jsonVaild, caller, touchInfo, nullptr), SC_OK); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h new file mode 100644 index 0000000000000000000000000000000000000000..eaf0968fec369055981fa5a373026fd7d06e4a43 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_manager_test.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 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. + */ +#ifndef SEC_COMP_MANAGER_TEST_H +#define SEC_COMP_MANAGER_TEST_H + +#include +#define private public +#include "sec_comp_manager.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_MANAGER_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c430ebec42f25856ef2fe3ac965e0348a7a7af2b --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_mock_test.cpp @@ -0,0 +1,365 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_service_test.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "location_button.h" +#include "mock_system_ability_proxy.h" +#include "mock_app_mgr_proxy.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "sec_comp_enhance_adapter.h" +#include "system_ability.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompServiceTest"}; + +static constexpr uint32_t HAP_TOKEN_ID = 537715419; +static constexpr int32_t SA_ID = 3506; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_SIZE = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0xff7fff00; +static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; +static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; +static AccessTokenID g_selfTokenId = 0; + +static std::string BuildSaveComponentInfo() +{ + SaveButton button; + button.fontSize_ = TEST_SIZE; + button.iconSize_ = TEST_SIZE; + button.padding_.top = TEST_SIZE; + button.padding_.right = TEST_SIZE; + button.padding_.bottom = TEST_SIZE; + button.padding_.left = TEST_SIZE; + button.textIconSpace_ = TEST_SIZE; + button.fontColor_.value = TEST_COLOR_YELLOW; + button.iconColor_.value = TEST_COLOR_RED; + button.bgColor_.value = TEST_COLOR_BLUE; + button.borderWidth_ = TEST_SIZE; + button.type_ = SAVE_COMPONENT; + button.rect_.x_ = TEST_COORDINATE; + button.rect_.y_ = TEST_COORDINATE; + button.rect_.width_ = TEST_COORDINATE; + button.rect_.height_ = TEST_COORDINATE; + button.windowRect_.x_ = TEST_COORDINATE; + button.windowRect_.y_ = TEST_COORDINATE; + button.windowRect_.width_ = TEST_COORDINATE; + button.windowRect_.height_ = TEST_COORDINATE; + button.text_ = static_cast(SaveDesc::DOWNLOAD); + button.icon_ = static_cast(SaveIcon::LINE_ICON); + button.bg_ = SecCompBackground::CIRCLE; + + nlohmann::json jsonRes; + button.ToJson(jsonRes); + return jsonRes.dump(); +} +} + +void SecCompServiceTest::SetUpTestCase() +{} + +void SecCompServiceTest::TearDownTestCase() +{} + +void SecCompServiceTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (secCompService_ != nullptr) { + return; + } + SecCompService* ptr = new (std::nothrow) SecCompService(SA_ID, true); + secCompService_ = sptr(ptr); + ASSERT_NE(nullptr, secCompService_); + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + ASSERT_TRUE(secCompService_->appStateObserver_ != nullptr); + g_selfTokenId = GetSelfTokenID(); +} + +void SecCompServiceTest::TearDown() +{ + if (secCompService_ != nullptr) { + secCompService_->appStateObserver_ = nullptr; + } + secCompService_ = nullptr; + EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); +} + +/** + * @tc.name: RegisterSecurityComponent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, RegisterSecurityComponent001, TestSize.Level1) +{ + // get caller fail + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, "", scId), + SC_SERVICE_ERROR_VALUE_INVALID); + + // parse component json fail + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, "{a=", scId), + SC_SERVICE_ERROR_VALUE_INVALID); // wrong json + + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + EXPECT_EQ(secCompService_->UpdateSecurityComponent(scId, BuildSaveComponentInfo()), + SC_OK); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT + }; + + EXPECT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touch, nullptr), + SC_OK); + sleep(5); + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(scId), SC_OK); +} + +/** + * @tc.name: RegisterSecurityComponent002 + * @tc.desc: Test register security component check touch info failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, RegisterSecurityComponent002, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) + }; + EXPECT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touch, nullptr), + SC_SERVICE_ERROR_CLICK_EVENT_INVALID); + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(scId), SC_OK); +} + +/** + * @tc.name: RegisterSecurityComponent003 + * @tc.desc: Test register security component permission grant failed + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, RegisterSecurityComponent003, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + + ASSERT_EQ(SetSelfTokenID(0), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT + }; + EXPECT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touch, nullptr), + SC_SERVICE_ERROR_PERMISSION_OPER_FAIL); + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(scId), SC_OK); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(SC_OK, + secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr)); + + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(6); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(scId), SC_OK); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent002 + * @tc.desc: Test report security component click with save button + * @tc.type: FUNC + * @tc.require: AR000HO9IN + */ +HWTEST_F(SecCompServiceTest, ReportSecurityComponentClickEvent002, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT;; + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent003 + * @tc.desc: Test report security component click twice with save button + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, ReportSecurityComponentClickEvent003, TestSize.Level1) +{ + int32_t scId; + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->Initialize(); + + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + // register security component ok + EXPECT_EQ(secCompService_->RegisterSecurityComponent(SAVE_COMPONENT, BuildSaveComponentInfo(), scId), + SC_OK); + struct SecCompClickEvent touchInfo = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT + }; + + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(3); + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(6); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + + touchInfo.timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT; + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildSaveComponentInfo(), touchInfo, nullptr), + SC_OK); + sleep(3); + ASSERT_TRUE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); + ASSERT_FALSE(secCompService_->ReduceAfterVerifySavePermission(HAP_TOKEN_ID)); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b6fe8eae2385291d3566907dba00372317d3822 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.cpp @@ -0,0 +1,307 @@ +/* + * Copyright (c) 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. + */ +#include "sec_comp_service_test.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "location_button.h" +#include "mock_system_ability_proxy.h" +#include "mock_app_mgr_proxy.h" +#include "paste_button.h" +#include "save_button.h" +#include "sec_comp_err.h" +#include "sec_comp_log.h" +#include "sec_comp_tool.h" +#include "system_ability.h" +#include "token_setproc.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompServiceTest"}; + +static constexpr uint32_t HAP_TOKEN_ID = 537715419; +static constexpr int32_t SA_ID = 3506; +static constexpr int32_t TEST_SC_ID = 1; +static AccessTokenID g_selfTokenId = 0; +static constexpr double TEST_COORDINATE = 100.0; +static constexpr double TEST_SIZE = 100.0; +static constexpr uint32_t TEST_COLOR_YELLOW = 0xff7fff00; +static constexpr uint32_t TEST_COLOR_RED = 0xffff0000; +static constexpr uint32_t TEST_COLOR_BLUE = 0xff0000ff; +static constexpr uint64_t TIME_CONVERSION_UNIT = 1000; + +static std::string BuildLocationComponentInfo() +{ + LocationButton button; + button.fontSize_ = TEST_SIZE; + button.iconSize_ = TEST_SIZE; + button.padding_.top = TEST_SIZE; + button.padding_.right = TEST_SIZE; + button.padding_.bottom = TEST_SIZE; + button.padding_.left = TEST_SIZE; + button.textIconSpace_ = TEST_SIZE; + button.fontColor_.value = TEST_COLOR_YELLOW; + button.iconColor_.value = TEST_COLOR_RED; + button.bgColor_.value = TEST_COLOR_BLUE; + button.borderWidth_ = TEST_SIZE; + button.type_ = LOCATION_COMPONENT; + button.rect_.x_ = TEST_COORDINATE; + button.rect_.y_ = TEST_COORDINATE; + button.rect_.width_ = TEST_COORDINATE; + button.rect_.height_ = TEST_COORDINATE; + button.windowRect_.x_ = TEST_COORDINATE; + button.windowRect_.y_ = TEST_COORDINATE; + button.windowRect_.width_ = TEST_COORDINATE; + button.windowRect_.height_ = TEST_COORDINATE; + button.text_ = static_cast(LocationDesc::SELECT_LOCATION); + button.icon_ = static_cast(LocationIcon::LINE_ICON); + button.bg_ = SecCompBackground::CIRCLE; + + nlohmann::json jsonRes; + button.ToJson(jsonRes); + return jsonRes.dump(); +} +} + +void SecCompServiceTest::SetUpTestCase() +{} + +void SecCompServiceTest::TearDownTestCase() +{} + +void SecCompServiceTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (secCompService_ != nullptr) { + return; + } + SecCompService* ptr = new (std::nothrow) SecCompService(SA_ID, true); + secCompService_ = sptr(ptr); + ASSERT_NE(nullptr, secCompService_); + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + ASSERT_TRUE(secCompService_->appStateObserver_ != nullptr); + g_selfTokenId = GetSelfTokenID(); +} + +void SecCompServiceTest::TearDown() +{ + if (secCompService_ != nullptr) { + secCompService_->appStateObserver_ = nullptr; + } + secCompService_ = nullptr; + EXPECT_EQ(0, SetSelfTokenID(g_selfTokenId)); +} + +/** + * @tc.name: Onstart001 + * @tc.desc: Test OnStart + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, OnStart001, TestSize.Level1) +{ + secCompService_->state_ = ServiceRunningState::STATE_RUNNING; + secCompService_->appStateObserver_ = nullptr; + secCompService_->OnStart(); + ASSERT_EQ(secCompService_->appStateObserver_, nullptr); + EXPECT_CALL(*secCompService_, Publish(testing::_)).WillOnce(testing::Return(false)); + + secCompService_->state_ = ServiceRunningState::STATE_NOT_START; + secCompService_->appStateObserver_ = new (std::nothrow) AppStateObserver(); + secCompService_->OnStart(); + ASSERT_EQ(secCompService_->state_, ServiceRunningState::STATE_RUNNING); + + secCompService_->OnStop(); + ASSERT_EQ(secCompService_->appStateObserver_, nullptr); +} + +/** + * @tc.name: RegisterAppStateObserver001 + * @tc.desc: Test RegisterAppStateObserver + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, RegisterAppStateObserver001, TestSize.Level1) +{ + // GetSystemAbilityManager get failed + secCompService_->appStateObserver_ = nullptr; + std::shared_ptr saClient = std::make_shared(); + ASSERT_NE(saClient, nullptr); + SystemAbilityManagerClient::clientInstance = saClient.get(); + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(nullptr)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // GetSystemAbility get app mgr failed + secCompService_->appStateObserver_ = nullptr; + SystemAbilityManagerProxy proxy(nullptr); + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // RegisterApplicationStateObserver failed + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + MockIRemoteObject object; + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + sptr appProxy = new (std::nothrow) MockAppMgrProxy(nullptr); + MockAppMgrProxy::g_MockAppMgrProxy = appProxy; + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(-1)); + EXPECT_FALSE(secCompService_->RegisterAppStateObserver()); + + // GetForegroundApplications failed + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(0)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + GetForegroundApplications(testing::_)).WillOnce(testing::Return(-1)); + EXPECT_TRUE(secCompService_->RegisterAppStateObserver()); + EXPECT_EQ(secCompService_->appStateObserver_->foregrandProcList_.size(), static_cast(0)); + + // get one foreground app + secCompService_->appStateObserver_ = nullptr; + EXPECT_CALL(*saClient, GetSystemAbilityManager()).WillOnce(testing::Return(&proxy)); + EXPECT_CALL(proxy, GetSystemAbility(testing::_)).WillOnce(testing::Return(&object)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, + RegisterApplicationStateObserver(testing::_, testing::_)).WillOnce(testing::Return(0)); + EXPECT_CALL(*MockAppMgrProxy::g_MockAppMgrProxy, GetForegroundApplications(testing::_)) + .WillOnce([](std::vector& list) { + AppExecFwk::AppStateData data; + data.uid = 1000; + list.emplace_back(data); + return 0; + }); + EXPECT_TRUE(secCompService_->RegisterAppStateObserver()); + EXPECT_EQ(secCompService_->appStateObserver_->foregrandProcList_.size(), static_cast(1)); + secCompService_->UnregisterAppStateObserver(); + SystemAbilityManagerClient::clientInstance = nullptr; +} + +/** + * @tc.name: UnregisterAppStateObserver001 + * @tc.desc: Test RegisterAppStateObserver + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UnregisterAppStateObserver001, TestSize.Level1) +{ + // GetSystemAbilityManager get failed + secCompService_->appStateObserver_ = nullptr; + sptr appProxy = new (std::nothrow) MockAppMgrProxy(nullptr); + secCompService_->iAppMgr_ = appProxy; + + EXPECT_CALL(*appProxy, UnregisterApplicationStateObserver(testing::_)).Times(testing::Exactly(0)); + secCompService_->UnregisterAppStateObserver(); +} + +/** + * @tc.name: GetCallerInfo001 + * @tc.desc: Test get caller info + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, GetCallerInfo001, TestSize.Level1) +{ + // not root uid + setuid(1); + SecCompCallerInfo caller; + EXPECT_FALSE(secCompService_->GetCallerInfo(caller)); + + // set token id to hap token, but uid is not in foreground + EXPECT_FALSE(secCompService_->GetCallerInfo(caller)); + setuid(0); + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + // add local uid to foreground. + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + EXPECT_TRUE(secCompService_->GetCallerInfo(caller)); +} + +/** + * @tc.name: UnregisterSecurityComponent001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UnregisterSecurityComponent001, TestSize.Level1) +{ + // get caller fail + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(TEST_SC_ID), SC_SERVICE_ERROR_COMPONENT_NOT_EXIST); +} + +/** + * @tc.name: UpdateSecurityComponent001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, UpdateSecurityComponent001, TestSize.Level1) +{ + // get caller fail + EXPECT_EQ(secCompService_->UpdateSecurityComponent(TEST_SC_ID, ""), SC_SERVICE_ERROR_VALUE_INVALID); + + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + EXPECT_EQ(secCompService_->UpdateSecurityComponent(TEST_SC_ID, "{a"), SC_SERVICE_ERROR_VALUE_INVALID); +} + +/** + * @tc.name: ReportSecurityComponentClickEvent001 + * @tc.desc: Test report security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompServiceTest, ReportSecurityComponentClickEvent001, TestSize.Level1) +{ + auto uid = getuid(); + // get caller fail + int32_t scId; + EXPECT_EQ(secCompService_->RegisterSecurityComponent(LOCATION_COMPONENT, "", scId), + SC_SERVICE_ERROR_VALUE_INVALID); + + // parse component json fail + ASSERT_EQ(SetSelfTokenID(HAP_TOKEN_ID), 0); + setuid(100); + AppExecFwk::AppStateData stateData = { + .uid = getuid() + }; + secCompService_->appStateObserver_->AddProcessToForegroundSet(stateData); + + EXPECT_EQ(secCompService_->RegisterSecurityComponent(LOCATION_COMPONENT, BuildLocationComponentInfo(), scId), + SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST); + uint8_t data[16] = { 0 }; + struct SecCompClickEvent touch = { + .touchX = 100, + .touchY = 100, + .timestamp = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()) / TIME_CONVERSION_UNIT, + .extraInfo.data = data, + .extraInfo.dataSize = 16, + }; + EXPECT_EQ(secCompService_->ReportSecurityComponentClickEvent(scId, BuildLocationComponentInfo(), touch, nullptr), + SC_ENHANCE_ERROR_IN_MALICIOUS_LIST); + EXPECT_EQ(secCompService_->UnregisterSecurityComponent(scId), SC_SERVICE_ERROR_COMPONENT_NOT_EXIST); + setuid(uid); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h new file mode 100644 index 0000000000000000000000000000000000000000..4786c06e8dd8ea9234225c5db7ef96332b04f9e7 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_service_test.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_SERVICE_TEST_H +#define SEC_COMP_SERVICE_TEST_H + +#include +#define private public +#include "sec_comp_service.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { +class SecCompServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + sptr secCompService_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_SERVICE_TEST_H diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d29720da6719fa09df0278f40855e820dcf77a3a --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 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. + */ + +#include "sec_comp_stub_test.h" +#include "sec_comp_log.h" +#include "sec_comp_err.h" +#include "sec_comp_click_event_parcel.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Security::SecurityComponent; + +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompStubTest"}; +} + +void SecCompStubTest::SetUpTestCase() +{} + +void SecCompStubTest::TearDownTestCase() +{} + +void SecCompStubTest::SetUp() +{ + SC_LOG_INFO(LABEL, "setup"); + if (stub_ != nullptr) { + return; + } + + stub_ = new (std::nothrow) SecCompStubMock(); + ASSERT_NE(nullptr, stub_); +} + +void SecCompStubTest::TearDown() +{ + stub_ = nullptr; +} + +/** + * @tc.name: OnRemoteRequest001 + * @tc.desc: Test on remote request + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, OnRemoteRequest001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(u"wrong"); + ASSERT_EQ(stub_->OnRemoteRequest( + static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), + data, reply, option), SC_SERVICE_ERROR_IPC_REQUEST_FAIL); + + data.WriteInterfaceToken(u"ohos.security.ISecCompService"); + ASSERT_EQ(stub_->OnRemoteRequest( + static_cast(SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT), + data, reply, option), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInterfaceToken(u"ohos.security.ISecCompService"); + ASSERT_EQ(stub_->OnRemoteRequest(1000, data, reply, option), 305); +} + +/** + * @tc.name: RegisterSecurityComponentInner001 + * @tc.desc: Test register security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, RegisterSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + + ASSERT_EQ(stub_->RegisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteUint32(UNKNOWN_SC_TYPE); + ASSERT_EQ(stub_->RegisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_VALUE_INVALID); + + data.WriteUint32(MAX_SC_TYPE); + ASSERT_EQ(stub_->RegisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_VALUE_INVALID); + + data.WriteUint32(LOCATION_COMPONENT); + ASSERT_EQ(stub_->RegisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteUint32(LOCATION_COMPONENT); + data.WriteString(""); + ASSERT_EQ(stub_->RegisterSecurityComponentInner(data, reply), SC_OK); +} + +/** + * @tc.name: UpdateSecurityComponentInner001 + * @tc.desc: Test update security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, UpdateSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + + ASSERT_EQ(stub_->UpdateSecurityComponentInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(-1); + ASSERT_EQ(stub_->UpdateSecurityComponentInner(data, reply), SC_SERVICE_ERROR_VALUE_INVALID); + + data.WriteInt32(1); + ASSERT_EQ(stub_->UpdateSecurityComponentInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(1); + data.WriteString(""); + ASSERT_EQ(stub_->UpdateSecurityComponentInner(data, reply), SC_OK); +} + +/** + * @tc.name: UnregisterSecurityComponentInner001 + * @tc.desc: Test unregister security component + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, UnregisterSecurityComponentInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + ASSERT_EQ(stub_->UnregisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(-1); + ASSERT_EQ(stub_->UnregisterSecurityComponentInner(data, reply), SC_SERVICE_ERROR_VALUE_INVALID); + + data.WriteInt32(1); + ASSERT_EQ(stub_->UnregisterSecurityComponentInner(data, reply), SC_OK); +} + +/** + * @tc.name: ReportSecurityComponentClickEventInner001 + * @tc.desc: Test report click event + * @tc.type: FUNC + * @tc.require: AR000HO9J7 + */ +HWTEST_F(SecCompStubTest, ReportSecurityComponentClickEventInner001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + ASSERT_EQ(stub_->ReportSecurityComponentClickEventInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(-1); + ASSERT_EQ(stub_->ReportSecurityComponentClickEventInner(data, reply), SC_SERVICE_ERROR_VALUE_INVALID); + + data.WriteInt32(1); + ASSERT_EQ(stub_->ReportSecurityComponentClickEventInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(1); + data.WriteString(""); + ASSERT_EQ(stub_->ReportSecurityComponentClickEventInner(data, reply), SC_SERVICE_ERROR_PARCEL_OPERATE_FAIL); + + data.WriteInt32(1); + data.WriteString(""); + SecCompClickEvent touchInfo; + sptr parcel = new (std::nothrow) SecCompClickEventParcel(); + parcel->touchInfoParams_ = touchInfo; + data.WriteParcelable(parcel); + ASSERT_EQ(stub_->ReportSecurityComponentClickEventInner(data, reply), SC_OK); +} diff --git a/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h new file mode 100644 index 0000000000000000000000000000000000000000..e56866c8b0a4aff13d0935bb7cb250d51b4f3400 --- /dev/null +++ b/services/security_component_service/sa/test/unittest/src/sec_comp_stub_test.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 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. + */ + +#ifndef SEC_COMP_STUB_TEST_H +#define SEC_COMP_STUB_TEST_H + +#include +#define private public +#include "sec_comp_stub.h" +#undef private + +namespace OHOS { +namespace Security { +namespace SecurityComponent { + +// stub is abstract class +struct SecCompStubMock : public SecCompStub { +public: + int32_t RegisterSecurityComponent(SecCompType type, + const std::string& componentInfo, int32_t& scId) override + { + return 0; + }; + + int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo) override + { + return 0; + }; + + int32_t UnregisterSecurityComponent(int32_t scId) override + { + return 0; + }; + + int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, + const SecCompClickEvent& touchInfo, sptr callerToken) override + { + return 0; + }; + + bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId) override + { + return true; + } + + sptr GetEnhanceRemoteObject() override + { + return nullptr; + } +}; + +class SecCompStubTest : public testing::Test { +public: + static void SetUpTestCase(); + + static void TearDownTestCase(); + + void SetUp(); + + void TearDown(); + + sptr stub_ = nullptr; +}; +} // namespace SecurityComponent +} // namespace Security +} // namespace OHOS +#endif // SEC_COMP_STUB_TEST_H diff --git a/test/dts/README_zh.md b/test/dts/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..bd543706331391254da30b3776b65be88f3001ad --- /dev/null +++ b/test/dts/README_zh.md @@ -0,0 +1,47 @@ +# 安全控件管理服务 + +## 简介 + +安全控件是OpenHarmony提供的一组系统实现的ArkUI基础组件。当用户点击了这类组件后,应用将被授予临时授权,应用开发者仅需要像使用Button等组件那样集成到应用自己的页面即可。 +安全控件管理服务主要提供如下功能: + +- 提供应用安全控件的注册、临时授权、取消注册等Native接口实现。 +- 负责安全控件的合法性检查,只有合法的安全控件才能授权成功。 +- 提供其他SA查询临时授权的Native接口实现。提供安全增强相关接口及适配层,供厂商定制安全增强功能使用。 + +## 目录 + +``` +/base/security/security_component +├── frameworks # 框架层,基础功能代码存放目录 +│ ├── common # 框架公共代码存放目录 +│ ├── enhance_adapter # 能力增强适配代码存放目录 +│ └── security_component # 安全控件服务框架代码存放目录 +├── interfaces # 接口层 +│ └── inner_api # 内部接口层 +│ ├── enhance_kits # 安全控件配置接口代码存放目录 +│ └── security_component # 安全控件服务接口层代码存放目录 +└── services # 服务层 + └── security_component_service/sa + └── sa_main # 安全控件服务侧代码存放目录 + +``` + +## 使用 +### 接口说明 + +| **接口申明** | **接口描述** | +| --- | --- | +| int32_t RegisterSecurityComponent(SecCompType type, const std::string& componentInfo, int32_t& scId); | 注册安全控件 | +| int32_t UpdateSecurityComponent(int32_t scId, const std::string& componentInfo); | 更新安全控件信息 | +| int32_t UnregisterSecurityComponent(int32_t scId); | 取消注册安全控件 | +| int32_t ReportSecurityComponentClickEvent(int32_t scId, const std::string& componentInfo, const SecCompClickEvent& touchInfo); | 上报点击事件,申请临时授权 | +| int32_t SetEnhanceCfg(SecCompEnhanceCfgBase* cfg); | 设置安全控件增强的配置,供多模服务使用 | +| int32_t GetPointerEventEnhanceData(void* data, uint32_t dataLen, uint8_t* enhanceData, uint32_t& enHancedataLen); | 获取点击事件的安全增强数据,供多模服务使用 | +| bool ReduceAfterVerifySavePermission(AccessToken::AccessTokenID tokenId); | 校验后取消保存控件权限 | + +## 相关仓 + +**[arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine/blob/master/README_zh.md)** + +**[multimodalinput\_input](https://gitee.com/openharmony/multimodalinput_input/blob/master/README_zh.md)** diff --git a/test/dts/location_button.d.ts b/test/dts/location_button.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f0deafc0bfff7dd0aff9eddbdb271e90881c5f4 --- /dev/null +++ b/test/dts/location_button.d.ts @@ -0,0 +1,263 @@ +/* + * Copyright (c) 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. + */ + +/** + * Enumerates the icon styles. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum LocationIconStyle { + /** + * Icon filled with the specified color. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + FULL_FILLED = 0, + + /** + * Icon rendered as lines. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + LINES = 1 +} + +/** + * Enumerates the text that can be displayed on the location button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum LocationDescription { + /** + * Current Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + CURRENT_LOCATION = 0, + + /** + * Add Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + ADD_LOCATION = 1, + + /** + * Select Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SELECT_LOCATION = 2, + + /** + * Share Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SHARE_LOCATION = 3, + + /** + * Send Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SEND_LOCATION = 4, + + /** + * Locating + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + LOCATING = 5, + + /** + * Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + LOCATION = 6, + + /** + * Send Current Location + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SEND_CURRENT_LOCATION = 7, + + /** + * Relocation + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + RELOCATION = 8, + + /** + * Punch In + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + PUNCH_IN = 9, + + /** + * Current Position + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + CURRENT_POSITION = 10 +} + +/** + * Declares the interface for setting the location button options. + * + * @interface LocationButtonOptions + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare interface LocationButtonOptions { + /** + * Style of the icon to be drawn. + * + * @type { ?LocationIconStyle } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + icon?: LocationIconStyle; + + /** + * Text to be displayed on the button. + * + * @type { ?LocationDescription } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + text?: LocationDescription; + + /** + * Type of the button. + * + * @type { ?ButtonType } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + buttonType?: ButtonType; +} + +/** + * Enumerates the click event results of the location button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum LocationButtonOnClickResult { + /** + * Success. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SUCCESS = 0, + + /** + * Failure because the application is not temporarily authorized for accessing location data. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + TEMPORARY_AUTHORIZATION_FAILED = 1 +} + +/** + * Defines the interface for setting a location button. + * + * @interface LocationButtonInterface + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +interface LocationButtonInterface { + /** + * Creates a location button. + * + * @returns { LocationButtonAttribute } TReturns the attribute of the location button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (): LocationButtonAttribute; + + /** + * Creates a location button with the specified composition. + * If an attribute is not set, the corresponding element will not be drawn. + * + * @param { LocationButtonOptions } options - Indicates the options of the location button. + * @returns { LocationButtonAttribute } Returns the attribute of the location button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (options: LocationButtonOptions): LocationButtonAttribute; +} + +/** + * Defines the attributes of the location button. + * + * @extends SecurityComponentMethod + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare class LocationButtonAttribute extends SecurityComponentMethod { + /** + * Called when the location button is clicked. + * + * @param { (event: ClickEvent, result: LocationButtonOnClickResult) => void } event - Indicates the + * click event result. + * @returns { LocationButtonAttribute } Returns the attribute of the location button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + onClick(event: (event: ClickEvent, result: LocationButtonOnClickResult) => void): LocationButtonAttribute; +} + +/** + * Defines a button that interacts with the security component service to + * request the authorization for accessing location data. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const LocationButton: LocationButtonInterface; + +/** + * Defines a location button instance for secure access. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const LocationButtonInstance: LocationButtonAttribute; diff --git a/test/dts/paste_button.d.ts b/test/dts/paste_button.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..50c06eb9f5a3b11dd2800604c8e4ad3f104a8ce9 --- /dev/null +++ b/test/dts/paste_button.d.ts @@ -0,0 +1,175 @@ +/* + * Copyright (c) 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. + */ + +/** + * Enumerates the icon styles. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum PasteIconStyle { + /** + * Icon rendered as lines. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + LINES = 0 +} + +/** + * Enumerates the text that can be displayed on the paste button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum PasteDescription { + /** + * Paste + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + PASTE = 0 +} + +/** + * Declares the interface for setting the paste button options. + * + * @interface PasteButtonOptions + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare interface PasteButtonOptions { + /** + * Style of the icon to be drawn. + * + * @type { ?PasteIconStyle } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + icon?: PasteIconStyle; + + /** + * Text to be displayed on the button. + * + * @type { ?PasteDescription } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + text?: PasteDescription; + + /** + * Type of the button. + * + * @type { ?ButtonType } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + buttonType?: ButtonType; +} + +/** + * Enumerates the click event results of the paste button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum PasteButtonOnClickResult { + /** + * Success. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SUCCESS = 0, + + /** + * Failure because the application is not temporarily authorized for accessing the current pasteboard data. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + TEMPORARY_AUTHORIZATION_FAILED = 1 +} + +/** + * Defines the interface for setting a paste button. + * + * @interface PasteButtonInterface + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +interface PasteButtonInterface { + /** + * Creates a paste button. + * + * @returns { PasteButtonAttribute } Returns the attribute of the paste button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (): PasteButtonAttribute; + + /** + * Creates a paste button with the specified composition. + * If an attribute is not set, the corresponding element will not be drawn. + * + * @param { PasteButtonOptions } options - Indicates the options of the paste button. + * @returns { PasteButtonAttribute } Returns the attribute of the paste button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (options: PasteButtonOptions): PasteButtonAttribute; +} + +/** + * Defines the attributes of the paste button. + * + * @extends SecurityComponentMethod + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare class PasteButtonAttribute extends SecurityComponentMethod { + /** + * Called when the paste button is clicked. + * + * @param { (event: ClickEvent, result: PasteButtonOnClickResult) => void } event - Indicates the + * click event result. + * @returns { PasteButtonAttribute } Returns the attribute of the paste button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + onClick(event: (event: ClickEvent, result: PasteButtonOnClickResult) => void): PasteButtonAttribute; +} + +/** + * Defines a button that interacts with the security component service to + * request the permission for accessing the current pasteboard data. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const PasteButton: PasteButtonInterface; + +/** + * Defines a paste button instance for secure access. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const PasteButtonInstance: PasteButtonAttribute; diff --git a/test/dts/save_button.d.ts b/test/dts/save_button.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61addc9bb4b2cf798a9f5f005d5326c0640e6e4e --- /dev/null +++ b/test/dts/save_button.d.ts @@ -0,0 +1,239 @@ +/* + * Copyright (c) 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. + */ + +/** + * Enumerates the icon styles. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum SaveIconStyle { + /** + * Icon filled with the specified color. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + FULL_FILLED = 0, + + /** + * Icon rendered as lines. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + LINES = 1 +} + +/** + * Enumerates the text that can be displayed on the save button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum SaveDescription { + /** + * Download + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + DOWNLOAD = 0, + + /** + * Download File + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + DOWNLOAD_FILE = 1, + + /** + * Save + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SAVE = 2, + + /** + * Save Image + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SAVE_IMAGE = 3, + + /** + * Save File + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SAVE_FILE = 4, + + /** + * Download and Share + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + DOWNLOAD_AND_SHARE = 5, + + /** + * Receive + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + RECEIVE = 6, + + /** + * Continue to Receive + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + CONTINUE_TO_RECEIVE = 7 +} + +/** + * Declares the interface for setting the save button options. + * + * @interface SaveButtonOptions + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare interface SaveButtonOptions { + /** + * Style of the icon to be drawn. + * + * @type { ?SaveIconStyle } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + icon?: SaveIconStyle; + + /** + * Text to be displayed on the button. + * + * @type { ?SaveDescription } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + text?: SaveDescription; + + /** + * Type of the button. + * + * @type { ?ButtonType } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + buttonType?: ButtonType; +} + +/** + * Enumerates the click event results of the save button. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum SaveButtonOnClickResult { + /** + * Success. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + SUCCESS = 0, + + /** + * Failure because the application is not temporarily authorized for saving files. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + TEMPORARY_AUTHORIZATION_FAILED = 1 +} + +/** + * Defines the interface for setting a save button. + * + * @interface SaveButtonInterface + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +interface SaveButtonInterface { + /** + * Creates a save button. + * + * @returns { SaveButtonAttribute } Returns the attribute of the save button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (): SaveButtonAttribute; + + /** + * Creates a save button with the specified composition. + * If an attribute is not set, the corresponding element will not be drawn. + * + * @param { SaveButtonOptions } options - Indicates the options of the save button. + * @returns { SaveButtonAttribute } Returns the attribute of the save button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + (options: SaveButtonOptions): SaveButtonAttribute; +} + +/** + * Defines the attributes of the save button. + * + * @extends SecurityComponentMethod + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare class SaveButtonAttribute extends SecurityComponentMethod { + /** + * Called when the save button is clicked. + * + * @param { (event: ClickEvent, result: SaveButtonOnClickResult) => void } event - Indicates the + * click event result. + * @returns { SaveButtonAttribute } Returns the attribute of the save button. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + onClick(event: (event: ClickEvent, result: SaveButtonOnClickResult) => void): SaveButtonAttribute; +} + +/** + * Defines a button that interacts with the security component service to + * request the permission for saving files in the media library. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const SaveButton: SaveButtonInterface; + +/** + * Defines a save button instance for secure access. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare const SaveButtonInstance: SaveButtonAttribute; diff --git a/test/dts/security_component.d.ts b/test/dts/security_component.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cac844e59f174d373b7c3afa3a182c66badc10b --- /dev/null +++ b/test/dts/security_component.d.ts @@ -0,0 +1,242 @@ +/* + * Copyright (c) 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. + */ + +/** + * Enumerates the layout direction of the icon and text. + * + * @enum { number } + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare enum SecurityComponentLayoutDirection { + /** + * Horizontal layout. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + HORIZONTAL = 0, + + /** + * Vertical layout. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + VERTICAL = 1 +} + +/** + * Defines the method of a security component. + * + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ +declare class SecurityComponentMethod { + /** + * Icon size. + * + * @param { Dimension } value - Indicates the size of the icon. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + iconSize(value: Dimension): T; + + /** + * Layout direction of the icon and text. + * + * @param { SecurityComponentLayoutDirection } value - Indicates the layout direction of the icon and text. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + layoutDirection(value: SecurityComponentLayoutDirection): T; + + /** + * Position of the security component. + * + * @param { Position } value - Indicates the position of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + position(value: Position): T; + + /** + * Anchor of the security component for positioning. The top start edge of the component is used as + * the reference point for offset. + * + * @param { Position } value - Indicates the anchor of the component when it is positioned. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + markAnchor(value: Position): T; + + /** + * Coordinate offset relative to the layout position. + * Setting this attribute does not affect the layout of the parent container. + * The position is adjusted only during drawing. + * + * @param { Position } value - Indicates the offset value. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + offset(value: Position): T; + + /** + * Font size of the inner text. + * + * @param { Dimension } value - Indicates the font size of the text in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + fontSize(value: Dimension): T; + + /** + * Font style of the inner text. + * + * @param { FontStyle } value - Indicates the font style of the text in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + fontStyle(value: FontStyle): T; + + /** + * Font weight of the inner text. + * + * @param { number | FontWeight | string } value - Indicates the font weight of the text in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + fontWeight(value: number | FontWeight | string): T; + + /** + * Font family of the inner text. + * + * @param { string | Resource } value - Indicates the font family of the text in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + fontFamily(value: string | Resource): T; + + /** + * Font color of the inner text. + * + * @param { ResourceColor } value - Indicates the font color of the text in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + fontColor(value: ResourceColor): T; + + /** + * Color of the icon. + * + * @param { ResourceColor } value - Indicates the icon color in the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + iconColor(value: ResourceColor): T; + + /** + * Background color. + * + * @param { ResourceColor } value - Indicates the background color of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + backgroundColor(value: ResourceColor): T; + + /** + * Style of the border. + * + * @param { BorderStyle } value - Indicates the border style of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + borderStyle(value: BorderStyle): T; + + /** + * Width of the border. + * + * @param { Dimension } value - Indicates the border width of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + borderWidth(value: Dimension): T; + + /** + * Color of the border. + * + * @param { ResourceColor } value - Indicates the border color of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + borderColor(value: ResourceColor): T; + + /** + * Radius of the border. + * + * @param { Dimension } value - Indicates the border radius of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + borderRadius(value: Dimension): T; + + /** + * Padding between the background border and icon/inner text. + * + * @param { Padding | Dimension } value - Indicates the padding of the security component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + padding(value: Padding | Dimension): T; + + /** + * Space between the inner text and icon. + * + * @param { Dimension } value - Indicates the space between the inner text and icon. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @since 10 + */ + textIconSpace(value: Dimension): T; + + /** + * Key. User can set an key to the component to identify it. + * + * @param { string } value - identify the key of the component. + * @returns { T } Returns the attribute of the security component. + * @syscap SystemCapability.ArkUI.ArkUI.Full + * @systemapi + * @since 10 + * @test + */ + key(value: string): T; +} diff --git a/test/fuzztest/security_component/BUILD.gn b/test/fuzztest/security_component/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8d2c4335c3f86f0029883e67a5a31fcc1b1c5754 --- /dev/null +++ b/test/fuzztest/security_component/BUILD.gn @@ -0,0 +1,34 @@ +# Copyright (c) 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. + +group("fuzztest") { + testonly = true + deps = [] + + deps += [ + "getenhanceremoteobjectInner_fuzzer:GetEnhanceRemoteObjectInnerFuzzTest", + "getenhanceremoteobject_fuzzer:GetEnhanceRemoteObjectFuzzTest", + "getpointereventenhancedata_fuzzer:GetPointerEventEnhanceDataFuzzTest", + "reduceafterverifysavepermissionInner_fuzzer:ReduceAfterVerifySavePermissionInnerFuzzTest", + "reduceafterverifysavepermission_fuzzer:ReduceAfterVerifySavePermissionFuzzTest", + "registersecuritycomponentInner_fuzzer:RegisterSecurityComponentInnerFuzzTest", + "registersecuritycomponent_fuzzer:RegisterSecurityComponentFuzzTest", + "reportsecuritycomponentclickeventInner_fuzzer:ReportSecurityComponentClickEventInnerFuzzTest", + "reportsecuritycomponentclickevent_fuzzer:ReportSecurityComponentClickEventFuzzTest", + "setenhancecfg_fuzzer:SetEnhanceCfgFuzzTest", + "unregistersecuritycomponentInner_fuzzer:UnregisterSecurityComponentInnerFuzzTest", + "unregistersecuritycomponent_fuzzer:UnregisterSecurityComponentFuzzTest", + "updatesecuritycomponentInner_fuzzer:UpdateSecurityComponentInnerFuzzTest", + "updatesecuritycomponent_fuzzer:UpdateSecurityComponentFuzzTest", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..68d43fe44ff6503698e930fac87b974e12a9659f --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetEnhanceRemoteObjectInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getenhanceremoteobjectInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48d375e56a93311aa4d5061e5e4e6664b72bae80 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getenhanceremoteobjectInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetEnhanceRemoteObjectInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::GET_SECURITY_COMPONENT_ENHANCE_OBJECT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetEnhanceRemoteObjectInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a3ec5aaea653d36d5318f656ee77a9177c06579a --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/getenhanceremoteobjectInner_fuzzer.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GET_ENHANCE_REMOTE_OBJECT_INNER_FUZZER_H +#define GET_ENHANCE_REMOTE_OBJECT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_stub.h" +#include "sec_comp_service.h" + +#endif diff --git a/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobjectInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d0a5c65c17a5a6b2cfd862a49170a52f41831d70 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetEnhanceRemoteObjectFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getenhanceremoteobject_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getenhanceremoteobject_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47d929378e2b804496c1c30332ac5c6ea2267219 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getenhanceremoteobject_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetEnhanceRemoteObjectFuzzTest(const uint8_t *data, size_t size) +{ + bool isLoad = true; + SecCompKit::GetEnhanceRemoteObject(isLoad); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetEnhanceRemoteObjectFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a907797afc598a88856dcd1444e49c1510034694 --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/getenhanceremoteobject_fuzzer.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GET_ENHANCE_REMOTE_OBJECT_FUZZER_H +#define GET_ENHANCE_REMOTE_OBJECT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif diff --git a/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getenhanceremoteobject_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bca0c526a208a37a3c441bb55c9459fed0aab913 --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("GetPointerEventEnhanceDataFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/getpointereventenhancedata_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/enhance_kits/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "getpointereventenhancedata_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c894798b9c190deff1969bac1f979caed4b9112b --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "getpointereventenhancedata_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void GetPointerEventEnhanceDataFuzzTest(const uint8_t *data, size_t size) +{ + uint8_t *data1 = const_cast(data); + uint8_t enhanceData[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + uint32_t enhancedataLen = 10; + SecCompEnhanceKit::GetPointerEventEnhanceData(data1, size, enhanceData, enhancedataLen); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::GetPointerEventEnhanceDataFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..5d8ac757c41e1ad06bacad2317b869cdc9a810cd --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/getpointereventenhancedata_fuzzer.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GET_POINTER_EVENT_ENHANCE_DATA_FUZZER_H +#define GET_POINTER_EVENT_ENHANCE_DATA_FUZZER_H + +#define FUZZ_PROJECT_NAME "getpointereventenhancedata_fuzzer" + +#include "sec_comp_enhance_kit.h" + +#endif diff --git a/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/getpointereventenhancedata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ff5172ec390ea64fbe429c57ceafd0d5be29cb8f --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReduceAfterVerifySavePermissionInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reduceafterverifysavepermissionInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5afd4e1204b82cf950d315e66bc2b8e62ec95fd2 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.cpp @@ -0,0 +1,48 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reduceafterverifysavepermissionInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReduceAfterVerifySavePermissionInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::VERIFY_TEMP_SAVE_PERMISSION; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReduceAfterVerifySavePermissionInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..d17798de5c79ea13f3b8ed7ec30ab65d06037cb7 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermissionInner_fuzzer/reduceafterverifysavepermissionInner_fuzzer.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REDUCE_AFTER_VERIFY_SAVEPERMISSION_INNER_FUZZER_H +#define REDUCE_AFTER_VERIFY_SAVEPERMISSION_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_stub.h" +#include "sec_comp_service.h" + +#endif diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aec22dc6f63f11dfd9e2df2414fc8cf9eb3f4b8a --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReduceAfterVerifySavePermissionFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reduceafterverifysavepermission_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62a7c88eb90597e405e9be22c103d57e4332ee91 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.cpp @@ -0,0 +1,40 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reduceafterverifysavepermission_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReduceAfterVerifySavePermissionFuzzTest(const uint8_t *data, size_t size) +{ + SecCompKit::ReduceAfterVerifySavePermission(size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReduceAfterVerifySavePermissionFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..6d024ef8d358f57f1e81d13a7ad4ba841ce6c568 --- /dev/null +++ b/test/fuzztest/security_component/reduceafterverifysavepermission_fuzzer/reduceafterverifysavepermission_fuzzer.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REDUCE_AFTER_VERIFY_SAVEPERMISSION_FUZZER_H +#define REDUCE_AFTER_VERIFY_SAVEPERMISSION_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif // TEST_FUZZTEST_SECURITY_COMPONENT_FUZZER_H diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3e81ae7618698e22339845259142ba0f7f6692f9 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("RegisterSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "registersecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24385f9d8e981b516ebf272e5804984f3d0b3328 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,51 @@ +/* + * 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 +#include +#include +#include +#include "registersecuritycomponentInner_fuzzer.h" +#include "accesstoken_kit.h" +#include "sec_comp_service.h" +#include "securec.h" +#include "token_setproc.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void RegisterSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = + SecurityComponentServiceInterfaceCode::REGISTER_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = + std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::RegisterSecurityComponentInnerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a8ada33ca5202605ee006fbb1bc54ef0a24fb4d6 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponentInner_fuzzer/registersecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REGISTER_SECURITY_COMPONENT_INNER_FUZZER_H +#define REGISTER_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..68f586d0d1a65f841fe6abda64e6b8e1d942de6a --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("RegisterSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/registersecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + "//third_party/json/test/thirdparty/fifo_map", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "registersecuritycomponent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea9d2753d2e0d1ca0e8ea7d7ce587c9ad92cf729 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "registersecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void RegisterSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + std::string componentInfo(reinterpret_cast(data), size); + int32_t scId = size; + enum SecCompType type = UNKNOWN_SC_TYPE; + SecCompKit::RegisterSecurityComponent(type, componentInfo, scId); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::RegisterSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..667b5925c6e6dbf87ca0eca15a4c3aba34c69d27 --- /dev/null +++ b/test/fuzztest/security_component/registersecuritycomponent_fuzzer/registersecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REGISTER_SECURITY_COMPONENT_FUZZER_H +#define REGISTER_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fa374fa989a1783a1c43d3119d553e8f73133243 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReportSecurityComponentClickEventInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reportsecuritycomponentclickeventInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cea50866d887a0f3368a56c6b7f6b4ae21c1635 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "reportsecuritycomponentclickeventInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReportSecurityComponentClickEventInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::REPORT_SECURITY_COMPONENT_CLICK_EVENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReportSecurityComponentClickEventInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..8af2a89541d9a6834b758fc0bdc21a9b00e26622 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickeventInner_fuzzer/reportsecuritycomponentclickeventInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REPORT_SECURITY_COMPONENT_CLICK_EVENT_INNER_FUZZER_H +#define REPORT_SECURITY_COMPONENT_CLICK_EVENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1ac949d7c2233da9e7fae24fa9c0ed1d6a868d1c --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("ReportSecurityComponentClickEventFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + "//third_party/json/include", + "//third_party/json/test/thirdparty/fifo_map", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "reportsecuritycomponentclickevent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89477c3af681f53de2606f72f43c5ee367d72cd9 --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.cpp @@ -0,0 +1,51 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "reportsecuritycomponentclickevent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void ReportSecurityComponentClickEventFuzzTest(const uint8_t *data, size_t size) +{ + std::string componentInfo(reinterpret_cast(data), size); + uint8_t *data1 = const_cast(data); + const double touchX = size; + const double touchY = size; + const uint64_t timesStamp = size; + struct SecCompClickEvent touchInfo; + touchInfo.touchX = touchX; + touchInfo.touchY = touchY; + touchInfo.timestamp = timesStamp; + touchInfo.extraInfo.data = data1; + touchInfo.extraInfo.dataSize = size; + SecCompKit::ReportSecurityComponentClickEvent(size, componentInfo, touchInfo); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::ReportSecurityComponentClickEventFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..989ec28ef896a09708630e0d6b05fe4f10a25eff --- /dev/null +++ b/test/fuzztest/security_component/reportsecuritycomponentclickevent_fuzzer/reportsecuritycomponentclickevent_fuzzer.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef REPORT_SECURITY_COMPONENT_CLICK_EVENT_FUZZER_H +#define REPORT_SECURITY_COMPONENT_CLICK_EVENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" + +#include "sec_comp_kit.h" + +#endif diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn b/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c7a950f93943331689e8b12c5c50e8af7d828d2f --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("SetEnhanceCfgFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${sec_comp_dir}/test/fuzztest/security_component/setenhancecfg_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/enhance_kits/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "setenhancecfg_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/enhance_kits:libsecurity_component_enhance_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init b/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml b/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be86e485bd5290118d0ff3919b6a2d025e374f9d --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "setenhancecfg_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void SetEnhanceCfgFuzzTest(const uint8_t *data, size_t size) +{ + uint8_t *cfg = const_cast(data); + SecCompEnhanceKit::SetEnhanceCfg(cfg, size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::SetEnhanceCfgFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..47d46f126e9fb2ff55ca30e75745c5004954f54d --- /dev/null +++ b/test/fuzztest/security_component/setenhancecfg_fuzzer/setenhancecfg_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SETENHANCE_CFG_FUZZER_H +#define SETENHANCE_CFG_FUZZER_H + +#define FUZZ_PROJECT_NAME "setenhancecfg_fuzzer" +#include "sec_comp_enhance_kit.h" +#endif diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..02f554eccc6ba019266d7689d61e851b49e1c8b2 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UnregisterSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "unregistersecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8eddb37a6946477d65e6cbf79a94e489a37e8b2f --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "unregistersecuritycomponentInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UnregisterSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::UNREGISTER_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UnregisterSecurityComponentInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..02a5307ec877556820a75c99eac14d98ff30cf0f --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponentInner_fuzzer/unregistersecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UNREGISTER_SECURITY_COMPONENT_INNER_FUZZER_H +#define UNREGISTER_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2afbc272f29e40ce4434fd8d5d1745f9ad7e9902 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UnregisterSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/interfaces/inner_api/security_component/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "unregistersecuritycomponent_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk" ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3219fb3fc111003a563fcf849132c5db2d00bf9c --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.cpp @@ -0,0 +1,40 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "unregistersecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UnregisterSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + SecCompKit::UnregisterSecurityComponent(size); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UnregisterSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..794af54033ff861e656ec5cb3d2953ded5e0213a --- /dev/null +++ b/test/fuzztest/security_component/unregistersecuritycomponent_fuzzer/unregistersecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UNREGISTER_SECURITY_COMPONENT_FUZZER_H +#define UNREGISTER_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..061dcc7612c13dfca5cc3586863a2b90e7254f14 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UpdateSecurityComponentInnerFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "updatesecuritycomponentInner_fuzzer.cpp" ] + + deps = [ "${sec_comp_dir}/services/security_component_service/sa:security_component_service" ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f1ab9fc6ad74a5604b27d450fab21d9c2bf24ca --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.cpp @@ -0,0 +1,49 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "sec_comp_service.h" +#include "updatesecuritycomponentInner_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UpdateSecurityComponentInnerFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t code = SecurityComponentServiceInterfaceCode::UPDATE_SECURITY_COMPONENT; + MessageParcel datas; + datas.WriteInterfaceToken(u"ohos.security.ISecCompService"); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + auto service = std::make_shared(SA_ID_SECURITY_COMPONENT_SERVICE, true); + service->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UpdateSecurityComponentInnerFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..2d2559048b020f2691e644aa264d2dc56fb064c6 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponentInner_fuzzer/updatesecuritycomponentInner_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UPDATE_SECURITY_COMPONENT_INNER_FUZZER_H +#define UPDATE_SECURITY_COMPONENT_INNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_stub.h" +#endif diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0e675b23ac98bc6c6e092cf4a4d77ed0869bf676 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../../security_component.gni") + +module_output_path = "security_component/security_component" + +ohos_fuzztest("UpdateSecurityComponentFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${sec_comp_dir}/test/fuzztest/security_component/updatesecuritycomponent_fuzzer" + + include_dirs = [ + "${sec_comp_dir}/frameworks/common/include", + "${sec_comp_dir}/services/security_component_service/sa/sa_main", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [ "${sec_comp_dir}/config:coverage_flags" ] + + cflags_cc = [ "-DHILOG_ENABLE" ] + sources = [ "updatesecuritycomponent_fuzzer.cpp" ] + + deps = [ + "${sec_comp_dir}/interfaces/inner_api/security_component:libsecurity_component_sdk", + "${sec_comp_dir}/services/security_component_service/sa:security_component_service", + ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..bc977bd9738ee9a70b362067f57a9c63d3adb801 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# 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. + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a15493c09fcc72fc7410e5628983f87b33d9f41 --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.cpp @@ -0,0 +1,41 @@ +/* + * 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 +#include +#include +#include +#include "accesstoken_kit.h" +#include "securec.h" +#include "token_setproc.h" +#include "updatesecuritycomponent_fuzzer.h" + +using namespace OHOS::Security::SecurityComponent; +using namespace OHOS::Security::AccessToken; +namespace OHOS { +static void UpdateSecurityComponentFuzzTest(const uint8_t *data, size_t size) +{ + std::string str(reinterpret_cast(data), size); + SecCompKit::UpdateSecurityComponent(size, str); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::UpdateSecurityComponentFuzzTest(data, size); + return 0; +} diff --git a/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..85f7f166a82a7daabc347bcfa3b1a4af785aae4e --- /dev/null +++ b/test/fuzztest/security_component/updatesecuritycomponent_fuzzer/updatesecuritycomponent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UPDATE_SECURITY_COMPONENT_FUZZER_H +#define UPDATE_SECURITY_COMPONENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "securitycomponent_fuzzer" +#include "sec_comp_kit.h" +#endif diff --git a/test/security_component/AppScope/app.json b/test/security_component/AppScope/app.json new file mode 100644 index 0000000000000000000000000000000000000000..bbf7eccf17bd8e0cad21558178d9eb4b2db8b0cf --- /dev/null +++ b/test/security_component/AppScope/app.json @@ -0,0 +1,21 @@ +{ + "app": { + "bundleName": "com.example.securitycomponent", + "vendor": "huawei", + "versionCode": 1000000, + "versionName": "1.0.0", + "debug": false, + "icon": "$media:icon", + "label": "$string:app_name", + "description": "$string:description_application", + "distributedNotificationEnabled": true, + "keepAlive": true, + "singleUser": true, + "minAPIVersion": 10, + "targetAPIVersion": 10, + "car": { + "apiCompatibleVersion": 10, + "singleUser": false + } + } +} \ No newline at end of file diff --git a/test/security_component/AppScope/resources/base/element/string.json b/test/security_component/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..633100a6d90763bfac9d20aaae683119d7320e9c --- /dev/null +++ b/test/security_component/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string":[ + { + "name":"app_name", + "value":"ohosProject" + } + ] +} \ No newline at end of file diff --git a/test/security_component/AppScope/resources/base/media/app_icon.png b/test/security_component/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/test/security_component/AppScope/resources/base/media/app_icon.png differ diff --git a/test/security_component/BUILD.gn b/test/security_component/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a1a2d698b86aa0e63b4286d0db956ca9b980db2d --- /dev/null +++ b/test/security_component/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 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("//test/xts/tools/build/suite.gni") + +ohos_js_hap_suite("ActsSecComponentTest") { + hap_profile = "entry/src/main/module.json" + js_build_mode = "debug" + deps = [ + ":security_component_assets", + ":security_component_resources", + ] + ets2abc = true + certificate_profile = "signature/openharmony_sx.p7b" + hap_name = "ActsSecComponentTest" + subsystem_name = "security" + part_name = "access_token" +} + +ohos_app_scope("security_app_profile") { + app_profile = "AppScope/app.json" + sources = [ "AppScope/resources" ] +} +ohos_js_assets("security_component_assets") { + source_dir = "entry/src/main/ets" +} +ohos_resources("security_component_resources") { + sources = [ "entry/src/main/resources" ] + deps = [ ":security_app_profile" ] + hap_profile = "entry/src/main/module.json" +} diff --git a/test/security_component/Test.json b/test/security_component/Test.json new file mode 100644 index 0000000000000000000000000000000000000000..c6f2985fba59fb576c6cef756b8f615362cb617f --- /dev/null +++ b/test/security_component/Test.json @@ -0,0 +1,20 @@ +{ + "description": "Configuration for hjunit demo Tests", + "driver": { + "type": "OHJSUnitTest", + "test-timeout": "1200000", + "bundle-name": "com.example.securitycomponent", + "module-name": "phone", + "shell-timeout": "1200000", + "testcase-timeout": "180000" + }, + "kits": [ + { + "test-file-name": [ + "ActsSecComponentTest.hap" + ], + "type": "AppInstallKit", + "cleanup-apps": true + } + ] +} diff --git a/test/security_component/entry/src/main/ets/Application/AbilityStage.ts b/test/security_component/entry/src/main/ets/Application/AbilityStage.ts new file mode 100644 index 0000000000000000000000000000000000000000..e86b53ef3a883a615d98994b39ec736482ba2cf7 --- /dev/null +++ b/test/security_component/entry/src/main/ets/Application/AbilityStage.ts @@ -0,0 +1,9 @@ +import AbilityStage from "@ohos.app.ability.AbilityStage" + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("[Demo] MyAbilityStage onCreate") + globalThis.stageOnCreateRun = 1; + globalThis.stageContext = this.context; + } +} diff --git a/test/security_component/entry/src/main/ets/MainAbility/MainAbility.ts b/test/security_component/entry/src/main/ets/MainAbility/MainAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..ced3a8306a1d434790a6c8802fde12f8f683383b --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/MainAbility.ts @@ -0,0 +1,37 @@ +import Ability from '@ohos.app.ability.UIAbility' + +export default class MainAbility extends Ability { + onCreate(want,launchParam){ + // Ability is creating, initialize resources for this ability + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + } + + onDestroy() { + // Ability is destroying, release resources for this ability + console.log("[Demo] MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] MainAbility onWindowStageCreate windowStage="+ windowStage) + globalThis.windowStage = windowStage + globalThis.abilityContext = this.context + windowStage.setUIContent(this.context, "MainAbility/pages/index/index", null) + } + + onWindowStageDestroy() { + //Main window is destroyed, release UI related resources + console.log("[Demo] MainAbility onWindowStageDestroy") + } + + onForeground() { + // Ability has brought to foreground + console.log("[Demo] MainAbility onForeground") + } + + onBackground() { + // Ability has back to background + console.log("[Demo] MainAbility onBackground") + } +}; \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/index/index.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/index/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..17615a7525b220d2e0e683d1bd7eff5b08ca1d60 --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/index/index.ets @@ -0,0 +1,56 @@ +/* + * Copyright (c) 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 router from '@ohos.router'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import { Hypium } from '@ohos/hypium' +import testsuite from '../../../test/List.test' + + +@Entry +@Component +struct Index { + + aboutToAppear(){ + console.info("start run testcase!!!!") + var abilityDelegator: any + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var abilityDelegatorArguments: any + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + console.info('start run testcase!!!') + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + build() { + Flex({ direction:FlexDirection.Column, alignItems:ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('SecButton Test') + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + + }) + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton.ets new file mode 100644 index 0000000000000000000000000000000000000000..ef207ffc2a6c157005d881b0abc8a7e298dda374 --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton.ets @@ -0,0 +1,241 @@ +/** + * Copyright (c) 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 events_emitter from '@ohos.events.emitter' + +@Entry +@Component +struct locationButton { + @State bgType: ButtonType = ButtonType.Normal + @State iconSize: number = 16 + @State direct: SecurityComponentLayoutDirection = 0 + @State positionX: number = 0 + @State positionY: number = 0 + @State anchorX: number = 0 + @State anchorY: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State fontSize: number = 16 + @State fontStyle: FontStyle = FontStyle.Normal + @State fontWeight: FontWeight = FontWeight.Medium + @State fontFamily: string = 'HarmonyOS Sans' + @State fontColor: number = 0xffffffff + @State iconColor: number = 0xffffffff + @State bgColor: number = 0xff007dff + @State borderSty: BorderStyle = BorderStyle.Dashed + @State borderWid: number = 0 + @State borderCol: number = 0xffffffff + @State borderRad: number = 0 + @State left: number = 24 + @State right: number = 24 + @State top: number = 8 + @State bottom: number = 8 + @State middle: number = 4 + @State clipSet: boolean = false + @State columnWidth: string = '100%' + @State columnHeight: string = '100%' + private stateChangeCallBack = (eventData) => { + if (eventData != null) { + console.debug("====>page_locationButton page state change called:" + JSON.stringify(eventData)); + if (eventData.data.bgType != null) { + this.bgType = eventData.data.bgType; + } + if (eventData.data.iconSize != null) { + this.iconSize = eventData.data.iconSize; + } + if (eventData.data.direct != null) { + this.direct = eventData.data.direct; + } + if (eventData.data.positionX != null) { + this.positionX = eventData.data.positionX; + } + if (eventData.data.positionY != null) { + this.positionY = eventData.data.positionY; + } + if (eventData.data.anchorX != null) { + this.anchorX = eventData.data.anchorX; + } + if (eventData.data.anchorY != null) { + this.anchorY = eventData.data.anchorY; + } + if (eventData.data.offsetX != null) { + this.offsetX = eventData.data.offsetX; + } + if (eventData.data.offsetY != null) { + this.offsetY = eventData.data.offsetY; + } + if (eventData.data.fontSize != null) { + this.fontSize = eventData.data.fontSize; + } + if (eventData.data.fontStyle != null) { + this.fontStyle = eventData.data.fontStyle; + } + if (eventData.data.fontWeight != null) { + this.fontWeight = eventData.data.fontWeight; + } + if (eventData.data.fontFamily != null) { + this.fontFamily = eventData.data.fontFamily; + } + if (eventData.data.fontColor != null) { + this.fontColor = eventData.data.fontColor; + } + if (eventData.data.iconColor != null) { + this.iconColor = eventData.data.iconColor; + } + if (eventData.data.bgColor != null) { + this.bgColor = eventData.data.bgColor; + } + if (eventData.data.borderSty != null) { + this.borderSty = eventData.data.borderSty; + } + if (eventData.data.borderWid != null) { + this.borderWid = eventData.data.borderWid; + } + if (eventData.data.borderCol != null) { + this.borderCol = eventData.data.borderCol; + } + if (eventData.data.borderRad != null) { + this.borderRad = eventData.data.borderRad; + } + if (eventData.data.left != null) { + this.left = eventData.data.left; + } + if (eventData.data.right != null) { + this.right = eventData.data.right; + } + if (eventData.data.top != null) { + this.top = eventData.data.top; + } + if (eventData.data.bottom != null) { + this.bottom = eventData.data.bottom; + } + if (eventData.data.middle != null) { + this.middle = eventData.data.middle; + } + if (eventData.data.clipSet != null) { + this.clipSet = eventData.data.clipSet; + } + if (eventData.data.columnWidth != null) { + this.columnWidth = eventData.data.columnWidth; + } + if (eventData.data.columnHeight != null) { + this.columnHeight = eventData.data.columnHeight; + } + } + } + + onPageShow() { + console.debug('====>page_locationButton page show called'); + var stateChangeEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + events_emitter.on(stateChangeEvent, this.stateChangeCallBack); + } + + onPageHide() { + console.debug('====>page_locationButton page hide called'); + events_emitter.off(1); + } + + build() { + Row() { + Column() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.CURRENT_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_locationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_locationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .position({ x: this.positionX, y: this.positionY }) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation") + Button() { + Text('--------------------') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 200, + bottom:60 + }).backgroundColor('#00000000') + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.CURRENT_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation1") + }.width(this.columnWidth).height(this.columnHeight).clip(this.clipSet) + }.height('100%') + } +} diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton_1.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton_1.ets new file mode 100644 index 0000000000000000000000000000000000000000..9fe207ca42dd9a1f393fb077a84ee12b3cbe75b5 --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/locationButton_1.ets @@ -0,0 +1,432 @@ +/** + * Copyright (c) 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 events_emitter from '@ohos.events.emitter' + +@Entry +@Component +struct locationButton_1 { + @State bgType: ButtonType = ButtonType.Normal + @State iconSize: number = 16 + @State positionX: number = 0 + @State positionY: number = 0 + @State anchorX: number = 0 + @State anchorY: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State fontSize: number = 16 + @State fontStyle: FontStyle = FontStyle.Normal + @State fontWeight: FontWeight = FontWeight.Medium + @State fontFamily: string = 'HarmonyOS Sans' + @State fontColor: number = 0xffffffff + @State iconColor: number = 0xffffffff + @State bgColor: number = 0x7dff + @State borderSty: BorderStyle = BorderStyle.Dashed + @State borderWid: number = 0 + @State borderCol: number = 0xffffffff + @State borderRad: number = 0 + @State left: number = 24 + @State right: number = 24 + @State top: number = 8 + @State bottom: number = 8 + @State middle: number = 4 + @State heightValue: number = 4 + marginValue = {top:30, bottom:30, left:10, right:10} + + build() { + Column() { + Row() { + LocationButton({ icon: LocationIconStyle.LINES, text: LocationDescription.ADD_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation2") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.SELECT_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.VERTICAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation3") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.SHARE_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation4") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.SEND_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation5") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.LOCATING, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation6") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation7") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.SEND_CURRENT_LOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation8") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.RELOCATION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation9") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.PUNCH_IN, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation10") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + LocationButton({ icon: LocationIconStyle.FULL_FILLED, text: LocationDescription.CURRENT_POSITION, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: LocationButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_LocationButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_LocationButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyLocation11") + }.width('100%').height(this.heightValue).margin(this.marginValue) + } + } +} diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/pasteButton.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/pasteButton.ets new file mode 100644 index 0000000000000000000000000000000000000000..dc8e31964fa0bed3ddcd01cb2c02067865836471 --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/pasteButton.ets @@ -0,0 +1,241 @@ +/** + * Copyright (c) 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 events_emitter from '@ohos.events.emitter' + +@Entry +@Component +struct pasteButton { + @State bgType: ButtonType = ButtonType.Normal + @State iconSize: number = 16 + @State direct: SecurityComponentLayoutDirection = 0 + @State positionX: number = 0 + @State positionY: number = 0 + @State anchorX: number = 0 + @State anchorY: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State fontSize: number = 16 + @State fontStyle: FontStyle = FontStyle.Normal + @State fontWeight: FontWeight = FontWeight.Medium + @State fontFamily: string = 'HarmonyOS Sans' + @State fontColor: number = 0xffffffff + @State iconColor: number = 0xffffffff + @State bgColor: number = 0xff007dff + @State borderSty: BorderStyle = BorderStyle.Dashed + @State borderWid: number = 0 + @State borderCol: number = 0xffffffff + @State borderRad: number = 0 + @State left: number = 24 + @State right: number = 24 + @State top: number = 8 + @State bottom: number = 8 + @State middle: number = 4 + @State clipSet: boolean = false + @State columnWidth: string = '100%' + @State columnHeight: string = '100%' + private stateChangeCallBack = (eventData) => { + if (eventData != null) { + console.debug("====>page_pasteButton page state change called:" + JSON.stringify(eventData)); + if (eventData.data.bgType != null) { + this.bgType = eventData.data.bgType; + } + if (eventData.data.iconSize != null) { + this.iconSize = eventData.data.iconSize; + } + if (eventData.data.direct != null) { + this.direct = eventData.data.direct; + } + if (eventData.data.positionX != null) { + this.positionX = eventData.data.positionX; + } + if (eventData.data.positionY != null) { + this.positionY = eventData.data.positionY; + } + if (eventData.data.anchorX != null) { + this.anchorX = eventData.data.anchorX; + } + if (eventData.data.anchorY != null) { + this.anchorY = eventData.data.anchorY; + } + if (eventData.data.offsetX != null) { + this.offsetX = eventData.data.offsetX; + } + if (eventData.data.offsetY != null) { + this.offsetY = eventData.data.offsetY; + } + if (eventData.data.fontSize != null) { + this.fontSize = eventData.data.fontSize; + } + if (eventData.data.fontStyle != null) { + this.fontStyle = eventData.data.fontStyle; + } + if (eventData.data.fontWeight != null) { + this.fontWeight = eventData.data.fontWeight; + } + if (eventData.data.fontFamily != null) { + this.fontFamily = eventData.data.fontFamily; + } + if (eventData.data.fontColor != null) { + this.fontColor = eventData.data.fontColor; + } + if (eventData.data.iconColor != null) { + this.iconColor = eventData.data.iconColor; + } + if (eventData.data.bgColor != null) { + this.bgColor = eventData.data.bgColor; + } + if (eventData.data.borderSty != null) { + this.borderSty = eventData.data.borderSty; + } + if (eventData.data.borderWid != null) { + this.borderWid = eventData.data.borderWid; + } + if (eventData.data.borderCol != null) { + this.borderCol = eventData.data.borderCol; + } + if (eventData.data.borderRad != null) { + this.borderRad = eventData.data.borderRad; + } + if (eventData.data.left != null) { + this.left = eventData.data.left; + } + if (eventData.data.right != null) { + this.right = eventData.data.right; + } + if (eventData.data.top != null) { + this.top = eventData.data.top; + } + if (eventData.data.bottom != null) { + this.bottom = eventData.data.bottom; + } + if (eventData.data.middle != null) { + this.middle = eventData.data.middle; + } + if (eventData.data.clipSet != null) { + this.clipSet = eventData.data.clipSet; + } + if (eventData.data.columnWidth != null) { + this.columnWidth = eventData.data.columnWidth; + } + if (eventData.data.columnHeight != null) { + this.columnHeight = eventData.data.columnHeight; + } + } + } + + onPageShow() { + console.debug('====>page_pasteButton page show called'); + var stateChangeEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + events_emitter.on(stateChangeEvent, this.stateChangeCallBack); + } + + onPageHide() { + console.debug('====>page_pasteButton page hide called'); + events_emitter.off(1); + } + + build() { + Row() { + Column() { + PasteButton({ icon: PasteIconStyle.LINES, text: PasteDescription.PASTE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: PasteButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_pasteButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_pasteButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .position({ x: this.positionX, y: this.positionY }) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyPaste") + Button() { + Text('--------------------') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 200, + bottom:60 + }).backgroundColor('#00000000') + PasteButton({ icon: PasteIconStyle.LINES, text: PasteDescription.PASTE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: PasteButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_pasteButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_pasteButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keyPaste1") + }.width(this.columnWidth).height(this.columnHeight).clip(this.clipSet) + }.height('100%') + } +} diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton.ets new file mode 100644 index 0000000000000000000000000000000000000000..4660b6736b69d717f109cabc683e5d8c4b3ccad8 --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton.ets @@ -0,0 +1,241 @@ +/** + * Copyright (c) 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 events_emitter from '@ohos.events.emitter' + +@Entry +@Component +struct saveButton { + @State bgType: ButtonType = ButtonType.Normal + @State iconSize: number = 16 + @State direct: SecurityComponentLayoutDirection = 0 + @State positionX: number = 0 + @State positionY: number = 0 + @State anchorX: number = 0 + @State anchorY: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State fontSize: number = 16 + @State fontStyle: FontStyle = FontStyle.Normal + @State fontWeight: FontWeight = FontWeight.Medium + @State fontFamily: string = 'HarmonyOS Sans' + @State fontColor: number = 0xffffffff + @State iconColor: number = 0xffffffff + @State bgColor: number = 0xff007dff + @State borderSty: BorderStyle = BorderStyle.Dashed + @State borderWid: number = 0 + @State borderCol: number = 0xffffffff + @State borderRad: number = 0 + @State left: number = 24 + @State right: number = 24 + @State top: number = 8 + @State bottom: number = 8 + @State middle: number = 4 + @State clipSet: boolean = false + @State columnWidth: string = '100%' + @State columnHeight: string = '100%' + private stateChangeCallBack = (eventData) => { + if (eventData != null) { + console.debug("====>page_saveButton page state change called:" + JSON.stringify(eventData)); + if (eventData.data.bgType != null) { + this.bgType = eventData.data.bgType; + } + if (eventData.data.iconSize != null) { + this.iconSize = eventData.data.iconSize; + } + if (eventData.data.direct != null) { + this.direct = eventData.data.direct; + } + if (eventData.data.positionX != null) { + this.positionX = eventData.data.positionX; + } + if (eventData.data.positionY != null) { + this.positionY = eventData.data.positionY; + } + if (eventData.data.anchorX != null) { + this.anchorX = eventData.data.anchorX; + } + if (eventData.data.anchorY != null) { + this.anchorY = eventData.data.anchorY; + } + if (eventData.data.offsetX != null) { + this.offsetX = eventData.data.offsetX; + } + if (eventData.data.offsetY != null) { + this.offsetY = eventData.data.offsetY; + } + if (eventData.data.fontSize != null) { + this.fontSize = eventData.data.fontSize; + } + if (eventData.data.fontStyle != null) { + this.fontStyle = eventData.data.fontStyle; + } + if (eventData.data.fontWeight != null) { + this.fontWeight = eventData.data.fontWeight; + } + if (eventData.data.fontFamily != null) { + this.fontFamily = eventData.data.fontFamily; + } + if (eventData.data.fontColor != null) { + this.fontColor = eventData.data.fontColor; + } + if (eventData.data.iconColor != null) { + this.iconColor = eventData.data.iconColor; + } + if (eventData.data.bgColor != null) { + this.bgColor = eventData.data.bgColor; + } + if (eventData.data.borderSty != null) { + this.borderSty = eventData.data.borderSty; + } + if (eventData.data.borderWid != null) { + this.borderWid = eventData.data.borderWid; + } + if (eventData.data.borderCol != null) { + this.borderCol = eventData.data.borderCol; + } + if (eventData.data.borderRad != null) { + this.borderRad = eventData.data.borderRad; + } + if (eventData.data.left != null) { + this.left = eventData.data.left; + } + if (eventData.data.right != null) { + this.right = eventData.data.right; + } + if (eventData.data.top != null) { + this.top = eventData.data.top; + } + if (eventData.data.bottom != null) { + this.bottom = eventData.data.bottom; + } + if (eventData.data.middle != null) { + this.middle = eventData.data.middle; + } + if (eventData.data.clipSet != null) { + this.clipSet = eventData.data.clipSet; + } + if (eventData.data.columnWidth != null) { + this.columnWidth = eventData.data.columnWidth; + } + if (eventData.data.columnHeight != null) { + this.columnHeight = eventData.data.columnHeight; + } + } + } + + onPageShow() { + console.debug('====>page_saveButton page show called'); + var stateChangeEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + events_emitter.on(stateChangeEvent, this.stateChangeCallBack); + } + + onPageHide() { + console.debug('====>page_saveButton page hide called'); + events_emitter.off(1); + } + + build() { + Row() { + Column() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.DOWNLOAD, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_saveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_saveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .position({ x: this.positionX, y: this.positionY }) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave") + Button() { + Text('--------------------') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 200, + bottom:60 + }).backgroundColor('#00000000') + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.DOWNLOAD, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_saveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_saveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(this.direct) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: this.offsetY }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor(this.fontColor) + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave1") + }.width(this.columnWidth).height(this.columnHeight).clip(this.clipSet) + }.height('100%') + } +} diff --git a/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton_1.ets b/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton_1.ets new file mode 100644 index 0000000000000000000000000000000000000000..7414dbdebf521aee87eb1321a700c3faaa8ca22e --- /dev/null +++ b/test/security_component/entry/src/main/ets/MainAbility/pages/saveButton_1.ets @@ -0,0 +1,320 @@ +/** + * Copyright (c) 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 events_emitter from '@ohos.events.emitter' + +@Entry +@Component +struct saveButton_1 { + @State icon: SaveIconStyle = 0 + @State textType: SaveDescription = 0 + @State bgType: ButtonType = ButtonType.Normal + @State iconSize: number = 16 + @State positionX: number = 0 + @State positionY: number = 0 + @State anchorX: number = 0 + @State anchorY: number = 0 + @State offsetX: number = 0 + @State offsetY: number = 0 + @State fontSize: number = 16 + @State fontStyle: FontStyle = FontStyle.Normal + @State fontWeight: FontWeight = FontWeight.Medium + @State fontFamily: string = 'HarmonyOS Sans' + @State fontColor: number = 0xffffffff + @State iconColor: number = 0xffffffff + @State bgColor: number = 0x7dff + @State borderSty: BorderStyle = BorderStyle.Dashed + @State borderWid: number = 0 + @State borderCol: number = 0xffffffff + @State borderRad: number = 0 + @State left: number = 24 + @State right: number = 24 + @State top: number = 8 + @State bottom: number = 8 + @State middle: number = 4 + @State heightValue: number = 4 + marginValue = {top:30, bottom:30, left:10, right:10} + + build() { + Column() { + Row() { + SaveButton({ icon: SaveIconStyle.LINES, text: SaveDescription.DOWNLOAD_FILE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave2") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.VERTICAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave3") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE_IMAGE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave4") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE_FILE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave5") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.DOWNLOAD_AND_SHARE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave6") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.RECEIVE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave7") + }.width('100%').height(this.heightValue).margin(this.marginValue) + Row() { + SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.CONTINUE_TO_RECEIVE, buttonType: this.bgType }) + .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => { + try { + var clickData = { + data: { + "clickResult": result, + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>page_SaveButton onclick result:" + JSON.stringify(result)) + events_emitter.emit(clickEvent, clickData) + } catch (err) { + console.debug("====>page_SaveButton emit action state err: " + JSON.stringify(err.message)) + } + }) + .iconSize(this.iconSize) + .layoutDirection(SecurityComponentLayoutDirection.HORIZONTAL) + .markAnchor({ x: this.anchorX, y: this.anchorY }) + .offset({ x: this.offsetX, y: 0 }) + .fontSize(this.fontSize) + .fontStyle(this.fontStyle) + .fontWeight(this.fontWeight) + .fontFamily(this.fontFamily) + .fontColor('0xFFFFF000') + .iconColor(this.iconColor) + .backgroundColor(this.bgColor) + .borderStyle(this.borderSty) + .borderWidth(this.borderWid) + .borderColor(this.borderCol) + .borderRadius(this.borderRad) + .padding({ left: this.left, right: this.right, top: this.top, bottom: this.bottom }) + .textIconSpace(this.middle) + .key("keySave8") + }.width('100%').height(this.heightValue).margin(this.marginValue) + } + } +} diff --git a/test/security_component/entry/src/main/ets/TestAbility/TestAbility.ts b/test/security_component/entry/src/main/ets/TestAbility/TestAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..368bbfc95338f58f24c4854f8ce6157fcc4af5f9 --- /dev/null +++ b/test/security_component/entry/src/main/ets/TestAbility/TestAbility.ts @@ -0,0 +1,50 @@ +/* + * Copyright (c) 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 Ability from '@ohos.app.ability.UIAbility' + +export default class TestAbility extends Ability { + onCreate(want, launchParam) { + console.log('TestAbility onCreate') + } + + onDestroy() { + console.log('TestAbility onDestroy') + } + + onWindowStageCreate(windowStage) { + console.log('TestAbility onWindowStageCreate') + windowStage.loadContent("TestAbility/pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + }); + + globalThis.abilityContext = this.context; + } + + onWindowStageDestroy() { + console.log('TestAbility onWindowStageDestroy') + } + + onForeground() { + console.log('TestAbility onForeground') + } + + onBackground() { + console.log('TestAbility onBackground') + } +}; \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/TestAbility/pages/index.ets b/test/security_component/entry/src/main/ets/TestAbility/pages/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..441f24058499e3ea4c4c3d96a776f02192e02549 --- /dev/null +++ b/test/security_component/entry/src/main/ets/TestAbility/pages/index.ets @@ -0,0 +1,48 @@ +/* + * Copyright (c) 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 router from '@ohos.router'; + +@Entry +@Component +struct Index { + aboutToAppear() { + console.info('TestAbility index aboutToAppear') + } + @State message: string = 'Hello World' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('35%') + .height('5%') + .onClick(()=>{ + }) + } + .width('100%') + } + .height('100%') + } + } \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/TestRunner/OpenHarmonyTestRunner.ts b/test/security_component/entry/src/main/ets/TestRunner/OpenHarmonyTestRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf0d2c2ec3dde78d766e2a564468bfeef97d31ea --- /dev/null +++ b/test/security_component/entry/src/main/ets/TestRunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,79 @@ +// @ts-nocheck +/** + * Copyright (c) 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 TestRunner from '@ohos.application.testRunner' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry' + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +function translateParamsToString(parameters) { + const keySet = new Set([ + '-s class', '-s notClass', '-s suite', '-s it', + '-s level', '-s testType', '-s size', '-s timeout', + '-s dryRun' + ]) + let targetParams = ''; + for (const key in parameters) { + if (keySet.has(key)) { + targetParams = `${targetParams} ${key} ${parameters[key]}` + } + } + return targetParams.trim() +} + +async function onAbilityCreateCallback() { + console.log("onAbilityCreateCallback"); +} + +async function addAbilityMonitorCallback(err: any) { + console.info("addAbilityMonitorCallback : " + JSON.stringify(err)) +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + console.info("OpenHarmonyTestRunner OnPrepare ") + } + + async onRun() { + console.log('OpenHarmonyTestRunner onRun run') + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.MainAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a com.example.securitycomponent.MainAbility' + ' -b ' + abilityDelegatorArguments.bundleName + cmd += ' '+translateParamsToString(abilityDelegatorArguments.parameters) + var debug = abilityDelegatorArguments.parameters["-D"] + if (debug == 'true') + { + cmd += ' -D' + } + console.info('cmd : '+cmd) + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + console.info('executeShellCommand : err : ' + JSON.stringify(err)); + console.info('executeShellCommand : data : ' + d.stdResult); + console.info('executeShellCommand : data : ' + d.exitCode); + }) + console.info('OpenHarmonyTestRunner onRun end') + } +}; \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/List.test.ets b/test/security_component/entry/src/main/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..904320805ee5cd026499cfbf1a409dde2976578e --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/List.test.ets @@ -0,0 +1,28 @@ +/** + * Copyright (c) 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 pasteComponentTest from './PasteComponentTest.test.ets'; +import locationComponentTest from './LocationComponentTest.test.ets'; +import locationComponentTest_1 from './LocationComponentTest_1.test.ets'; +import saveComponentTest from './SaveComponentTest.test.ets'; +import saveComponentTest_1 from './SaveComponentTest_1.test.ets'; + +export default function testsuite() { + pasteComponentTest(); + locationComponentTest(); + locationComponentTest_1(); + saveComponentTest(); + saveComponentTest_1(); +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/LocationComponentTest.test.ets b/test/security_component/entry/src/main/ets/test/LocationComponentTest.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..b1b39baa11151f430d9a2252f6264cc79f6f87fb --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/LocationComponentTest.test.ets @@ -0,0 +1,1927 @@ +/** + * Copyright (c) 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from "@ohos/hypium" +import router from '@ohos.router'; +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON } from '@ohos.UiTest' +import Utils from './Utils'; + +export default function locationComponentTest() { + describe('locationComponentTest', function () { + beforeAll(async function (done) { + let options = { + url: 'MainAbility/pages/locationButton', + } + try { + router.clear(); + let pages = router.getState(); + console.debug("====>locationComponentTest get state success " + JSON.stringify(pages)); + if (!("locationButton" == pages.name)) { + console.debug("====>locationComponentTest get state success " + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.debug("====>locationComponentTest push page success " + JSON.stringify(result)); + } + } catch (err) { + console.error("====>locationComponentTest push page error: " + err); + } + done() + }); + + afterEach(async function () { + await Utils.sleep(1000); + console.debug("====>locationComponentTest after each called"); + }); + + it('Test_Security_Button_Location_0100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0100] START===='); + let strJson = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJson); + expect(obj.$attrs.icon).assertEqual(0); + expect(obj.$attrs.text).assertEqual(0); + expect(obj.$attrs.buttonType).assertEqual(0); + expect(obj.$attrs.iconSize).assertEqual('16.00vp'); + expect(obj.$attrs.layoutDirection).assertEqual(0); + expect(obj.$attrs.position.x).assertEqual('0.00vp'); + expect(obj.$attrs.position.y).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('0.00vp'); + expect(obj.$attrs.offset.x).assertEqual('0.00vp'); + expect(obj.$attrs.offset.y).assertEqual('0.00vp'); + expect(obj.$attrs.fontSize).assertEqual('16.00fp'); + expect(obj.$attrs.fontStyle).assertEqual(0); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Medium'); + expect(obj.$attrs.fontFamily).assertEqual('HarmonyOS Sans'); + expect(obj.$attrs.fontColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.iconColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.backgroundColor).assertEqual('#FF007DFF'); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('0.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('0.00vp'); + expect(obj.$attrs.padding.left).assertEqual('24.00vp'); + expect(obj.$attrs.padding.right).assertEqual('24.00vp'); + expect(obj.$attrs.padding.top).assertEqual('8.00vp'); + expect(obj.$attrs.padding.bottom).assertEqual('8.00vp'); + expect(obj.$attrs.textIconSpace).assertEqual('4.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = async (clickData) => { + console.debug("====>[Test_Security_Button_Location_0100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0100] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + await Utils.sleep(500); + let driver = Driver.create(); + let textComponent = await driver.findComponent(ON.type('Button')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0100] textComponent is:" + JSON.stringify(textComponent)); + await textComponent.click(); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0100] END===="); + done() + } else { + console.debug("====>[Test_Security_Button_Location_0100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0100] END===="); + done() + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": SecurityComponentLayoutDirection.VERTICAL, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.layoutDirection).assertEqual(SecurityComponentLayoutDirection.VERTICAL); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0200] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 150, + "positionY": 20, + "anchorX": 20, + "anchorY": 20, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.position.x).assertEqual('150.00vp'); + expect(obj.$attrs.position.y).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0300] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 1, + "positionX": 0, + "positionY": 0, + "anchorX": 20, + "anchorY": 20, + "offsetX": 100, + "offsetY": 100, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('100.00vp'); + expect(obj.$attrs.offset.y).assertEqual('100.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0400] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Italic, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontStyle).assertEqual(1); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0500] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0500] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Lighter, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Lighter'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0600] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Normal, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Normal'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0700] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Regular, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Regular'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0800] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_0900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_0900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bold, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_0900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bold'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_0900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_0900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_0900] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_0900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_0900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_0900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_0900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_0900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bolder, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bolder'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_1000] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1000] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dotted, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(2); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_1100] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_1200] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Solid, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(0); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_1300] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1400] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1400] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": -200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('-200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1500] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1500] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1500] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 150, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('150.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1600] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1600] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0x10ff0000, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#10FF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1700] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1700] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 20, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xfffa0050, + "bgColor": 0xffff0000, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.buttonType).assertEqual(0); + expect(obj.$attrs.iconSize).assertEqual('20.00vp'); + expect(obj.$attrs.iconColor).assertEqual('#FFFA0050'); + expect(obj.$attrs.backgroundColor).assertEqual('#FFFF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1800] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1800] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_1900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_1900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 1, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_1900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('1.00vp'); + expect(obj.$attrs.fontSize).assertEqual('20.00fp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_1900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_1900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_1900] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_1900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_1900] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_1900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_1900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_1900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": Color.Transparent, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_2000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_2000] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2000] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": Color.Transparent, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_2100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_2100] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2100] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": Color.Transparent, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Location_2200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.backgroundColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Location_2200] ERR CASE 成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2200] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + }) +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/LocationComponentTest_1.test.ets b/test/security_component/entry/src/main/ets/test/LocationComponentTest_1.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..dad8ed8b0da2928e5df703c4345e2dac7d1086fe --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/LocationComponentTest_1.test.ets @@ -0,0 +1,490 @@ +/** + * Copyright (c) 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from "@ohos/hypium" +import router from '@ohos.router'; +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON } from '@ohos.UiTest' +import Utils from './Utils'; + +export default function locationComponentTest_1() { + describe('locationComponentTest_1', function () { + beforeAll(async function (done) { + let options = { + url: 'MainAbility/pages/locationButton_1', + } + try { + router.clear(); + let pages = router.getState(); + console.debug("====>locationComponentTest_1 get state success " + JSON.stringify(pages)); + if (!("locationButton_1" == pages.name)) { + console.debug("====>locationComponentTest_1 get state success " + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.debug("====>locationComponentTest_1 push page success " + JSON.stringify(result)); + } + } catch (err) { + console.error("====>locationComponentTest_1 push page error: " + err); + } + done() + }); + + afterEach(async function () { + await Utils.sleep(1000); + console.debug("====>locationComponentTest_1 after each called"); + }); + + it('Test_Security_Button_Location_2300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2300] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation2'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.icon:" + obj.$attrs.icon); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.icon).assertEqual(1); + expect(obj.$attrs.text).assertEqual(1); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2300] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2300] button is:" + JSON.stringify(button)); + await button[0].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2400] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation3'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(2); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2400] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2500] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation4'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(3); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2500] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2500] button is:" + JSON.stringify(button)); + await button[2].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2600] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation5'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(4); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2600] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2600] button is:" + JSON.stringify(button)); + await button[3].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2700] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation6'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(5); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2700] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2700] button is:" + JSON.stringify(button)); + await button[4].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2800] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation7'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(6); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2800] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2800] button is:" + JSON.stringify(button)); + await button[5].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_2900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_2900] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation8'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(7); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_2900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_2900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_2900] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_2900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_2900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_2900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_2900] button is:" + JSON.stringify(button)); + await button[6].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_2900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_3000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_3000] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation9'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(8); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_3000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_3000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_3000] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_3000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_3000] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_3000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_3000] button is:" + JSON.stringify(button)); + await button[7].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_3100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_3100] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation10'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(9); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_3100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_3100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_3100] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_3100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_3100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_3100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_3100] button is:" + JSON.stringify(button)); + await button[8].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Location_3200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Location_3200] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyLocation11'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(10); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Location_3200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Location_3200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Location_3200] 设置权限成功"); + expect(clickData.data.clickResult == LocationButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Location_3200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Location_3200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Location_3200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('LocationButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Location_3200] button is:" + JSON.stringify(button)); + await button[9].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Location_3200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + }) +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/PasteComponentTest.test.ets b/test/security_component/entry/src/main/ets/test/PasteComponentTest.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..fbf134d308213e46692d5ade3b39e248bca65076 --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/PasteComponentTest.test.ets @@ -0,0 +1,1923 @@ +/** + * Copyright (c) 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from "@ohos/hypium" +import router from '@ohos.router'; +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON } from '@ohos.UiTest' +import Utils from './Utils'; + +export default function pasteComponentTest() { + describe('pasteComponentTest', function () { + beforeAll(async function (done) { + let options = { + url: 'MainAbility/pages/pasteButton', + } + try { + router.clear(); + let pages = router.getState(); + console.debug("====>pasteComponentTest get state success " + JSON.stringify(pages)); + if (!("pasteButton" == pages.name)) { + console.debug("====>pasteComponentTest get state success " + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.debug("====>pasteComponentTest push page success " + JSON.stringify(result)); + } + } catch (err) { + console.error("====>pasteComponentTest push page error: " + err); + } + done() + }); + + afterEach(async function () { + await Utils.sleep(1000); + console.debug("====>pasteComponentTest after each called"); + }); + + it('Test_Security_Button_Paste_0100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0100] START'); + let strJson = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJson); + expect(obj.$attrs.icon).assertEqual(0); + expect(obj.$attrs.text).assertEqual(0); + expect(obj.$attrs.buttonType).assertEqual(0); + expect(obj.$attrs.iconSize).assertEqual('16.00vp'); + expect(obj.$attrs.layoutDirection).assertEqual(0); + expect(obj.$attrs.position.x).assertEqual('0.00vp'); + expect(obj.$attrs.position.y).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('0.00vp'); + expect(obj.$attrs.offset.x).assertEqual('0.00vp'); + expect(obj.$attrs.offset.y).assertEqual('0.00vp'); + expect(obj.$attrs.fontSize).assertEqual('16.00fp'); + expect(obj.$attrs.fontStyle).assertEqual(0); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Medium'); + expect(obj.$attrs.fontFamily).assertEqual('HarmonyOS Sans'); + expect(obj.$attrs.fontColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.iconColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.backgroundColor).assertEqual('#FF007DFF'); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('0.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('0.00vp'); + expect(obj.$attrs.padding.left).assertEqual('24.00vp'); + expect(obj.$attrs.padding.right).assertEqual('24.00vp'); + expect(obj.$attrs.padding.top).assertEqual('8.00vp'); + expect(obj.$attrs.padding.bottom).assertEqual('8.00vp'); + expect(obj.$attrs.textIconSpace).assertEqual('4.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = async (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0100] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0100] END===="); + done() + } else { + console.debug("====>[Test_Security_Button_Paste_0100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0100] END===="); + done() + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + + it('Test_Security_Button_Paste_0200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": SecurityComponentLayoutDirection.VERTICAL, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.layoutDirection).assertEqual(SecurityComponentLayoutDirection.VERTICAL); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0200] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 150, + "positionY": 20, + "anchorX": 20, + "anchorY": 20, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.position.x).assertEqual('150.00vp'); + expect(obj.$attrs.position.y).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0300] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + + it('Test_Security_Button_Paste_0400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 1, + "positionX": 0, + "positionY": 0, + "anchorX": 20, + "anchorY": 20, + "offsetX": 100, + "offsetY": 100, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('100.00vp'); + expect(obj.$attrs.offset.y).assertEqual('100.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0400] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Italic, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontStyle).assertEqual(1); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0500] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0500] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Lighter, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Lighter'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0600] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Normal, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Normal'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0700] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Regular, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Regular'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0800] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_0900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_0900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bold, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_0900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bold'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_0900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_0900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_0900] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_0900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_0900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_0900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_0900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_0900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bolder, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bolder'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_1000] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1000] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dotted, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(2); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_1100] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_1200] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Solid, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(0); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Paste_1300] 设置权限成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1400] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1400] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": -200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('-200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1500] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1500] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1500] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 150, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('150.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1600] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1600] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0x10ff0000, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#10FF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1700] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1700] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 20, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xfffa0050, + "bgColor": 0xffff0000, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.buttonType).assertEqual(0); + expect(obj.$attrs.iconSize).assertEqual('20.00vp'); + expect(obj.$attrs.iconColor).assertEqual('#FFFA0050'); + expect(obj.$attrs.backgroundColor).assertEqual('#FFFF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1800] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1800] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_1900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_1900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 1, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_1900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('1.00vp'); + expect(obj.$attrs.fontSize).assertEqual('20.00fp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_1900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_1900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_1900] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_1900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_1900] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_1900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_1900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_1900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_2000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_2000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor":Color.Transparent, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_2000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_2000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_2000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_2000] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_2000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_2000] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_2000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_2000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_2100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_2100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": Color.Transparent, + "iconColor":0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_2100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_2100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_2100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_2100] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_2100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_2100] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_2100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_2100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Paste_2200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Paste_2200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor":0xffffffff, + "bgColor": Color.Transparent, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Paste_2200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keyPaste'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.backgroundColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Paste_2200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Paste_2200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Paste_2200] ERR CASE 成功"); + expect(clickData.data.clickResult == PasteButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Paste_2200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Paste_2200] ERR CASE 失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Paste_2200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('PasteButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Paste_2200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Paste_2200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + }) +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/SaveComponentTest.test.ets b/test/security_component/entry/src/main/ets/test/SaveComponentTest.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..112b6bbacfb32d7fa30214e4065fc21d7a8b0828 --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/SaveComponentTest.test.ets @@ -0,0 +1,1926 @@ +/** + * Copyright (c) 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from "@ohos/hypium" +import router from '@ohos.router'; +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON } from '@ohos.UiTest' +import Utils from './Utils'; + +export default function saveComponentTest() { + describe('saveComponentTest', function () { + beforeAll(async function (done) { + let options = { + url: 'MainAbility/pages/saveButton', + } + try { + router.clear(); + let pages = router.getState(); + console.debug("====>saveComponentTest get state success " + JSON.stringify(pages)); + if (!("saveButton" == pages.name)) { + console.debug("====>saveComponentTest get state success " + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.debug("====>saveComponentTest push page success " + JSON.stringify(result)); + } + } catch (err) { + console.error("====>saveComponentTest push page error: " + err); + } + done() + }); + + afterEach(async function () { + await Utils.sleep(1000); + console.debug("====>saveComponentTest after each called"); + }); + + it('Test_Security_Button_Save_0100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0100] START===='); + let strJson = getInspectorByKey('keySave'); + let obj = JSON.parse(strJson); + expect(obj.$attrs.icon).assertEqual(0); + expect(obj.$attrs.text).assertEqual(0); + expect(obj.$attrs.buttonType).assertEqual(0); + expect(obj.$attrs.iconSize).assertEqual('16.00vp'); + expect(obj.$attrs.layoutDirection).assertEqual(0); + expect(obj.$attrs.position.x).assertEqual('0.00vp'); + expect(obj.$attrs.position.y).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('0.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('0.00vp'); + expect(obj.$attrs.offset.x).assertEqual('0.00vp'); + expect(obj.$attrs.offset.y).assertEqual('0.00vp'); + expect(obj.$attrs.fontSize).assertEqual('16.00fp'); + expect(obj.$attrs.fontStyle).assertEqual(0); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Medium'); + expect(obj.$attrs.fontFamily).assertEqual('HarmonyOS Sans'); + expect(obj.$attrs.fontColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.iconColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.backgroundColor).assertEqual('#FF007DFF'); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('0.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('0.00vp'); + expect(obj.$attrs.padding.left).assertEqual('24.00vp'); + expect(obj.$attrs.padding.right).assertEqual('24.00vp'); + expect(obj.$attrs.padding.top).assertEqual('8.00vp'); + expect(obj.$attrs.padding.bottom).assertEqual('8.00vp'); + expect(obj.$attrs.textIconSpace).assertEqual('4.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = async (clickData) => { + console.debug("====>[Test_Security_Button_Save_0100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0100] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + await Utils.sleep(500); + let driver = Driver.create(); + let textComponent = await driver.findComponent(ON.type('Button')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0100] textComponent is:" + JSON.stringify(textComponent)); + await textComponent.click(); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0100] END===="); + done() + } else { + console.debug("====>[Test_Security_Button_Save_0100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0100] END===="); + done() + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": SecurityComponentLayoutDirection.VERTICAL, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.layoutDirection).assertEqual(SecurityComponentLayoutDirection.VERTICAL); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0200] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 150, + "positionY": 20, + "anchorX": 20, + "anchorY": 20, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.position.x).assertEqual('150.00vp'); + expect(obj.$attrs.position.y).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0300] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 1, + "positionX": 0, + "positionY": 0, + "anchorX": 20, + "anchorY": 20, + "offsetX": 100, + "offsetY": 100, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('100.00vp'); + expect(obj.$attrs.offset.y).assertEqual('100.00vp'); + expect(obj.$attrs.markAnchor.x).assertEqual('20.00vp'); + expect(obj.$attrs.markAnchor.y).assertEqual('20.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0400] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Italic, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontStyle).assertEqual(1); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0500] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0500] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Lighter, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Lighter'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0600] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Normal, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Normal'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0700] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Regular, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Regular'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0800] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_0900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_0900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bold, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_0900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bold'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_0900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_0900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_0900] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_0900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_0900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_0900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_0900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_0900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Bolder, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontWeight).assertEqual('FontWeight.Bolder'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_1000] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1000] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dotted, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(2); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_1100] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(1); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_1200] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1300] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Solid, + "borderWid": 5, + "borderCol": 0xffffffff, + "borderRad": 5, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1300] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1300] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.borderStyle).assertEqual(0); + expect(obj.$attrs.borderWidth).assertEqual('5.00vp'); + expect(obj.$attrs.borderColor).assertEqual('#FFFFFFFF'); + expect(obj.$attrs.borderRadius).assertEqual('5.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_1300] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1300] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1400] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1400] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1400] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1400] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1500] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": -200, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1500] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1500] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave1'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.offset.x).assertEqual('-200.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1500] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1500] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1600] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 150, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1600] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1600] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('150.00vp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1600] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1600] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1700] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0x10ff0000, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1700] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1700] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#10FF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1700] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1700] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1800] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 20, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xfffa0050, + "bgColor": 0xffff0000, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1800] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1800] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('20.00vp'); + expect(obj.$attrs.iconColor).assertEqual('#FFFA0050'); + expect(obj.$attrs.backgroundColor).assertEqual('#FFFF0000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1800] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1800] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_1900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_1900] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 1, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_1900] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1900] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconSize).assertEqual('1.00vp'); + expect(obj.$attrs.fontSize).assertEqual('20.00fp'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_1900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_1900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_1900] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_1900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_1900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_1900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_1900] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_1900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2000', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2000] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": Color.Transparent, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_2000] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2000] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.iconColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2000] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2000] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_2000] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2000] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2000] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2000] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2000] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2000] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2000] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2100', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2100] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 16, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": Color.Transparent, + "iconColor": 0xffffffff, + "bgColor": 0xff007dff, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_2100] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2100] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.fontColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2100] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2100] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_2100] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2100] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2100] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2100] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2100] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2100] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2100] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2200', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2200] START===='); + await Utils.sleep(1000); + try { + var eventData = { + data: { + "icon": 0, + "textType": 0, + "bgType": ButtonType.Normal, + "iconSize": 16, + "direct": 0, + "positionX": 0, + "positionY": 0, + "anchorX": 0, + "anchorY": 0, + "offsetX": 0, + "offsetY": 0, + "fontSize": 20, + "fontStyle": FontStyle.Normal, + "fontWeight": FontWeight.Medium, + "fontFamily": 'HarmonyOS Sans', + "fontColor": 0xffffffff, + "iconColor": 0xffffffff, + "bgColor": Color.Transparent, + "borderSty": BorderStyle.Dashed, + "borderWid": 0, + "borderCol": 0xffffffff, + "borderRad": 0, + "left": 24, + "right": 24, + "top": 8, + "bottom": 8, + "middle": 4 + } + } + var innerEvent = { + eventId: 1, + priority: events_emitter.EventPriority.LOW + } + console.debug("====>[Test_Security_Button_Save_2200] start to publish emit"); + events_emitter.emit(innerEvent, eventData); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2200] change component data error: " + err.message); + } + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave'); + let obj = JSON.parse(strJsonNew); + expect(obj.$attrs.backgroundColor).assertEqual('#00000000'); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2200] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2200] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED) { + console.debug("====>[Test_Security_Button_Save_2200] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.TEMPORARY_AUTHORIZATION_FAILED).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2200] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2200] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2200] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2200] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2200] button is:" + JSON.stringify(button)); + await button.click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2200] clickSecComponent err : " + JSON.stringify(err)); + } + }); + }) +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/SaveComponentTest_1.test.ets b/test/security_component/entry/src/main/ets/test/SaveComponentTest_1.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..6ac33ad30eb4b4f1984f1dbb689d9d2bc19afd20 --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/SaveComponentTest_1.test.ets @@ -0,0 +1,358 @@ +/** + * Copyright (c) 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from "@ohos/hypium" +import router from '@ohos.router'; +import events_emitter from '@ohos.events.emitter'; +import { Driver, ON } from '@ohos.UiTest' +import Utils from './Utils'; + +export default function saveComponentTest_1() { + describe('saveComponentTest_1', function () { + beforeAll(async function (done) { + let options = { + url: 'MainAbility/pages/saveButton_1', + } + try { + router.clear(); + let pages = router.getState(); + console.debug("====>saveComponentTest_1 get state success " + JSON.stringify(pages)); + if (!("saveButton_1" == pages.name)) { + console.debug("====>saveComponentTest_1 get state success " + JSON.stringify(pages.name)); + let result = await router.pushUrl(options); + await Utils.sleep(2000); + console.debug("====>saveComponentTest_1 push page success " + JSON.stringify(result)); + } + } catch (err) { + console.error("====>saveComponentTest_1 push page error: " + err); + } + done() + }); + + afterEach(async function () { + await Utils.sleep(1000); + console.debug("====>saveComponentTest_1 after each called"); + }); + + it('Test_Security_Button_Save_2300', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2300] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave2'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.icon:" + obj.$attrs.icon); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.icon).assertEqual(1); + expect(obj.$attrs.text).assertEqual(1); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2300] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2300] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2300] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2300] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2300] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2300] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2300] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2300] button is:" + JSON.stringify(button)); + await button[0].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2300] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2400', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2400] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave3'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(2); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2400] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2400] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2400] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2400] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2400] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2400] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2400] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2400] button is:" + JSON.stringify(button)); + await button[1].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2400] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2500', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2500] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave4'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(3); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2500] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2500] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2500] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2500] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2500] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2500] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2500] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2500] button is:" + JSON.stringify(button)); + await button[2].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2500] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2600', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2600] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave5'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(4); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2600] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2600] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2600] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2600] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2600] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2600] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2600] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2600] button is:" + JSON.stringify(button)); + await button[3].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2600] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2700', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2700] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave6'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(5); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2700] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2700] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2700] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2700] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2700] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2700] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2700] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2700] button is:" + JSON.stringify(button)); + await button[4].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2700] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2800', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2800] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave7'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(6); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2800] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2800] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2800] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2800] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2800] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2800] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2800] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2800] button is:" + JSON.stringify(button)); + await button[5].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2800] clickSecComponent err : " + JSON.stringify(err)); + } + }); + + it('Test_Security_Button_Save_2900', 0, async function (done) { + console.debug('====>[Test_Security_Button_Save_2900] START===='); + await Utils.sleep(1000); + let strJsonNew = getInspectorByKey('keySave8'); + let obj = JSON.parse(strJsonNew); + console.debug("====>component obj.$attrs.text:" + obj.$attrs.text); + expect(obj.$attrs.text).assertEqual(7); + await Utils.sleep(1000); + try { + let clickCallback = (clickData) => { + console.debug("====>[Test_Security_Button_Save_2900] get clickEvent result is: " + JSON.stringify(clickEvent)); + console.debug("====>[Test_Security_Button_Save_2900] get clickData.data.clickResult is: " + JSON.stringify(clickData.data.clickResult)); + if (clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS) { + console.debug("====>[Test_Security_Button_Save_2900] 设置权限成功"); + expect(clickData.data.clickResult == SaveButtonOnClickResult.SUCCESS).assertTrue(); + console.debug("====>[Test_Security_Button_Save_2900] END===="); + done(); + } else { + console.debug("====>[Test_Security_Button_Save_2900] 设置权限失败"); + expect().assertFail() + console.debug("====>[Test_Security_Button_Save_2900] END===="); + done(); + } + } + var clickEvent = { + eventId: 2, + priority: events_emitter.EventPriority.LOW + } + events_emitter.once(clickEvent, clickCallback); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2900] once clickEvent err : " + JSON.stringify(err)); + } + try { + let driver = Driver.create(); + let button = await driver.findComponents(ON.type('SaveButton')); + await Utils.sleep(500); + console.debug("====>[Test_Security_Button_Save_2900] button is:" + JSON.stringify(button)); + await button[6].click(); + await Utils.sleep(1000); + } catch (err) { + console.debug("====>[Test_Security_Button_Save_2900] clickSecComponent err : " + JSON.stringify(err)); + } + }); + }) +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/ets/test/Utils.ets b/test/security_component/entry/src/main/ets/test/Utils.ets new file mode 100644 index 0000000000000000000000000000000000000000..bb1f4a49ebf2db8543071ec5999d44fff08a94d1 --- /dev/null +++ b/test/security_component/entry/src/main/ets/test/Utils.ets @@ -0,0 +1,118 @@ +// @ts-nocheck +/** + * Copyright (c) 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. + */ + +export default class Utils { + static rect_left; + static rect_top; + static rect_right; + static rect_bottom; + static rect_value; + + static sleep(time) { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve() + }, time) + }).then(() => { + console.info(`sleep ${time} over...`) + }) + } + + static getComponentRect(key) { + let strJson = getInspectorByKey(key); + let obj = JSON.parse(strJson); + console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj)); + let rectInfo = JSON.parse('[' + obj.$rect + ']') + console.info("[getInspectorByKey] rectInfo is: " + rectInfo); + this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0] + this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1] + this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0] + this.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1] + return this.rect_value = { + "left": this.rect_left, "top": this.rect_top, "right": this.rect_right, "bottom": this.rect_bottom + } + } + + static async swipe(downX, downY, upX, upY, steps) { + console.info('start to swipe') + this.drags(downX, downY, upX, upY, steps, false) + } + + static async drag(downX, downY, upX, upY, steps) { + console.info('start to drag') + this.drags(downX, downY, upX, upY, steps, true) + } + + static async drags(downX, downY, upX, upY, steps, drag) { + var xStep; + var yStep; + var swipeSteps; + var ret; + xStep = 0; + yStep = 0; + ret = false; + swipeSteps = steps; + if (swipeSteps == 0) { + swipeSteps = 1; + } + xStep = (upX - downX) / swipeSteps; + yStep = (upY - downY) / swipeSteps; + console.info('move step is: ' + 'xStep: ' + xStep + ' yStep: ' + yStep) + var downPonit: TouchObject = { + id: 1, + x: downX, + y: downY, + type: TouchType.Down, + } + console.info('down touch started: ' + JSON.stringify(downPonit)) + sendTouchEvent(downPonit); + console.info('start to move') + if (drag) { + await this.sleep(500) + } + for (var i = 1;i <= swipeSteps; i++) { + var movePoint: TouchObject = { + id: 1, + x: downX + (xStep * i), + y: downY + (yStep * i), + type: TouchType.Move + } + console.info('move touch started: ' + JSON.stringify(movePoint)) + ret = sendTouchEvent(movePoint) + if (ret == false) { + break; + } + await this.sleep(5) + } + console.info('start to up') + if (drag) { + await this.sleep(100) + } + var upPoint: TouchObject = { + id: 1, + x: upX, + y: upY, + type: TouchType.Up, + } + console.info('up touch started: ' + JSON.stringify(upPoint)) + sendTouchEvent(upPoint) + await this.sleep(500) + } +} + + + + diff --git a/test/security_component/entry/src/main/module.json b/test/security_component/entry/src/main/module.json new file mode 100644 index 0000000000000000000000000000000000000000..0db2097afeb7deb0c5107a0b327ba7ce20522e48 --- /dev/null +++ b/test/security_component/entry/src/main/module.json @@ -0,0 +1,46 @@ +{ + "module": { + "name": "phone", + "type": "entry", + "srcEntrance": "./ets/Application/AbilityStage.ts", + "description": "$string:phone_entry_dsc", + "mainElement": "MainAbility", + "deviceTypes": [ + "tablet", + "default", + "phone", + "2in1" + ], + "deliveryWithInstall": true, + "installationFree": false, + "uiSyntax": "ets", + "pages": "$profile:main_pages", + "metadata": [ + { + "name": "ArkTSPartialUpdate", + "value": "true" + } + ], + "abilities": [ + { + "name": "com.example.securitycomponent.MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:phone_entry_main", + "icon": "$media:icon", + "label": "$string:entry_label", + "visible": true, + "orientation": "portrait", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/resources/base/element/color.json b/test/security_component/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..07a14d2b8dcf50dae012854d8310c489dfd7391c --- /dev/null +++ b/test/security_component/entry/src/main/resources/base/element/color.json @@ -0,0 +1,12 @@ +{ + "color": [ + { + "name": "color_hello", + "value": "#ffff0000" + }, + { + "name": "color_world", + "value": "#ff0000ff" + } + ] +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/resources/base/element/float.json b/test/security_component/entry/src/main/resources/base/element/float.json new file mode 100644 index 0000000000000000000000000000000000000000..26a0491a2b293d8296d4de4d55c8d682527b6c6b --- /dev/null +++ b/test/security_component/entry/src/main/resources/base/element/float.json @@ -0,0 +1,12 @@ +{ + "float":[ + { + "name":"font_hello", + "value":"28.0fp" + }, + { + "name":"font_world", + "value":"20.0fp" + } + ] +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/resources/base/element/string.json b/test/security_component/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..f9f9529435996599eaf1069ead7cb6f832f34968 --- /dev/null +++ b/test/security_component/entry/src/main/resources/base/element/string.json @@ -0,0 +1,60 @@ +{ + "string": [ + { + "name": "entry_MainAbility", + "value": "entry_MainAbility" + }, + { + "name": "description_mainability", + "value": "ETS_Empty Ability" + }, + { + "name": "TestAbility_desc", + "value": "description" + }, + { + "name": "TestAbility_label", + "value": "label" + }, + { + "name":"string_hello", + "value":"Hello" + }, + { + "name":"string_world", + "value":"World" + }, + { + "name":"message_arrive", + "value":"We will arrive at %s." + }, + { + "name": "phone_entry_dsc", + "value": "i am an entry for phone" + }, + { + "name": "phone_entry_main", + "value": "the phone entry ability" + }, + { + "name": "entry_label", + "value": "ActsContextTest" + }, + { + "name": "form_description", + "value": "my form" + }, + { + "name": "serviceability_description", + "value": "my whether" + }, + { + "name": "description_application", + "value": "demo for test" + }, + { + "name": "app_name", + "value": "Demo" + } + ] +} \ No newline at end of file diff --git a/test/security_component/entry/src/main/resources/base/media/icon.png b/test/security_component/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/test/security_component/entry/src/main/resources/base/media/icon.png differ diff --git a/test/security_component/entry/src/main/resources/base/profile/main_pages.json b/test/security_component/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..edbffe608c130bd5f11cccb7c10a74f0b472d154 --- /dev/null +++ b/test/security_component/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,10 @@ +{ + "src": [ + "MainAbility/pages/index/index", + "MainAbility/pages/pasteButton", + "MainAbility/pages/locationButton", + "MainAbility/pages/locationButton_1", + "MainAbility/pages/saveButton", + "MainAbility/pages/saveButton_1" + ] +} \ No newline at end of file diff --git a/test/security_component/signature/openharmony_sx.p7b b/test/security_component/signature/openharmony_sx.p7b new file mode 100644 index 0000000000000000000000000000000000000000..91a332fc135b8a7ecb91d161d7d11d672584c448 Binary files /dev/null and b/test/security_component/signature/openharmony_sx.p7b differ